init

Dependencies:   mbed

Fork of 仓库 by Keegan Hu

main.cpp

Committer:
zhangyx
Date:
2017-11-15
Revision:
5:9a0acd11c445
Parent:
4:46e5e96a6233
Child:
7:49a823b5a935

File content as of revision 5:9a0acd11c445:

/*-----------------------------------------------------
 File Name : main.cpp
 Purpose : For esp8266 mbed porting
 Creation Date : 22-06-2017
 Last Modified :
 Created By : Jeasine Ma [jeasinema[at]gmail[dot]com]
-----------------------------------------------------*/
#include <cstdarg>
#include <cstring>
#include "mbed.h"
#include "esp8266.h"

Serial ser2usb(PA_9, PA_10, 115200);
DigitalOut LED(PD_2);

int main(void) {
    // 选定与 esp8266 相连接的串口,WiFi 名称和密码
    // 参数分别为 TX pin / RX pin / SSID / Password
    Esp8266 client(PA_2, PA_3, "TSINGHUA.iCenter", "TS.icenter");

    //声明所有的传感器,每行一个,每个由名字、单位两部分组成,最后一行必须为空指针作为结尾
    //服务器收到声明后,将在网页上显示这些传感器
    const char* sensors[][2] = {
        "pressure", "Pa",
        "temperature", "C",
        "humidity", "%",
        NULL, NULL //最后一行以空指针作为结束标记
    };

    //声明所有的执行器,每行一个,每个由名字、参数类型两部分组成,最后一行必须为空指针作为结尾
    //服务器收到声明后,将在网页上显示这些执行器
    const char* actuators[][2] = {
        "servo1", "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) {
        //检查有没有收到新的执行器控制指令
        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 %");
            
            last_report = t.read();
        }
    }
}