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:
40:77bd44f57ad3
Parent:
39:f51aa948acee
Child:
41:2d023bd80a9c
--- a/emmaCode.cpp	Wed Aug 19 15:04:50 2015 +0000
+++ b/emmaCode.cpp	Thu Aug 20 06:15:32 2015 +0000
@@ -54,6 +54,7 @@
 public:
     REST *restConn;
     NODES(REST *r);
+    int type;
     string macAddr;
     string ipAddr;
 };
@@ -707,7 +708,7 @@
         while(!emmaGetRegKey) {
             //DBG.printf("post:%s\r\n",s);
             str.clear();
-            str = ethGET(connHost,connPort,connData);
+            str = ethREST(connHost,connPort,connData);
             DBG.printf("rsp reg:%s\r\n",str.c_str());
 
             //check and save mqtt setting
@@ -781,7 +782,7 @@
         //verify registration
         while(!emmaRegistered && loop < 12){
             str.clear();
-            str = ethGET(connHost,connPort,connData);
+            str = ethREST(connHost,connPort,connData);
             DBG.printf("rsp vrf:%s\r\n",str.c_str());
             
             TFT.locate(0,40);
@@ -996,10 +997,12 @@
 
 void emmaModeOperation(void) {
     //char mqttClientId[32];
+    char connBody[256];
     char p[64];
     char q[32];
     char r[32];
     char s[4096];
+    int connBodyLen;
     int connPort;
     int loop=0;
     int trial=0;
@@ -1048,31 +1051,206 @@
     
     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());
-        //ethMQTTAttemptConnect(&client, &ipstack);
-        t.start();
-        DBG.printf("start\r\n");
         /*
-        while(true) {
-            if(!ipstack.getEth().linkstatus()) {
-                NVIC_SystemReset();  
+        //start new log indicator
+        seconds = time(NULL);
+        strftime(q, 32, "%Y-%m-%d %H:%M:%S",localtime(&seconds));
+        DBG.printf("newLog:%d\r\n",writeLog(q,"++++++++++Ethernet++++++++++"));
+        
+        //set ade7758 parameter
+        ADE.begin();
+        
+        ADE.writeRMSOffset(AIRMSOFFSET, BIRMSOFFSET, CIRMSOFFSET, AVRMSOFFSET, BVRMSOFFSET, CVRMSOFFSET);
+        
+        ADE.write16bits(AWG, 0);
+        ADE.write16bits(BWG, 0);
+        ADE.write16bits(CWG, 0);
+        ADE.write16bits(AVAG, 0);
+        ADE.write16bits(BVAG, 0);
+        ADE.write16bits(CVAG, 0);
+        
+        //check firmware update
+        
+        //execute last state of switches on board
+        
+        //get list of nodes from server
+        connBodyLen = sprintf(connBody,"{\"uid\":\"%s\",\"hmac\":\"%s\"}",emmaUID.c_str(),hmac.c_str());
+        
+        //sprintf(s,"GET /emma/api/controller/remotes?uid=%s&hmac=%s HTTP/1.0\nHost: %s\r\n\r\n",emmaUID.c_str(),hmac.c_str(),restSERVER.c_str());
+        sprintf(s,"POST /emma/api/controller/wifinodes HTTP/1.0\nHost: %s\nContent-Length:%d\n\n%s\r\n\r\n",restSERVER.c_str(),connBodyLen,connBody);
+        str.clear();
+        sscanf(restPORT.c_str(),"%d",&connPort);
+        str = ethREST(restSERVER,connPort,s);
+        DBG.printf("str:%s\r\n",str.c_str());
+        if(str.rfind("[{\"type\"") != std::string::npos) {
+            DBG.printf("get nodes from server\r\n");
+            str.erase(str.begin(),str.begin()+str.rfind("[{\"type\""));
+            str.erase(str.begin()+str.rfind("}]")+2,str.end());
+            
+            MbedJSONValue jsonValue;
+            parse(jsonValue,str.c_str());
+            char *parameter[3] = {"type","mac","ip"};
+            
+            TFT.locate(0,40);
+            TFT.printf("                                        ");
+            TFT.locate(0,40);
+            TFT.printf("get %d nodes from server",jsonValue.size());
+            wait(0.5);
+            TFT.locate(0,40);
+            TFT.printf("                                        ");
+            
+            //check whether nodes valid
+            bool validNodes = true;
+            for(int i=0; i<jsonValue.size(); i++) {
+                for(int j=0; j<3; j++) {
+                    validNodes = validNodes && jsonValue[i].hasMember(parameter[j]);
+                }    
+            }
+            DBG.printf("nodes validity:%d\r\n",validNodes);
+            
+            if(validNodes) {
+                for(int i=0; i<jsonValue.size(); i++) {
+                    string typeValue = jsonValue[i][parameter[0]].get<std::string>();
+                    string macValue = jsonValue[i][parameter[1]].get<std::string>();
+                    string ipValue = jsonValue[i][parameter[2]].get<std::string>();
+                    nodes[i].type = typeValue;
+                    nodes[i].macAddr = macValue;
+                    nodes[i].ipAddr = ipValue;
+                    DBG.printf("nodes[%d]type:%s\r\n",i,nodes[i].type.c_str());
+                    DBG.printf("nodes[%d]mac:%s\r\n",i,nodes[i].macAddr.c_str());
+                    DBG.printf("nodes[%d]ip:%s\r\n",i,nodes[i].ipAddr.c_str());
+                }
             }
-            if(t.read_ms() > 5000) {
-                if(publish(&client,&ipstack) != 0)
-                    ethMQTTAttemptConnect(&client, &ipstack);
-                t.reset();
+            
+        } else {
+            DBG.printf("no nodes from server\r\n");    
+        }
+        
+        //define thread
+        osThreadDef(energyThread, osPriorityBelowNormal, (8*DEFAULT_STACK_SIZE));
+        //create thread
+        osThreadCreate(osThread(energyThread),NULL);
+        
+        tPanelEnergy.start();
+        tPanel.start();
+        tNodes.start();
+        wait(1);
+        while(1) {
+            //checkVoltagePower();  //need revision to support ethernet
+            
+            //panelEnergy, panelVoltage, and panelPower
+            if(tPanelEnergy.read() > 30.0f) {
+                DBG.printf("[%d]WattHR for each phase: %.2f, %.2f, %.2f\r\n", loop, AWattHr, BWattHr, CWattHr);
+                TFT.locate(0,60);
+                TFT.printf("                                                  ");
+                TFT.locate(0,60);
+                TFT.printf("[%d]WHR: %.1f, %.1f, %.1f", loop, AWattHr, BWattHr, CWattHr);
+                
+                DBG.printf("VRMS for each phase: %.2f, %.2f, %.2f\r\n", AVrms, BVrms, CVrms);
+                TFT.locate(0,80);
+                TFT.printf("                                                  ");
+                TFT.locate(0,80);
+                TFT.printf("VRMS: %.1f, %.1f, %.1f", AVrms, BVrms, CVrms);
+                
+                DBG.printf("Watt for each phase: %.2f, %.2f, %.2f\r\n", AWatt, BWatt, CWatt);
+                TFT.locate(0,100);
+                TFT.printf("                                                  ");
+                TFT.locate(0,100);
+                TFT.printf("Watt: %.1f, %.1f, %.1f", AWatt, BWatt, CWatt);
+                
+                if(newEnergyData) {
+                    //for(int i=1; i<4; i++) {
+                    for(int i=1; i<2; i++) {
+                        DBG.printf("sending channel: %d\r\n",i);
+                        if(i==1){
+                            XWattHr = AWattHr;
+                            XVrms = AVrms;
+                            XWatt = AWatt;    
+                        } else if(i==2) {
+                            XWattHr = BWattHr;
+                            XVrms = BVrms;
+                            XWatt = BWatt;
+                        } else {
+                            XWattHr = CWattHr;
+                            XVrms = CVrms;
+                            XWatt = CWatt;
+                        }
+                        
+                        if(XWattHr != 0.0f) {
+                            seconds = time(NULL);
+                            strftime(q, 32, "%Y-%m-%d %H:%M:%S",localtime(&seconds));
+                        
+                            //calculate hmacTime
+                            for(int j=0; j<sizeof(p); j++) {
+                                p[j]=0; }
+                            sprintf(p,"emma-%s-%s",emmaUID.c_str(),q);   
+                            hmacTime = calculateMD5(p);
+                            
+                            connBodyLen = sprintf(connBody,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"%s\",\"energy\":%.2f,\"voltage\":%.2f,\"power\":%.2f}",
+                            emmaUID.c_str(),hmacTime.c_str(),q,XWattHr,XVrms,XWatt);
+                            //DBG.printf("dataEnergy:\r\n%s\r\n",connBody);
+                            
+                            sprintf(r,"POST /emma/api/controller/energy/%d HTTP/1.0\nHost:%s\nContent-Length:%d\n\n%s\r\n\r\n",i,restSERVER.c_str(),connBodyLen,connBody);
+                            
+                            str.clear();
+                            sscanf(restPORT.c_str(),"%d",&connPort);
+                            str = ethREST(restSERVER,connPort,r);
+                            if(str.find("\"status\":\"success\"") != std::string::npos) {
+                                //logging purpose
+                                seconds = time(NULL);
+                                strftime(q, 32, "%Y-%m-%d %H:%M:%S",localtime(&seconds));
+                                DBG.printf("logPE:%d\r\n",writeLog(q,"sendEnergyData success"));
+                            
+                                DBG.printf("send channel: %d success\r\n",i);
+                                TFT.foreground(Green);
+                                TFT.locate(0,120);
+                                TFT.printf("                                        ");
+                                TFT.locate(0,120);
+                                TFT.printf("send ch%d success",i);
+                                wait(1);
+                                TFT.locate(0,120);
+                                TFT.printf("                                        ");
+                                TFT.foreground(White);    
+                            } else {
+                                //logging purpose
+                                seconds = time(NULL);
+                                strftime(q, 32, "%Y-%m-%d %H:%M:%S",localtime(&seconds));
+                                DBG.printf("logPE:%d\r\n",writeLog(q,"sendEnergyData failed"));
+                                
+                                DBG.printf("send channel: %d failed\r\n",i);
+                                TFT.foreground(Red);
+                                TFT.locate(0,120);
+                                TFT.printf("                                        ");
+                                TFT.locate(0,120);
+                                TFT.printf("send ch%d failed",i);
+                                wait(1);
+                                TFT.locate(0,120);
+                                TFT.printf("                                        ");
+                                TFT.foreground(White);    
+                            }
+                        }
+                    }
+                    
+                    newEnergyData = false;
+                }
+                
+                tPanelEnergy.reset();
+                loop++;    
             }
-            client.yield(100);  //allow MQTT client to receive message
+            
+            //panel environment
+            
+            osDelay(5000);   
         }
         */
+        
     } else if(wifiConnected) {
         DBG.printf("emmaModeOperation - wifi\r\n");
         
         //start new log and dbg indicator
         seconds = time(NULL);
         strftime(q, 32, "%Y-%m-%d %H:%M:%S",localtime(&seconds));
-        DBG.printf("newLog:%d\r\n",writeLog(q,"++++++++++++++++++++"));
+        DBG.printf("newLog:%d\r\n",writeLog(q,"++++++++++WiFi++++++++++"));
         //DBG.printf("newDbg:%d\r\n",writeDbg(q,"++++++++++++++++++++"));
     
         //do not delete code below - indicator that esp need to MODE=B and esp.ready() to work
@@ -1135,6 +1313,8 @@
         //execute last state of switches on board
     
         //get list of nodes from server
+        /*
+        //working
         sprintf(s,"/emma/api/controller/remotes?uid=%s&hmac=%s",emmaUID.c_str(),hmac.c_str());
         rest.get(s);
         for(int i=0; i<sizeof(s); i++) {
@@ -1181,6 +1361,72 @@
         } else {
             DBG.printf("no nodes from server\r\n");    
         }
+        */
+        
+        _ESP.attach(&rxInterrupt,Serial::RxIrq);
+        
+        //get list of nodes from server (post)
+        sprintf(p,"/emma/api/controller/wifinodes");
+        sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\"}",emmaUID.c_str(),hmacTime.c_str());
+        rest.post(p,s);
+        wait(2);
+        str = rxBuf;
+        if(str.rfind("[{\"type\"") != std::string::npos) {
+            DBG.printf("get nodes from server\r\n");
+            str.erase(str.begin(),str.begin()+str.rfind("[{\"type\""));
+            str.erase(str.begin()+str.rfind("}]")+2,str.end());
+            //DBG.printf("strCrop:%s\r\n",str.c_str());
+            
+            //start special handler
+            while(1){
+                if(str.find("}],") != std::string::npos) {
+                    str.erase(str.begin()+str.find("}],")+1,str.begin()+str.find("}],")+2);    
+                } else {
+                    break;
+                }
+            }
+            //end special handler
+            
+            DBG.printf("strCrop:%s\r\n",str.c_str());
+            
+            MbedJSONValue jsonValue;
+            parse(jsonValue,str.c_str());
+            char *parameter[3] = {"type","mac","ip"};
+            
+            TFT.locate(0,40);
+            TFT.printf("                                        ");
+            TFT.locate(0,40);
+            TFT.printf("get %d nodes from server",jsonValue.size());
+            wait(0.5);
+            TFT.locate(0,40);
+            TFT.printf("                                        ");
+            
+            //check whether nodes valid
+            bool validNodes = true;
+            for(int i=0; i<jsonValue.size(); i++) {
+                for(int j=0; j<3; j++) {
+                    validNodes = validNodes && jsonValue[i].hasMember(parameter[j]);
+                }    
+            }
+            DBG.printf("nodes validity:%d\r\n",validNodes);
+            
+            if(validNodes) {
+                for(int i=0; i<jsonValue.size(); i++) {
+                    int typeValue = jsonValue[i][parameter[0]].get<int>();
+                    string macValue = jsonValue[i][parameter[1]].get<std::string>();
+                    string ipValue = jsonValue[i][parameter[2]].get<std::string>();
+                    nodes[i].type = typeValue;
+                    nodes[i].macAddr = macValue;
+                    nodes[i].ipAddr = ipValue;
+                    DBG.printf("nodes[%d]type:%d\r\n",i,nodes[i].type);
+                    DBG.printf("nodes[%d]mac:%s\r\n",i,nodes[i].macAddr.c_str());
+                    DBG.printf("nodes[%d]ip:%s\r\n",i,nodes[i].ipAddr.c_str());
+                }
+            }
+            
+        } else {
+            DBG.printf("no nodes from server\r\n");    
+        }
         
         /*
         //working
@@ -1204,6 +1450,9 @@
         t.reset();
         */
         
+        //disable UART2
+        NVIC_DisableIRQ(USART2_IRQn);
+        
         //init rest to remotes
         for(int i=0; i<NODES_MAX; i++) {
             if(!nodes[i].ipAddr.empty()) {
@@ -1216,7 +1465,10 @@
             }
         }
         
-        _ESP.attach(&rxInterrupt,Serial::RxIrq);
+        //enable UART2
+        NVIC_EnableIRQ(USART2_IRQn);
+        
+        //_ESP.attach(&rxInterrupt,Serial::RxIrq);
         
         //define thread
         osThreadDef(energyThread, osPriorityBelowNormal, (8*DEFAULT_STACK_SIZE));
@@ -1474,7 +1726,12 @@
             }
             
             //command
