CHANG rozen / Mbed 2 deprecated IDW01M1-MQTT

Dependencies:   MQTT NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "BME280.hpp"
00003 #include "SpwfInterface.h"
00004 #include "TCPSocket.h"
00005 #include "MQTTClient.h"
00006 #include "MQTTWiFi.h"
00007 
00008 // MQTT use
00009 #define MQTT_MAX_PACKET_SIZE 250
00010 #define MQTT_MAX_PAYLOAD_SIZE 300
00011 //Configuration value needed to connect Red-node
00012 #define BROKER_URL "192.168.0.10";
00013 #define MQTT_PORT 1883
00014 //MQTT use Topic 
00015 #define TOPIC "temp"
00016 #define SUB_TOPIC "LED"
00017 
00018 
00019 //Wifi network
00020 #define SSID "megu megu fire"
00021 #define PASSW "66666667"
00022 
00023 DigitalOut myled(LED1);
00024 BME280 bmpSensor;
00025 
00026 int connack_rc = 0;    // MQTT connack return code
00027 const char * ip_addr = "";
00028 char *host_addr = "";
00029 bool netConnecting = false;
00030 int connectTimeout = 1000;
00031 bool mqttConnecting = false;
00032 bool netConnected = false;
00033 bool connected = false;
00034 int retryAttempt = 0;
00035 char subscription_url[MQTT_MAX_PAYLOAD_SIZE];
00036 
00037 MQTT::Message message;
00038 MQTTString TopicName={TOPIC};
00039 MQTT::MessageData MsgData(TopicName, message);
00040 
00041 void subscribe_LED(char* msg){
00042     int value = atoi(msg);
00043     //printf("value = %d\n", value);
00044     if(value ==1){
00045         myled = !myled;
00046     }
00047     
00048 }
00049 
00050 
00051 void subscribe_cb(MQTT::MessageData & msgMQTT) {
00052     char msg[MQTT_MAX_PAYLOAD_SIZE];
00053     msg[0]='\0';
00054     strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen);
00055     printf ("--->>> subscribe_cb msg: %s\n\r", msg);
00056     subscribe_LED(msg);
00057 }
00058 int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
00059 {
00060     char* pubTopic = SUB_TOPIC;    
00061     return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb);
00062 }
00063 
00064 
00065 int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
00066     const char* host = BROKER_URL;
00067 
00068     char hostname[strlen(host) + 1];
00069     sprintf(hostname,"%s", host);
00070 
00071     SpwfSAInterface& WiFi = ipstack->getWiFi();
00072 
00073     //Network Debug statements
00074     LOG("=====================================\n\r");
00075     LOG("Connecting WiFi.\n\r");
00076     LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address());
00077     LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address());
00078     LOG("Server Hostname: %s port: %d\n\r", hostname, MQTT_PORT);
00079     LOG("Topic: %s\n\r", TOPIC);
00080     //need subscrie
00081     LOG("=====================================\n\r");
00082     netConnecting = true;
00083     ipstack->open(&ipstack->getWiFi());
00084     int rc = ipstack->connect(hostname,MQTT_PORT,connectTimeout);
00085      if (rc != 0)
00086     {
00087         WARN("IP Stack connect returned: %d\n", rc);    
00088         return rc;
00089     }
00090     printf ("--->TCP Connected\n\r");
00091     netConnected = true;
00092     netConnecting = false;
00093 
00094     //MQTT Connect
00095     mqttConnecting = true;
00096     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
00097     data.MQTTVersion = 4;
00098     data.struct_version =0;
00099 
00100     if((rc = client->connect(data)) == 0){
00101         connected = true;
00102         printf("--->MQTT Connected\n\r");
00103 //#ifdef SUBSCRIBE
00104         if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",SUB_TOPIC);
00105 //#endif 
00106     }else {
00107         WARN("MQTT connect returned %d\n", rc);        
00108     }
00109     if (rc >= 0)
00110         connack_rc = rc;
00111         mqttConnecting = false;
00112         return rc;
00113    
00114 }
00115 int getConnTimeout(int attemptNumber)
00116 {  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
00117    // after 20 attempts, retry every 10 minutes
00118     return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
00119 }
00120 void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
00121 {
00122     connected = false;
00123            
00124     while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
00125     {    
00126         /*if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
00127             printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc);        
00128             return; // don't reattempt to connect if credentials are wrong
00129         } */
00130         int timeout = getConnTimeout(++retryAttempt);
00131         WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
00132         
00133         // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
00134         //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)        
00135         // this works - reset the system when the retry count gets to a threshold
00136         if (retryAttempt == 5)
00137             NVIC_SystemReset();
00138         else
00139             wait(timeout);
00140     }
00141 }
00142 int publish (MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
00143     
00144     
00145     MQTT::Message message;
00146     int data = bmpSensor.Temp_read();
00147     char *pubTopic = TOPIC;
00148     char buf[MQTT_MAX_PAYLOAD_SIZE];
00149 
00150 
00151     printf("Temp = %d\n", data);
00152     sprintf(buf,"%d",data);
00153     message.qos = MQTT::QOS0;
00154     message.retained = false;
00155     message.dup = false;
00156     message.payload = (void*)buf;
00157     message.payloadlen = strlen(buf);
00158 
00159     printf("Publishing %s\n\r", buf);
00160     return client->publish(pubTopic, message);
00161 }
00162 
00163 int main(int argc, char const *argv[])
00164 {
00165     myled =0;
00166     /* code */
00167     const char *ssid = SSID;
00168     const char *seckey = PASSW;
00169     //use SpwfSAInterface connect AP
00170     SpwfSAInterface spwf(D8,D2, false);
00171 
00172     printf("\r\nX-NUCLEO-IDW01M1 mbed \n");
00173     printf("\r\nconnecting to AP\n");
00174     //connect to Wifi
00175     MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2);
00176     //check wifi has got ip_address
00177     if(ipstack.getWiFi().get_ip_address() == 0){
00178         printf("Connect WiFi is failed!\nPlease check your ssid and passwd is correct");
00179         return 0;
00180     }
00181     printf("ip: %s\n",ipstack.getWiFi().get_ip_address() );
00182 
00183     MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
00184     attemptConnect(&client, &ipstack);
00185 
00186        
00187    int count = 0;    
00188 //    tyeld.start();    
00189     while (true)
00190     {
00191         if (++count == 100)
00192         {               // Publish a message every second
00193             if (publish(&client, &ipstack) != 0) { 
00194                
00195                 attemptConnect(&client, &ipstack);   // if we have lost the connection                
00196             }
00197             count = 0;
00198         }        
00199 //        int start = tyeld.read_ms();
00200         client.yield(10);  // allow the MQTT client to receive messages
00201 //        printf ("tyeld: %d\n\r",tyeld.read_ms()-start);
00202 
00203     }
00204     
00205     return 0;
00206 }