able to subscribe for >10hrs and still running

Dependencies:   ADE7758_v1 Crypto DHT11 MQTT MbedJSONValue SDFileSystem SPI_TFT_ILI9341 SWSPI SetRTC TFT_fonts Touch W5500Interface mbed-rtos mbed-src tuanpm

Fork of PB_emma_controller_mbed_src by Emma

Files at this revision

API Documentation at this revision

Comitter:
bonchenko
Date:
Wed Aug 05 10:07:18 2015 +0000
Parent:
26:79c12923e362
Child:
28:cd25d46cb141
Commit message:
able to subscribe for several times using own parser

Changed in this revision

emmaCode.cpp Show annotated file Show diff for this revision Revisions of this file
emmaCode.h Show annotated file Show diff for this revision Revisions of this file
jsmn.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/emmaCode.cpp	Sat Jul 25 11:59:35 2015 +0000
+++ b/emmaCode.cpp	Wed Aug 05 10:07:18 2015 +0000
@@ -32,6 +32,7 @@
 //init dht sensor
 DHT11 d(PD_2);
 
+
 //emma settings
 string emmaUID;
 string hmac;
@@ -296,6 +297,7 @@
     string str;
     TFT.locate(0,0);
     TFT.printf(" please wait");
+    MbedJSONValue jsonValue;    
     
     if(wifiAvailable) {
         DBG.printf("emmaModeWiFiConfig\r\n");
@@ -325,8 +327,7 @@
                 if(str.find("[") != std::string::npos && str.find("]") != std::string::npos) {
                     str.erase(str.begin(),str.begin()+str.find("[")+1);
                     str.erase(str.begin()+str.find("]"),str.end());
-                            
-                    MbedJSONValue jsonValue;
+                    
                     parse(jsonValue,str.c_str());
                         
                     char *parameter[2] = {"wifiSSID","wifiPASS"};
@@ -379,6 +380,7 @@
     bool serverIsListened = false;
     char s[32];
     string str;
+    MbedJSONValue jsonValue;
     
     TFT.locate(0,0);
     TFT.printf(" please wait");
@@ -443,7 +445,6 @@
                                 str.erase(str.begin(),str.begin()+str.find("[")+1);
                                 str.erase(str.begin()+str.find("]"),str.end());
                             
-                                MbedJSONValue jsonValue;
                                 parse(jsonValue,str.c_str());
                         
                                 char *parameter[5] = {"gprsAPN","proxySERVER","proxyPORT","proxyAUTH","epochTime"};
@@ -504,7 +505,6 @@
                     str.erase(str.begin(),str.begin()+str.find("[")+1);
                     str.erase(str.begin()+str.find("]"),str.end());
                             
-                    MbedJSONValue jsonValue;
                     parse(jsonValue,str.c_str());
                         
                     char *parameter[5] = {"gprsAPN","proxySERVER","proxyPORT","proxyAUTH","epochTime"};
@@ -578,10 +578,11 @@
     string str;
     string regKey;
     Timer t;
+    MbedJSONValue jsonValue;
     
     TFT.locate(0,0);
     TFT.printf(" please wait");
-    
+    useProxy = true;
     //check connected interface
     //connectedIface();
     isEthConnected();
@@ -630,7 +631,6 @@
                 str.erase(str.begin(),str.begin()+str.find("[")+1);
                 str.erase(str.begin()+str.find("]"),str.end());
         
-                MbedJSONValue jsonValue;
                 parse(jsonValue,str.c_str());
     
                 char *parameter[4] = {"platformDOMAIN","platformKEY","platformSECRET","registrationKey"};
@@ -696,7 +696,6 @@
                 str.erase(str.begin(),str.begin()+str.find("[")+1);
                 str.erase(str.begin()+str.find("]"),str.end());
                     
-                MbedJSONValue jsonValue;
                 parse(jsonValue,str.c_str());
                 if(jsonValue.hasMember("user")) {
                     string val = jsonValue["user"].get<std::string>();
@@ -770,7 +769,6 @@
                     str.erase(str.begin(),str.begin()+str.find("[")+1);
                     str.erase(str.begin()+str.find("]"),str.end());
         
-                    MbedJSONValue jsonValue;
                     parse(jsonValue,str.c_str());
     
                     char *parameter[4] = {"platformDOMAIN","platformKEY","platformSECRET","registrationKey"};
@@ -845,7 +843,6 @@
                     str.erase(str.begin(),str.begin()+str.find("[")+1);
                     str.erase(str.begin()+str.find("]"),str.end());
                     
-                    MbedJSONValue jsonValue;
                     parse(jsonValue,str.c_str());
                     if(jsonValue.hasMember("user")) {
                         string val = jsonValue["user"].get<std::string>();
@@ -885,6 +882,7 @@
 }
 
 void emmaModeOperation(void) {
+    char *parameter[5] = {"\"id\"","\"nType\"","\"nAddr\"","\"dType\"","\"cmd\""};
     char mqttClientId[32];
     char p[64];
     char q[32];
@@ -901,12 +899,14 @@
     Timer tPanelEnergy;
     Timer tPanel;
     Timer tNodes;
-    
+    MbedJSONValue jsonValue;
+     
     TFT.locate(0,0);
     TFT.printf(" please wait");
     
     //check connected interface
     //connectedIface();
+    DBG.printf("EMMA OPERATION MODE\r\n");
     isEthConnected();
     isWiFiConnected();
     isGprsConnected();
@@ -946,96 +946,92 @@
     
     if(ethConnected) {
         DBG.printf("emmaModeOperation - eth\r\n");
-        //DBG.printf("IP Address:%s\r\n",ipstack.getEth().getIPAddress());
-        //DBG.printf("MAC Address:%s\r\n",ipstack.getEth().getMACAddress());
+        DBG.printf("IP Address:%s\r\n",ipstack.getEth().getIPAddress());
+        DBG.printf("MAC Address:%s\r\n",ipstack.getEth().getMACAddress());
         ethMQTTAttemptConnect(&client, &ipstack);
-        //t.start();
-        DBG.printf("start\r\n");
+//        t.start();
+//        DBG.printf("start\r\n");
         while(true) {
-            //if(!ipstack.getEth().linkstatus()) {
-            //    NVIC_SystemReset();  
-            //}
-            //if(t.read_ms() > 5000) {
-            //    if(publish(&client,&ipstack) != 0)
-            //        ethMQTTAttemptConnect(&client, &ipstack);
-            //    t.reset();
-            //}
-        
+//            if(!ipstack.getEth().linkstatus()) {
+//                NVIC_SystemReset();  
+//            }
+
             //check for new command
             if(newCommand) {
-                DBG.printf("newCommand\r\n");
-                //DBG.printf("globalCommand: %s\r\n",globalCommand.c_str());
-                //string qw(globCmd);
-            
-                //if(cmd.find("[") != std::string::npos && cmd.find("]") != std::string::npos) {
-                //    cmd.erase(cmd.begin(),cmd.begin()+cmd.find("[")+1);
-                //    cmd.erase(cmd.begin()+cmd.find("]"),cmd.end());
-                    //globalCommand = cmd;
-                    //newCommand = true;
-                //}
-                /*
-                MbedJSONValue jsonValue;
-                parse(jsonValue,globalCommand.c_str());
-                char *parameter[5] = {"id","nType","nAddr","dType","cmd"};
+                string cmd(globalCommand);
+                string cmdBuffer;
+                int keyIndex, key2Index;
+                int valueLength;
+                
+                DBG.printf("Parsing CMD...\r\n");
                 
+                for (int i=0; i<5; i++) {
+                    keyIndex = cmd.find(parameter[i]);
+                    key2Index = cmd.find(parameter[i+1]);
+                    valueLength = key2Index - keyIndex - strlen(parameter[i]) - 2;
+                    DBG.printf("%s index: %d\r\n", parameter[i], keyIndex);
+                    cmdBuffer.assign(cmd, keyIndex+strlen(parameter[i]), valueLength);
+                    DBG.printf("the value: %s\r\n", cmdBuffer);
+                }
+
+                DBG.printf("Checking command validity...\r\n");
                 //check if command is valid
                 bool validCommand = true;
-                for(int i=0; i<5; i++) {
-                    validCommand = validCommand && jsonValue.hasMember(parameter[i]);
-                }
-                DBG.printf("command validity:%d\r\n",validCommand);
-                
-                if(validCommand) {
-                    string commandId = jsonValue[parameter[0]].get<std::string>();
-                    string commandNType = jsonValue[parameter[1]].get<std::string>();
-                    string commandNAddr = jsonValue[parameter[2]].get<std::string>();
-                    string commandDType = jsonValue[parameter[3]].get<std::string>();
-                    string commandCmd = jsonValue[parameter[4]].get<std::string>();
-                    
-                    if(commandNType == "0") {       //switch on panel controller
-                        DBG.printf("command for switch\r\n");
-                    }
-                    else if(commandNType == "1") {  //node with mac address
-                        DBG.printf("command for node\r\n");
-                        //get node ip address based on node mac address
-                        string nodeIP = readNodeIP(commandNAddr);
-                        DBG.printf("nodeIP: %s\r\n",nodeIP.c_str());
-                        
-                        //get cmd string based on device type and command number
-                        string nodeCmd = readNodeCmd(commandDType,commandCmd);
-                        DBG.printf("nodeCmd: %s\r\n",nodeCmd.c_str());
-                        
-                        //execute command
-                        //int trial=0;
-                        trial = 0;
-                        string execStatus="failed";
-                    
-                        while(1) {
-                            sprintf(s,"<?xml version=\"1.0\" encoding=\"utf-8\"?><app_cmd cmd=\"5\" /><app_data code=\"%s\"/>\r\n",nodeCmd.c_str());
-                            str = s;
-                            string rcv = ethGET(nodeIP,REMOTE_TCP_PORT,str);
-                            DBG.printf("response:%s\r\n",rcv.c_str());
-                            str = rcv;
-                            if(str.find("OK") != std::string::npos) {
-                                DBG.printf("cmd executed\r\n");
-                                execStatus = "success";
-                                break;    
-                            }
-                            if(trial>0) {   //two times trial
-                                DBG.printf("cmd is not executed\r\n");
-                                break;    
-                            }
-                            trial++;
-                            wait(3);
-                        }
-                    
-                        //send execution status
-                    }
-                }
-                */
+                DBG.printf("Command validity:%d\r\n",validCommand);
+                                
+//                if(validCommand) {
+//                    string commandId = jsonValue[parameter[0]].get<std::string>();
+//                    string commandNType = jsonValue[parameter[1]].get<std::string>();
+//                    string commandNAddr = jsonValue[parameter[2]].get<std::string>();
+//                    string commandDType = jsonValue[parameter[3]].get<std::string>();
+//                    string commandCmd = jsonValue[parameter[4]].get<std::string>();
+//                    
+//                    if(commandNType == "0") {       //switch on panel controller
+//                        DBG.printf("command for switch\r\n");
+//                    }
+//                    else if(commandNType == "1") {  //node with mac address
+//                        DBG.printf("command for node\r\n");
+//                        //get node ip address based on node mac address
+//                        string nodeIP = readNodeIP(commandNAddr);
+//                        //DBG.printf("nodeIP: %s\r\n",nodeIP.c_str());
+//                        
+//                        //get cmd string based on device type and command number
+//                        string nodeCmd = readNodeCmd(commandDType,commandCmd);
+//                        //DBG.printf("nodeCmd: %s\r\n",nodeCmd.c_str());                        
+//                        //execute command
+//                        //int trial=0;
+//                        trial = 0;
+//                        bool execStatus=false;
+//                    
+//                        while( !execStatus ) {
+//                            sprintf(s,"<?xml version=\"1.0\" encoding=\"utf-8\"?><app_cmd cmd=\"5\" /><app_data code=\"%s\"/>\r\n",nodeCmd.c_str());
+//                            str = s;
+//                            DBG.printf("str value:%s\r\n",str.c_str());                            
+//                            string rcv = ethGET(nodeIP,REMOTE_TCP_PORT,str); // cause mqtt to stop
+//                            DBG.printf("response:%s\r\n",rcv.c_str());
+//                            str = rcv;
+//                            if(str.find("OK") != std::string::npos) {
+//                                DBG.printf("CMD executed successfully\r\n");
+//                                execStatus = true;
+//                            }
+//                            if(trial>0) {   //two times trial
+//                                DBG.printf("cmd is not executed\r\n");
+//                                execStatus = false;
+//                            }
+//                            DBG.printf("Trial++\r\n");
+//                            trial++;
+//                            wait(3);
+//                        }
+//                        DBG.printf("Send execution status\r\n");
+//                        //send execution status
+//                    }
+//                }
                 newCommand = false;    
-            } 
-            client.yield(100);  //allow MQTT client to receive message
+                DBG.printf("New command false\r\n");
+            }
+            // DBG.printf("Yielding...\r\n");            
+            client.yield(10);  //allow MQTT client to receive message
+            // DBG.printf("Yield finished\r\n");
         }
     } else if(wifiConnected) {
         DBG.printf("emmaModeOperation - wifi\r\n");
@@ -1044,7 +1040,7 @@
         //_ESP.printf("MODE=B");
         //wait(1);
         //while(!esp.ready());
-        
+
         /*
         DBG.printf("emma: setup mqtt client\r\n");
         sprintf(mqttClientId,"emma/%s",emmaUID.c_str());
@@ -1125,7 +1121,6 @@
             str.erase(str.begin(),str.begin()+str.rfind("[{\"mac\""));
             str.erase(str.begin()+str.rfind("}]")+2,str.end());
             
-            MbedJSONValue jsonValue;
             parse(jsonValue,str.c_str());
             char *parameter[2] = {"mac","ip"};
             
@@ -1459,7 +1454,6 @@
                 TFT.locate(0,160);
                 TFT.printf("newCommand");
                 
-                MbedJSONValue jsonValue;
                 parse(jsonValue,globalCommand.c_str());
                 char *parameter[5] = {"name","nType","nAddr","dType","cmd"};
                 
@@ -1605,6 +1599,7 @@
 }
 void emmaModeFirmwareDownload(void) {
     bool emmaGetFirmwareParam = false;
+    MbedJSONValue jsonValue;
     
     DBG.printf("emmaModeFirmwareDownload\r\n");
     
@@ -1677,7 +1672,6 @@
             str.erase(str.begin(),str.begin()+str.find("[")+1);
             str.erase(str.begin()+str.find("]"),str.end());
             
-            MbedJSONValue jsonValue;
             parse(jsonValue,str.c_str());
             
             char *parameter[2] = {"firmwareVer","numPart"};
@@ -1962,7 +1956,7 @@
         if(rxBuf.find("[{") != std::string::npos && rxBuf.find("}]") != std::string::npos) {
             rxBuf.erase(rxBuf.begin(),rxBuf.begin()+rxBuf.find("[{")+1);
             rxBuf.erase(rxBuf.begin()+rxBuf.find("]"),rxBuf.end());
-            globalCommand = rxBuf;
+            rxBuf.assign(globalCommand);
             //DBG.printf("gC:%s\r\n",globalCommand.c_str());
             newCommand = true;
         }
@@ -1981,38 +1975,15 @@
 /*start eth mqtt*/
 void ethMQTTMessageArrived(MQTT::MessageData& md) {
     MQTT::Message &message = md.message;
-    DBG.printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n",
-    message.qos, message.retained, message.dup, message.id);
-    DBG.printf("Payload: %.*s\r\n", message.payloadlen, (char*)message.payload);
-    //DBG.printf("Payload %s\r\n",message.payload);
-    
+    DBG.printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
+    DBG.printf("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
+
+    string sp = string((char*)(message.payload));
     
-    //check whether cmd is json
-    //char r[255];
-    char *s = (char*)message.payload;
-    string sp(s);
-    //sprintf(s,"%.*s",message.payloadlen, (char*)message.payload);
-    //sprintf(globCmd,"%s",s);
-    //DBG.printf("Payload: %s\r\n", r);
-    //string cmd = r;
-    //globalCommand = cmd;
-    
-    //globalCommand = sp;
-    
-    //globCmd = (char*)message.payload;
-    //string globCmd((char*)message.payload);
-    //std::string *sp = static_cast<std::char*>(message.payload);
-    //string sp((char*)message.payload);
-    
-    //DBG.printf("String: %s\r\n",sp.c_str());
-    
-    //globCmd = sp;
-    
-    //newCommand = true;
     if(sp.find("[") != std::string::npos && sp.find("]") != std::string::npos) {
         sp.erase(sp.begin(),sp.begin()+sp.find("[")+1);
-        sp.erase(sp.begin()+sp.find("]"),sp.end());
-        globalCommand = sp;
+        sp.erase(sp.begin()+sp.find("]"), sp.end());
+        globalCommand.assign(sp);
         newCommand = true;
     }
     sp.clear();
@@ -2047,18 +2018,19 @@
     char s[64];
     sprintf(s,"%s/%s/command",platformDOMAIN.c_str(),emmaUID.c_str());
     string topic = s;
-    //DBG.printf("topic:%s\r\n",topic.c_str());
-    if((rc=client->subscribe(topic.c_str(),MQTT::QOS0,ethMQTTMessageArrived)) == 0) {
+    DBG.printf("topic:%s\r\n",topic.c_str());
+    if((rc=client->subscribe(topic.c_str(),MQTT::QOS2,ethMQTTMessageArrived)) == 0) {
         DBG.printf("subscribe success!\r\n");    
     }
     return rc;
 }
+
 void ethMQTTAttemptConnect(MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTEthernet* ipstack) {
     int retryAttempt = 0;
     
     while(!ipstack->getEth().linkstatus()) {
         DBG.printf("Ethernet link not present. Check cable connection\r\n");
-        wait(1);    
+        wait(1);
     }
     
     while(ethMQTTConnect(client,ipstack) != 0) {
@@ -2068,6 +2040,7 @@
         retryAttempt++;
     }
 }
+
 /*end eth mqtt*/
 
 /*start emma settings*/
@@ -2240,15 +2213,36 @@
 
 /*start emma connection function*/
 string ethGET(string host, int port, string url) {
+//    DBG.printf("Entering ethGET with url: %s\r\n", url);
+//    DBG.printf("Host: %s\r\n", host);
+//    DBG.printf("Port: %d\r\n", port);    
     char buf[1024];
     char s[256];
     int ret;
     TCPSocketConnection sock;
     Timer t;
     
+    DBG.printf("Sock connecting\r\n");
+    if (sock.connect(host.c_str(), port) == 0){
+        DBG.printf("Sock connected successfully\r\n");
+    }
+    else {
+        DBG.printf("Sock failed to connect\r\n");
+        sock.close();
+        return buf;
+    }
+    DBG.printf("Sock sending all\r\n");
     sprintf(s,"%s",url.c_str());
-    sock.connect(host.c_str(),port);
-    sock.send_all(s,sizeof(s)-1);
+    int size = sock.send_all(s,sizeof(s)-1);
+    if (size >= 0) {
+        DBG.printf("Sock sent %d\r\n", size);
+    }
+    else {
+        DBG.printf("Sock failed to send\r\n");
+        sock.close();
+        return buf;
+    }
+    DBG.printf("Wait...\r\n");
     wait(2);
     
     //receive return
@@ -2353,6 +2347,7 @@
 void isEthAvailable(void) {
     if(ipstack.getEth().linkstatus()) {
         ethAvailable = true;    
+        DBG.printf("IP address: %s\r\n", ipstack.getEth().getIPAddress());
     } else {
         ethAvailable = false;    
     }
@@ -2377,12 +2372,13 @@
             connPort = EMMA_SERVER_PORT;
             for(int i=0; i<sizeof(s); i++) {
                 s[i]=0; }
-            strcpy(s,"GET /emma/api/controller/test HTTP/1.0\nHost: %s\r\n\r\n");
+            sprintf(s,"GET /emma/api/controller/test HTTP/1.0\nHost: %s\r\n\r\n",EMMA_SERVER_HOST);
         }
         
         t.start();
         while(1) {
             str = ethGET(connHost,connPort,s);
+            DBG.printf("str value: %s", str);
             if(str.find("OK") != std::string::npos) {
                 t.stop();
                 ethConnected = true;
--- a/emmaCode.h	Sat Jul 25 11:59:35 2015 +0000
+++ b/emmaCode.h	Wed Aug 05 10:07:18 2015 +0000
@@ -8,6 +8,7 @@
 #include "MQTTClient.h"         //eth mqtt
 #include "MQTTEthernet.h"       //eth mqtt
 #include "MbedJSONValue.h"      //json
+#include "jsmn.h"              //json alternative
 #include "SDFileSystem.h"       //sd card
 #include "Crypto.h"             //hash calculation
 #include "cmsis_os.h"           //threads
@@ -26,6 +27,8 @@
 #define BASE_ADDR 0x1FFF7A10
 #endif
 
+#define MAXTOKEN                64
+
 //mode
 #define MODE_WIFI_CONFIG        0x00    //wifi config
 #define MODE_SETTINGS           0x01    //settings
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jsmn.lib	Wed Aug 05 10:07:18 2015 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/yoonghm/code/jsmn/#5167da2fcc4e
--- a/main.cpp	Sat Jul 25 11:59:35 2015 +0000
+++ b/main.cpp	Wed Aug 05 10:07:18 2015 +0000
@@ -4,8 +4,8 @@
 
 int main() {
     //init touchscreen and read input
-    //mode = MODE_OPERATION;
-    mode = emmaModeSelection();
+    mode = MODE_OPERATION;
+    // mode = emmaModeSelection();
     
     emmaInit(mode);
     //switch mode