-            rest.get("/emma/api/controller/command");
+            sprintf(r,"/emma/api/controller/command");
+            sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\"}",
+            emmaUID.c_str(),hmacTime.c_str());
+            //rest.get("/emma/api/controller/command");
+            rest.post(r,s);
+            
             checkRxBuffer();
             if(newCommand) {
                 DBG.printf("newCommand:\r\n%s\r\n",globalCommand.c_str());
@@ -1485,7 +1742,7 @@
                 
                 MbedJSONValue jsonValue;
                 parse(jsonValue,globalCommand.c_str());
-                char *parameter[5] = {"name","nType","nAddr","dType","cmd"};
+                char *parameter[5] = {"from","nType","nAddr","dType","cmd"};
                 
                 //check whether command is valid
                 bool validCommand = true;
@@ -1495,7 +1752,7 @@
                 DBG.printf("command validity:%d\r\n",validCommand);
                 
                 if(validCommand) {
-                    string commandName = jsonValue[parameter[0]].get<std::string>();
+                    string commandFrom = 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>();
@@ -1535,6 +1792,7 @@
                             //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());
+                            DBG.printf("s:%s\r\n",s);
                             
                             trial=0;
                             while(1) {
@@ -1593,8 +1851,8 @@
                         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\",\"name\":\"%s\",\"result\":\"%s\",\"hmac\":\"%s\"}",
-                        emmaUID.c_str(), commandNType.c_str(),commandNAddr.c_str(),commandDType.c_str(),commandCmd.c_str(),commandName.c_str(),execResult.c_str(),hmacCmd.c_str());
+                        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) {
@@ -2108,7 +2366,7 @@
                 sprintf(s,"<?xml version=\"1.0\" encoding=\"utf-8\"?><app_cmd cmd=\"5\" /><app_data code=\"%s\"/>\r\n",nodeCmd.c_str());
                 str.assign(s);
                 DBG.printf("str value:%s\r\n",str.c_str());                            
-                string rcv = ethGET(nodeIP,REMOTE_TCP_PORT,str); // cause mqtt to stop
+                string rcv = ethREST(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) {
@@ -2404,14 +2662,14 @@
 /*end emma node*/
 
 /*start emma connection function*/
-string ethGET(string host, int port, string url) {
+string ethREST(string host, int port, string data) {
     char buf[1024];
     char s[256];
     int ret;
     TCPSocketConnection sock;
     Timer t;
     
-    sprintf(s,"%s",url.c_str());
+    sprintf(s,"%s",data.c_str());
     sock.connect(host.c_str(),port);
     sock.send_all(s,sizeof(s)-1);
     wait(2);
@@ -2464,7 +2722,7 @@
         
         t.start();
         while(1) {
-            str = ethGET(connHost,connPort,s);
+            str = ethREST(connHost,connPort,s);
             if(str.find("OK") != std::string::npos) {
                 t.stop();
                 ethConnected = true;