wang tang / Mbed 2 deprecated DS1820_IDW01M1_finish

Dependencies:   watersenor_and_temp_code MQTT NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed

Fork of DS1820_IDW01M1 by CHANG rozen

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 #include "DS1820.h"
00008 
00009 // MQTT use
00010 #define MQTT_MAX_PACKET_SIZE 250
00011 #define MQTT_MAX_PAYLOAD_SIZE 300
00012 //Configuration value needed to connect Red-node
00013 #define BROKER_URL "192.168.1.111";
00014 #define MQTT_PORT 1883
00015 //MQTT use Topic 
00016 #define TOPIC2 "1"
00017 #define TOPIC1 "3"
00018 #define SUB_TOPIC "LED"
00019 
00020 
00021 //Wifi network
00022 #define SSID "18-2F"
00023 #define PASSW "062432779"
00024 
00025 DigitalOut myled(LED1);
00026 //BME280 bmpSensor;
00027 int connack_rc = 0;    // MQTT connack return code
00028 const char * ip_addr = "";
00029 char *host_addr = "";
00030 bool netConnecting = false;
00031 int connectTimeout = 1000;
00032 bool mqttConnecting = false;
00033 bool netConnected = false;
00034 bool connected = false;
00035 int retryAttempt = 0;
00036 char subscription_url[MQTT_MAX_PAYLOAD_SIZE];
00037 
00038 
00039 
00040 Serial serial(USBTX, USBRX);
00041 DS1820  ds1820(PA_8);    // substitute PA_9 with actual mbed pin name connected to the DS1820 data pin
00042 DigitalIn  sensor_in(D4);
00043 
00044 
00045 MQTT::Message message;
00046 MQTTString TopicName1={TOPIC1};
00047 MQTTString TopicName2={TOPIC2};
00048 MQTT::MessageData MsgData1(TopicName1, message);
00049 MQTT::MessageData MsgData2(TopicName2, message);
00050 
00051 void subscribe_LED(char* msg){
00052     int value = atoi(msg);
00053     //printf("value = %d\n", value);
00054     if(value ==1){
00055         myled = !myled;
00056     }
00057     
00058 }
00059 
00060 
00061 void subscribe_cb(MQTT::MessageData & msgMQTT) {
00062     char msg[MQTT_MAX_PAYLOAD_SIZE];
00063     msg[0]='\0';
00064     strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen);
00065     printf ("--->>> subscribe_cb msg: %s\n\r", msg);
00066     subscribe_LED(msg);
00067 }
00068 int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
00069 {
00070     char* pubTopic = SUB_TOPIC;    
00071     return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb);
00072 }
00073 
00074 
00075 int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
00076     const char* host = BROKER_URL;
00077 
00078     char hostname[strlen(host) + 1];
00079     sprintf(hostname,"%s", host);
00080 
00081     SpwfSAInterface& WiFi = ipstack->getWiFi();
00082 
00083     //Network Debug statements
00084     LOG("=====================================\n\r");
00085     LOG("Connecting WiFi.\n\r");
00086     LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address());
00087     LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address());
00088     LOG("Server Hostname: %s port: %d\n\r", hostname, MQTT_PORT);
00089     LOG("Topic1: %s\n\r", TOPIC1);
00090     LOG("Topic2: %s\n\r", TOPIC2);
00091     //need subscrie
00092     LOG("=====================================\n\r");
00093     netConnecting = true;
00094     ipstack->open(&ipstack->getWiFi());
00095     int rc = ipstack->connect(hostname,MQTT_PORT,connectTimeout);
00096      if (rc != 0)
00097     {
00098         WARN("IP Stack connect returned: %d\n", rc);    
00099         return rc;
00100     }
00101     printf ("--->TCP Connected\n\r");
00102     netConnected = true;
00103     netConnecting = false;
00104 
00105     //MQTT Connect
00106     mqttConnecting = true;
00107     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
00108     data.MQTTVersion = 4;
00109     data.struct_version =0;
00110 
00111     if((rc = client->connect(data)) == 0){
00112         connected = true;
00113         printf("--->MQTT Connected\n\r");
00114 //#ifdef SUBSCRIBE
00115         if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",SUB_TOPIC);
00116 //#endif 
00117     }else {
00118         WARN("MQTT connect returned %d\n", rc);        
00119     }
00120     if (rc >= 0)
00121         connack_rc = rc;
00122         mqttConnecting = false;
00123         return rc;
00124    
00125 }
00126 int getConnTimeout(int attemptNumber)
00127 {  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
00128    // after 20 attempts, retry every 10 minutes
00129     return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
00130 }
00131 void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
00132 {
00133     connected = false;
00134            
00135     while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
00136     {    
00137         /*if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
00138             printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc);        
00139             return; // don't reattempt to connect if credentials are wrong
00140         } */
00141         int timeout = getConnTimeout(++retryAttempt);
00142         WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
00143         
00144         // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
00145         //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)        
00146         // this works - reset the system when the retry count gets to a threshold
00147         if (retryAttempt == 5)
00148             NVIC_SystemReset();
00149         else
00150             wait(timeout);
00151     }
00152 }
00153 int publish1(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack,int data){
00154     
00155     
00156     MQTT::Message message;
00157     char *pubTopic = TOPIC1;
00158     char buf[MQTT_MAX_PAYLOAD_SIZE];
00159 //  printf("Temp = %d\n", data);
00160     sprintf(buf,"%d",data);
00161     message.qos = MQTT::QOS0;
00162     message.retained = false;
00163     message.dup = false;
00164     message.payload = (void*)buf;
00165     message.payloadlen = strlen(buf);
00166 
00167     printf("Temp = %s\n\r", buf);
00168     return client->publish(pubTopic, message);
00169 }
00170 int publish2(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack,int data){
00171     
00172     
00173     MQTT::Message message;
00174     char *pubTopic = TOPIC1;
00175     char buf[MQTT_MAX_PAYLOAD_SIZE];
00176     if(data)
00177     {
00178         printf("LED:OFF \n");       
00179     }
00180     else
00181     {
00182         printf("LED:ON \n");        
00183     }
00184     sprintf(buf,"%d",data);
00185     message.qos = MQTT::QOS0;
00186     message.retained = false;
00187     message.dup = false;
00188     message.payload = (void*)buf;
00189     message.payloadlen = strlen(buf);
00190     return client->publish(pubTopic, message);
00191 }
00192 int main()
00193 {
00194     myled =0;
00195     
00196     
00197     const char *ssid = SSID;
00198     const char *seckey = PASSW;
00199     //use SpwfSAInterface connect AP
00200     SpwfSAInterface spwf(D8,D2, false);
00201     printf("\r\nX-NUCLEO-IDW01M1 mbed \n");
00202     printf("\r\nconnecting to AP\n");
00203     //connect to Wifi
00204     MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2);
00205     //check wifi has got ip_address
00206     if(ipstack.getWiFi().get_ip_address() == 0){
00207         printf("Connect WiFi is failed!\nPlease check your ssid and passwd is correct");
00208         return 0;
00209     }
00210     printf("ip: %s\n",ipstack.getWiFi().get_ip_address() );
00211 
00212     MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
00213     attemptConnect(&client, &ipstack);
00214        
00215    int count = 0;  
00216    int databuffer1;
00217    int databuffer2;  
00218 //    tyeld.start();    
00219     while (true){
00220         if(!ds1820.begin())
00221         {
00222             return -1;
00223         }
00224         else
00225         {
00226             ds1820.startConversion();
00227         }
00228         
00229         if(sensor_in)
00230         {
00231             databuffer2 = 0;
00232         }
00233         else
00234         {
00235             databuffer2 = 1;
00236         }
00237         if (++count == 20)
00238         {               // Publish a message every second
00239 //            serial.printf("temp = %3.1f\r\n", ds1820.read());     // read temperature
00240             databuffer1 = ds1820.read();
00241             ds1820.startConversion();     // start temperature conversion
00242             wait(1.0);                    // let DS1820 complete the temperature conversion
00243             if (publish1(&client, &ipstack,databuffer1) != 0) 
00244             { 
00245                 attemptConnect(&client, &ipstack);   // if we have lost the connection                
00246             }
00247             if (publish2(&client, &ipstack,databuffer2) != 0) 
00248             { 
00249                 attemptConnect(&client, &ipstack);   // if we have lost the connection                
00250             }
00251         count = 0;
00252         }
00253         else
00254         {
00255 //          serial.printf("count: %d \n",count);
00256         }      
00257 //      int start = tyeld.read_ms();
00258         //client.yield(10);  // allow the MQTT client to receive messages
00259 //      printf ("tyeld: %d\n\r",tyeld.read_ms()-start);
00260         }
00261 }