emma controller code in production board v1

Dependencies:   ADE7758_v1 Crypto DHT11 MQTT MbedJSONValueEmma SDFileSystem TFT_ILI9341 SWSPI SetRTC TFT_fonts Touch W5500Interface mbed-rtos mbed-src SoftSerial

Fork of emma_controller_energy by Emma

Revision:
45:2406c2b6995a
Parent:
44:c1d11c491237
Child:
46:86a0c2133130
--- a/emmaCode.cpp	Wed Aug 26 07:18:33 2015 +0000
+++ b/emmaCode.cpp	Wed Aug 26 10:00:39 2015 +0000
@@ -17,6 +17,7 @@
 EthernetInterface eth(&spi, PB_12, PC_6);   //spi, cs, reset
 //MQTTEthernet ipstack(&spi, PB_12, PC_6);    //spi, cs, reset
 //MQTT::Client<MQTTEthernet, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
+TCPSocketConnection sock;
 
 //init sd card
 SDFileSystem sd(PA_7, PA_6, PA_5, PB_3, "sd"); //mosi, miso, sck, cs
@@ -1020,8 +1021,7 @@
     char p[64];
     char q[32];
     char r[32];
-    //char s[4096];
-    char s[512];
+    char s[4096];
     int connBodyLen;
     int connPort;
     int loop=0;
@@ -1255,11 +1255,258 @@
             //panel environment
             
             //command
