Xiaoyuan Yu
/
Ex_esp8266
for high school students
Diff: main.cpp
- Revision:
- 0:4c6832694c5e
diff -r 000000000000 -r 4c6832694c5e main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Sep 14 07:55:51 2018 +0000 @@ -0,0 +1,67 @@ +#include "mbed.h" +#include "esp8266.h" +/********** + * 订阅和发布地址格式 + * 订阅主题/control/device/actuators + * 发布主题/values/device/sensors +**********/ + + +Serial ser2usb(PA_2, PA_3); + +//声明设备名称,用于订阅和发布消息 +const char device[] = "warehouse"; + +//声明所有传感器, 每行一个, 每个由名字单位两部分组成 +const char* sensors[][2] = { + "report", "", + NULL, NULL //last line must end with empty pointer +}; + +//声明所有执行器, 每行一个, 每个由名字参数类型两部分组成 +const char* actuators[][2] = { + "command", "", + "dat", "", + NULL, NULL //last line must end with empty pointer +}; + + +int main() +{ + ser2usb.baud(115200); + // connect to wifi + ser2usb.printf("Initializing...\r\n"); + Esp8266 client(PA_9, PA_10, "iot_b827eb8fb527", "7c02b50b");// TX pin / RX pin / SSID / Password + + // connect to server + ser2usb.printf("connecting to mqtt server...\r\n"); + client.connect_mqtt_broker("192.168.12.1", device, sensors, actuators); + + //subscribe topic + client.subscribe_control(actuators[0][0]); + client.subscribe_control(actuators[1][0]); + + // done report + ser2usb.printf("Initialization done.\r\n"); + + // declare buff + char actuator_name[32], control_value[32]; + + // main function + while (1) + { + // looking for new command + if (client.get_control_cmd(actuator_name, control_value)) + { + ser2usb.printf("Received %s %s\r\n", actuator_name, control_value); + if (strcmp(actuator_name, "command") == 0) + { + client.publish_value("report", "received_a_command"); + } + else if (strcmp(actuator_name, "dat") == 0) + { + client.publish_value("report", "received_a_data"); + } + } + } +}