![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Kuo Yiching
Fork of iot_example by
Diff: main.cpp
- Revision:
- 3:06080fa094a0
- Parent:
- 2:b10925c474fc
- Child:
- 4:46e5e96a6233
--- a/main.cpp Tue Nov 07 04:09:57 2017 +0000 +++ b/main.cpp Mon Nov 13 20:25:48 2017 +0800 @@ -10,26 +10,61 @@ #include "mbed.h" #include "esp8266.h" - - -Serial ser2usb(USBTX, USBRX); +Serial ser2usb(PA_9, PA_10, 115200); +DigitalOut LED(PD_2); int main(void) { // 选定与 esp8266 相连接的串口,WiFi 名称和密码 // 参数分别为 TX pin / RX pin / SSID / Password - Esp8266 client(PC_10, PC_11, "TSINGHUA.iCenter", "TS.icenter"); - client.connect_mqtt_broker("tdxls-iot.xicp.net"); + // Esp8266 client(PA_2, PA_3, "TSINGHUA.iCenter", "TS.icenter"); + Esp8266 client(PA_2, PA_3, "cqtest_mi", "wifipassword1611"); + + //声明所有的传感器,每行一个,每个由名字、单位两部分组成,最后一行必须为空指针作为结尾 + //服务器收到声明后,将在网页上显示这些传感器 + const char* sensors[][2] = { + "pressure", "Pa", + "temperature", "C", + "humidity", "%", + NULL, NULL //最后一行以空指针作为结束标记 + }; + + //声明所有的执行器,每行一个,每个由名字、参数类型两部分组成,最后一行必须为空指针作为结尾 + //服务器收到声明后,将在网页上显示这些执行器 + const char* actuators[][2] = { + "switch1", "int", + "switch2", "int", + NULL, NULL //最后一行以空指针作为结束标记 + }; + + //连接到服务器 + client.connect_mqtt_broker("tdxls-iot.xicp.net", sensors, actuators); + ser2usb.printf("Initialization done.\r\n"); - + + char actuator_name[32], control_value[32]; + float last_report=0; + Timer t;// 定时器用于计量发送传感器数据的时间 + t.start(); + while(1) { - client.publish("pressure", "12345"); - wait(1); - //char buf[32]; - //client.subscribe_poll("/icenter", buf, 32); - //ser2esp8266.attach(simple_callback, Serial::RxIrq); - //ser2usb.printf("%s\r\n", esp_paramBuf); - //ser2usb.printf("loop\r\n"); - //ser2usb.printf("haha\n"); - //while(1); + //检查有没有收到新的执行器控制指令 + if(client.get_control_cmd(actuator_name, control_value)){ + ser2usb.printf("Received CMD %s, %s\r\n", actuator_name, control_value); + //判断哪个执行器收到命令 + if(strcmp(actuator_name, "switch1")){ + //do something for switch1 + LED = atoi(control_value); + }else if(strcmp(actuator_name, "switch2")){ + //do something for switch2 + } + } + + if(t.read() - last_report > 1){ // 每1s发送汇报一次传感器数据 + + //汇报传感器数据,两个参数分别是传感器名字和值 + client.publish_value("pressure", "100000 Pa"); + client.publish_value("temperature", "20 C"); + client.publish_value("humidity", "30 %"); + } } }