-            connBodyLen = sprintf(connBody,"{\"uid\":\"005e00553533510334313732\",\"hmac\":\"9424c60e708d8e3d3dff6d23fb104339\"}");
-            sprintf(s,"POST /emma/api/controller/command HTTP/1.0\nHost: 36.80.35.8\nContent-Length:%d\n\n%s\r\n\r\n",connBodyLen,connBody);
-            str.clear();
-            str = ethREST("36.80.35.8",8080,s);
-            DBG.printf("str:%s\r\n",str.c_str());
+            connBodyLen = sprintf(connBody,"{\"uid\":\"%s\",\"hmac\":\"%s\"}",emmaUID.c_str(),hmac.c_str());
+            sprintf(s,"POST /%s/api/controller/command HTTP/1.0\nHost: %s\nContent-Length:%d\n\n%s\r\n\r\n",appNAME.c_str(),restSERVER.c_str(),connBodyLen,connBody);
+            sscanf(restPORT.c_str(),"%d",&connPort);
+            str = ethREST(restSERVER,connPort,s);
+            //DBG.printf("str:%s\r\n",str.c_str());
+            
+            if(str.rfind("[{\"from\"") != std::string::npos) {
+                str.erase(str.begin(),str.begin()+str.rfind("[{\"from\""));
+                if(str.find("[{") != std::string::npos && str.rfind("}]") != std::string::npos) {
+                    str.erase(str.begin(),str.begin()+str.find("[{"));
+                    str.erase(str.begin()+str.rfind("}]")+2,str.end());
+                }
+                //DBG.printf("newCommand:\r\n%s\r\n",str.c_str());
+                TFT.locate(0,160);
+                TFT.printf("                                        ");
+                TFT.locate(0,160);
+                TFT.printf("newCommand");
+                
+                MbedJSONValue jsonValue;
+                parse(jsonValue,str.c_str());
+                char *parameter[5] = {"from","nType","nAddr","dType","cmd"};
+                
+                DBG.printf("get %d command\r\n",jsonValue.size());
+                
+                //processing each command
+                bool validCommand;
+                for(int i=0; i<jsonValue.size(); i++) {
+                    //check whether command is valid
+                    DBG.printf("\r\nprocessing cmd[%d]\r\n",i);
+                    validCommand = true;
+                    for(int j=0; j<5; j++) {
+                        validCommand = validCommand && jsonValue[i].hasMember(parameter[j]);
+                    }
+                    DBG.printf("command validity:%d\r\n",validCommand);
+                    
+                    if(validCommand) {
+                        string commandFrom = jsonValue[i][parameter[0]].get<std::string>();
+                        string commandNType = jsonValue[i][parameter[1]].get<std::string>();
+                        string commandNAddr = jsonValue[i][parameter[2]].get<std::string>();
+                        string commandDType = jsonValue[i][parameter[3]].get<std::string>();
+                        string commandCmd = jsonValue[i][parameter[4]].get<std::string>();
+                        
+                        if(commandNType == "0") {       //switch on panel controller
+                            DBG.printf("command for switch\r\n");
+                        }
+                        else if(commandNType == "1") {  //ir&rf remote control
+                            DBG.printf("command for remote control\r\n");
+                    
+                            //get index of node list based on mac address
+                            int idx = NODES_INVALID;
+                            for(int i=0; i<NODES_MAX; i++) {
+                                if(!nodes[i].macAddr.compare(commandNAddr)) {
+                                    idx = i;
+                                }
+                            }
+                    
+                            //execution process
+                            string execResult = "failed";
+                            if(idx != NODES_INVALID) {
+                                DBG.printf("index found at %d\r\n",idx);
+                        
+                                //get cmd string based on device type and command number
+                                string nodeCmd;
+                                nodeCmd = readNodeCmd(commandDType,commandCmd);
+                        
+                                //execute command
+                                DBG.printf("executing command\r\n");
+                                sprintf(s,"<?xml version=\"1.0\" encoding=\"utf-8\"?><app_cmd cmd=\"5\" /><app_data code=\"%s\"/>\r\n",nodeCmd.c_str());
+                            
+                                trial=0;
+                                while(1) {
+                                    if(trial>=2) {   //two times trial
+                                        DBG.printf("cmd is not executed\r\n");
+                                        TFT.foreground(Red);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.locate(0,180);
+                                        TFT.printf("cmd is not executed");
+                                        wait(1);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.foreground(White);
+                                        break;    
+                                    }
+                                    str = ethREST(nodes[idx].ipAddr,REMOTE_TCP_PORT,s);
+                                    wait(2);
+                                    if(str.find("200 OK") != std::string::npos) {
+                                        DBG.printf("cmd is executed\r\n");
+                                        TFT.foreground(Green);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.locate(0,180);
+                                        TFT.printf("cmd is executed");
+                                        wait(1);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.foreground(White);
+                                        execResult = "success";
+                                        break;    
+                                    }
+                                    str.clear();
+                                    trial++;
+                                }    
+                            } else {
+                                TFT.foreground(Red);
+                                TFT.locate(0,180);
+                                TFT.printf("                                        ");
+                                TFT.locate(0,180);
+                                TFT.printf("node is invalid");
+                                wait(1);
+                                TFT.locate(0,180);
+                                TFT.printf("                                        ");
+                                TFT.foreground(White);    
+                            }
+                            wait(2);
+                            
+                            //send execution result
+                            sprintf(p,"emma-%s-%s",emmaUID.c_str(),commandCmd.c_str());   
+                            hmacCmd = calculateMD5(p);
+                        
+                            connBodyLen = sprintf(connBody,"{\"uid\":\"%s\",\"nType\":\"%s\",\"nAddr\":\"%s\",\"dType\":\"%s\",\"cmd\":\"%s\",\"from\":\"%s\",\"result\":\"%s\",\"hmac\":\"%s\"}",
+                            emmaUID.c_str(), commandNType.c_str(),commandNAddr.c_str(),commandDType.c_str(),commandCmd.c_str(),commandFrom.c_str(),execResult.c_str(),hmacCmd.c_str());
+                            
+                            sprintf(s,"POST /%s/api/controller/result HTTP/1.0\nHost: %s\nContent-Length:%d\n\n%s\r\n\r\n",appNAME.c_str(),restSERVER.c_str(),connBodyLen,connBody);
+                            sscanf(restPORT.c_str(),"%d",&connPort);
+                    
+                            trial=0;
+                            while(1) {
+                                if(trial>=2) {   //two times trial
+                                    DBG.printf("failed to send execution result\r\n");
+                                    break;    
+                                }
+                                str = ethREST(restSERVER,connPort,s);
+                                wait(2);
+                                if(str.rfind("[{\"status\"") != std::string::npos) {
+                                    str.erase(str.begin(),str.begin()+str.rfind("[{\"status\""));
+                                    if(str.find("\"status\":\"success\"") != std::string::npos) {
+                                        DBG.printf("success to send execution result\r\n");
+                                        break;
+                                    }
+                                }
+                                str.clear();
+                                trial++;
+                            }
+                        } else if(commandNType == "2") {  //wifi smart plug
+                            /*
+                            DBG.printf("command for smart plug\r\n");
+                    
+                            //get index of node list based on mac address
+                            int idx = NODES_INVALID;
+                            for(int i=0; i<NODES_MAX; i++) {
+                                if(!nodes[i].macAddr.compare(commandNAddr)) {
+                                    idx = i;
+                                }
+                            }
+                    
+                            //execution process
+                            string execResult = "failed";
+                            if(idx != NODES_INVALID) {
+                                DBG.printf("index found at %d\r\n",idx);
+                                
+                                //execute command
+                                DBG.printf("executing command\r\n");
+                                sprintf(s,"<?xml version=\"1.0\" encoding=\"utf-8\"?><app_cmd cmd=\"13\"/><app_data on-off=\"%s\"/>\r\n",commandCmd.c_str());
+                            
+                                trial=0;
+                                while(1) {
+                                    rxBuf.clear();
+                                    if(trial>=2) {   //two times trial
+                                        DBG.printf("cmd is not executed\r\n");
+                                        TFT.foreground(Red);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.locate(0,180);
+                                        TFT.printf("cmd is not executed");
+                                        wait(1);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.foreground(White);
+                                        break;    
+                                    }
+                                    nodes[idx].restConn->get("/",s);
+                                    wait(2);
+                                    if(rxBuf.find("REST: status = 200") != std::string::npos) {
+                                        DBG.printf("cmd is executed\r\n");
+                                        TFT.foreground(Green);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.locate(0,180);
+                                        TFT.printf("cmd is executed");
+                                        wait(1);
+                                        TFT.locate(0,180);
+                                        TFT.printf("                                        ");
+                                        TFT.foreground(White);
+                                        execResult = "success";
+                                        break;    
+                                    }
+                                    trial++;
+                                }    
+                            } else {
+                                TFT.foreground(Red);
+                                TFT.locate(0,180);
+                                TFT.printf("                                        ");
+                                TFT.locate(0,180);
+                                TFT.printf("node is invalid");
+                                wait(1);
+                                TFT.locate(0,180);
+                                TFT.printf("                                        ");
+                                TFT.foreground(White);    
+                            }
+                    
+                            wait(2);       
+                            //send execution result
+                            //DBG.printf("send execution result\r\n");
+                        
+                            //calculate hmacCmd
+                            sprintf(p,"emma-%s-%s",emmaUID.c_str(),commandCmd.c_str());   
+                            hmacCmd = calculateMD5(p);
+                        
+                            sprintf(s,"{\"uid\":\"%s\",\"nType\":\"%s\",\"nAddr\":\"%s\",\"dType\":\"%s\",\"cmd\":\"%s\",\"from\":\"%s\",\"result\":\"%s\",\"hmac\":\"%s\"}",
+                            emmaUID.c_str(), commandNType.c_str(),commandNAddr.c_str(),commandDType.c_str(),commandCmd.c_str(),commandFrom.c_str(),execResult.c_str(),hmacCmd.c_str());
+                    
+                            trial=0;
+                            while(1) {
+                                if(trial>=2) {   //two times trial
+                                    DBG.printf("failed to send execution result\r\n");
+                                    break;    
+                                }
+                                sprintf(p,"/%s/api/controller/result",appNAME.c_str());
+                                rest.post(p,s);
+                                //rest.post("/emma/api/controller/result",s);   //working
+                                wait(2);
+                                str = rxBuf;
+                                if(str.rfind("/result") != std::string::npos) {
+                                    str.erase(str.begin(),str.begin()+str.rfind("/result"));
+                                    if(str.find("\"status\":\"success\"") != std::string::npos) {
+                                        DBG.printf("success to send execution result\r\n");
+                                        break;
+                                    }
+                                }
+                                //checkRxBuffer();
+                                trial++;
+                            }
+                            */
+                        }
+                    }
+                }
+                //clear text on lcd
+                TFT.locate(0,160);
+                TFT.printf("                                        ");
+                
+            }
             
             osDelay(5000);   
         }
@@ -1480,7 +1727,7 @@
         for(int i=0; i<NODES_MAX; i++) {
             if(!nodes[i].ipAddr.empty()) {
                 DBG.printf("restConn nodes[%d] is created\r\n",i);
-                nodes[i].restConn->begin(nodes[i].ipAddr.c_str(),16038,false);
+                nodes[i].restConn->begin(nodes[i].ipAddr.c_str(),REMOTE_TCP_PORT,false);
                 wait(1);
             } else {
                 DBG.printf("restConn nodes[%d] is NOT created\r\n",i);
@@ -2347,22 +2594,22 @@
     int ret=99;
     string str;
     Timer t;
-    TCPSocketConnection sock;
+    //TCPSocketConnection sock;
     
-    /*
     eth.init();
+    eth.connect();
+    connBodyLen = sprintf(connBody,"{\"uid\":\"005e00553533510334313732\",\"hmac\":\"9424c60e708d8e3d3dff6d23fb104339\"}");
+    sprintf(s,"POST /emma/api/controller/command HTTP/1.0\nHost: 36.80.35.8\nContent-Length:%d\n\n%s\r\n\r\n",connBodyLen,connBody);
     while(1) {
         //command
-        connBodyLen = sprintf(connBody,"{\"uid\":\"005e00553533510334313732\",\"hmac\":\"9424c60e708d8e3d3dff6d23fb104339\"}");
-        sprintf(s,"POST /emma/api/controller/command HTTP/1.0\nHost: 36.80.35.8\nContent-Length:%d\n\n%s\r\n\r\n",connBodyLen,connBody);
         str.clear();
         str = ethREST("36.80.35.8",8080,s);
         DBG.printf("[%d]str:%s\r\n",i,str.c_str());
         i++;
         wait(5);
     }
-    */
     
+    /*
     //start working as expected
     eth.init();
     eth.connect();
@@ -2403,6 +2650,7 @@
         wait(5);
     }
     //end working as expected
+    */
 }
 /*end emma mode*/
 
@@ -2815,12 +3063,45 @@
 string ethREST(string host, int port, string data) {
     char buf[1024];
     char s[256];
-    int ret;
+    int ret=99;
+    Timer t;
+    
+    t.start();
+    while(eth.linkstatus() && t.read() < 5 && ret !=0) {
+        ret = sock.connect(host.c_str(),port);
+    }
+    t.stop();
+    t.reset();
     
+    memset(buf,0,sizeof(buf));
+    if(sock.is_connected()) {
+        DBG.printf("sockConnect\r\n");
+        sprintf(s,"%s",data.c_str());
+        sock.send_all(s,sizeof(s)-1);
+        //wait(2);
+        wait(0.5);
+        
+        //receive return
+        t.start();
+        while(1) {
+            ret = sock.receive(buf, sizeof(buf));
+            if(ret<=0 || t.read() > 5) {
+                t.stop();
+                t.reset();
+                break;
+            }    
+        }
+        sock.close();    
+    } else {
+        DBG.printf("sockNotConnect\r\n");       
+    }
+    return buf;
+    
+    /*
     //eth.init(); //use DHCP
     eth.connect();
     
-    TCPSocketConnection sock;
+    //TCPSocketConnection sock;
     Timer t;
     
     sprintf(s,"%s",data.c_str());
@@ -2840,6 +3121,7 @@
     sock.close();
     eth.disconnect();
     return buf;
+    */
 }
 /*end emma connection function*/
 
@@ -2851,7 +3133,6 @@
     } else {
         ethAvailable = false;    
     }
-    eth.init(); //init ethernet
 }
 
 void isEthConnected(void) {
@@ -2861,6 +3142,9 @@
     string str;
     Timer t;
     
+    eth.init(); //init ethernet
+    eth.connect();
+    
     if(ethAvailable) {
         if(useProxy) {
             connHost = proxySERVER;