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

Revision:
4:76ab12e2f8a3
Parent:
3:e7fcbe6deb19
Child:
5:d00233dd36f5
--- a/emmaCode.cpp	Fri Jul 03 08:12:09 2015 +0000
+++ b/emmaCode.cpp	Wed Jul 08 13:33:14 2015 +0000
@@ -25,6 +25,7 @@
 
 //emma settings
 string emmaUID;
+string hmac;
 string platformDOMAIN;
 string platformKEY;
 string platformSECRET;
@@ -35,6 +36,20 @@
 string proxyPORT;
 string proxyAUTH;
 
+//nodes settings
+class NODES {
+public:
+    REST *restConn;
+    NODES(REST *r);
+    string macAddr;
+    string ipAddr;
+};
+NODES::NODES(REST *r) {
+    restConn = r;    
+}
+REST restObj[NODES_MAX] = {REST(&esp),REST(&esp),REST(&esp),REST(&esp),REST(&esp)};
+NODES nodes[NODES_MAX] = {NODES(&restObj[0]),NODES(&restObj[1]),NODES(&restObj[2]),NODES(&restObj[3]),NODES(&restObj[4])};
+
 //ade7758 variables
 uint16_t AWattHrValue, BWattHrValue, CWattHrValue;
 uint16_t AVAHrValue, BVAHrValue, CVAHrValue;
@@ -42,6 +57,10 @@
 long BWattHrSum = 0;    
 long CWattHrSum = 0;
 float AWattHr, BWattHr, CWattHr;
+float AVrms, BVrms, CVrms;
+float AIrms, BIrms, CIrms;
+float AWatt, BWatt, CWatt;
+float XWattHr,XVrms,XWatt;
 
 //variables
 bool ethAvailable = false;
@@ -52,11 +71,10 @@
 bool useProxy = false;
 bool newCommand = false;
 string globalCommand;
-//char globCmd[255];
-//char *globCmd;
-string globCmd;
+string rxBuf;
 
 void emmaInit(void) {
+    char s[64];
     DBG.baud(19200);
     DBG.printf("\r\nemmaInit\r\n");
     
@@ -65,6 +83,12 @@
     //emmaUID = readSetting("emmaUID");
     emmaUID = "066eff575349896767073038";
     DBG.printf("emmaUID:%s\r\n",emmaUID.c_str());
+    //calculate hmac
+    for(int i=0; i<sizeof(s); i++) {
+        s[i]=0; }
+    sprintf(s,"emma-%s",emmaUID.c_str());   
+    hmac = calculateMD5(s);
+    DBG.printf("hmac:%s\r\n",hmac.c_str());
     //platformDOMAIN = readSetting("platformDOMAIN");
     platformDOMAIN = "testdulu";
     DBG.printf("platformDOMAIN:%s\r\n",platformDOMAIN.c_str());
@@ -129,12 +153,12 @@
                     for(int i=0; i<2; i++) {
                         if(jsonValue.hasMember(parameter[i])) {
                             string val = jsonValue[parameter[i]].get<std::string>();
-                            int st = writeSetting(parameter[i],val.c_str());
-                            if(st) {
-                                DBG.printf("%s is saved\r\n",parameter[i]);
-                            } else {
-                                DBG.printf("%s is not saved\r\n",parameter[i]);
-                            }
+                            //int st = writeSetting(parameter[i],val.c_str());
+                            //if(st) {
+                            //    DBG.printf("%s is saved\r\n",parameter[i]);
+                            //} else {
+                            //    DBG.printf("%s is not saved\r\n",parameter[i]);
+                            //}
                         }
                     }
                 } 
@@ -289,7 +313,7 @@
     int loop = 0;
     string connData;
     string connHost;
-    string hmac;
+    //string hmac;
     string str;
     string regKey;
     Timer t;
@@ -300,11 +324,11 @@
     DBG.printf("wifiConnected:%d\r\n",wifiConnected);
     
     //calculate hmac
-    for(int i=0; i<sizeof(s); i++) {
-        s[i]=0; }
-    sprintf(s,"emma-%s",emmaUID.c_str());   
-    hmac = calculateMD5(s);
-    DBG.printf("hmac:%s\r\n",hmac.c_str());
+    //for(int i=0; i<sizeof(s); i++) {
+    //    s[i]=0; }
+    //sprintf(s,"emma-%s",emmaUID.c_str());   
+    //hmac = calculateMD5(s);
+    //DBG.printf("hmac:%s\r\n",hmac.c_str());
     
     if(wifiConnected) {
         DBG.printf("emmaModeRegister - wifi\r\n");
@@ -575,17 +599,13 @@
 
 void emmaModeOperation(void) {
     char mqttClientId[32];
-    char mqttTopic[64];
-    char mqttPayload[64];
+    char r[32];
     char s[512];
     int loop=0;
-    string hmac;
+    //string hmac;
     string str;
     Timer t;
-    Timer tEnergy;
-    Timer tNodeTemp;
-    
-    //DBG.printf("emmaModeOperation\r\n");
+    Timer tNodes;
     
     //check connected interface
     connectedIface();
@@ -599,11 +619,11 @@
     //get list of nodes from server
     
     //calculate hmac
-    for(int j=0; j<sizeof(s); j++) {
-        s[j]=0; }
-    sprintf(s,"emma-%s",emmaUID.c_str());   
-    hmac = calculateMD5(s);
-    DBG.printf("hmac:%s\r\n",hmac.c_str());
+    //for(int j=0; j<sizeof(s); j++) {
+    //    s[j]=0; }
+    //sprintf(s,"emma-%s",emmaUID.c_str());   
+    //hmac = calculateMD5(s);
+    //DBG.printf("hmac:%s\r\n",hmac.c_str());
     
     //operation wifi
     if(wifiConnected) {
@@ -618,19 +638,22 @@
         sprintf(mqttClientId,"emma/%s",emmaUID.c_str());
     
         if(mqtt.begin(mqttClientId, platformKEY.c_str(), platformSECRET.c_str(), 120, 1)) {
-            mqtt.lwt("/lwt", "offline", 0, 0);
+            //mqtt.lwt("/lwt", "offline", 0, 0);
             mqtt.connectedCb.attach(&mqttConnected);
             mqtt.disconnectedCb.attach(&mqttDisconnected);
-            mqtt.publishedCb.attach(&mqttPublished);
-            mqtt.dataCb.attach(&mqttData);
+            //mqtt.publishedCb.attach(&mqttPublished);
+            //mqtt.dataCb.attach(&mqttData);
             mqtt.connect(MQTT_HOST,MQTT_PORT,false);
             DBG.printf("emma: success to setup mqtt\r\n");    
         }
-        
         DBG.printf("emma: system started\r\n");
         
-        //define thread
-        osThreadDef(energyThread, osPriorityBelowNormal, (4*DEFAULT_STACK_SIZE));
+        t.start();
+        while(t.read_ms() < 5000) {
+            esp.process();    
+        }
+        t.stop();
+        t.reset();
         
         //set ade7758 parameter
         ADE.begin();
@@ -650,7 +673,7 @@
         ADE.write16bits(BVAG, 0);
         ADE.write16bits(CVAG, 0);
         
-        ADE.AWhLSB = 0.00010846;
+        ADE.AWhLSB = 0.00006025556;
         ADE.BWhLSB = 0.25075167;
         ADE.CWhLSB = 0.25075167;
         
@@ -658,63 +681,79 @@
         ADE.BVAhLSB = 0;
         ADE.CVAhLSB = 0;
         
+        //init rest to server
+        if(rest.begin(EMMA_SERVER_HOST,8080,false)) {
+            DBG.printf("rest to server is created\r\n");
+        } else {
+            DBG.printf("rest to server is NOT created\r\n");
+        }
+        
+        //preset nodes' macAddr and ipAddr
+        nodes[0].macAddr = "002629034222";
+        nodes[0].ipAddr = "192.168.2.15";
+        nodes[1].macAddr = "00262903424e";
+        nodes[1].ipAddr = "192.168.2.32";
+        
+        //init rest to remotes
+        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);
+                wait(1);
+            } else {
+                DBG.printf("restConn nodes[%d] is NOT created\r\n",i);
+                wait(1);
+            }
+        }
+        
+        _ESP.attach(&rxInterrupt,Serial::RxIrq);
+        
+        //define thread
+        osThreadDef(energyThread, osPriorityBelowNormal, (4*DEFAULT_STACK_SIZE));
         //create thread
         osThreadCreate(osThread(energyThread),NULL);
         
         t.start();
-        tEnergy.start();
-        tNodeTemp.start();
+        tNodes.start();
+        wait(1);
         while(1) {
-            esp.process();
-            
-            //fatal exception handler - use only if rest function is used?
-            
-            if(!esp.ready()) {  //ready is true
-                DBG.printf("exception handler - start\r\n");
-                while(1) {
-                    _ESP.printf("MODE=B");
-                    char rcv[16] = {};
-                    rcvReply(rcv,1000);
-                    str = rcv;
-                    if(str.find("MODE=B_OK") != std::string::npos)
-                        break;
-                }
-                wait(1);
-                if(mqtt.begin(mqttClientId, platformKEY.c_str(), platformSECRET.c_str(), 120, 1)) {
-                    mqtt.lwt("/lwt", "offline", 0, 0);
-                    mqtt.connectedCb.attach(&mqttConnected);
-                    mqtt.disconnectedCb.attach(&mqttDisconnected);
-                    mqtt.publishedCb.attach(&mqttPublished);
-                    mqtt.dataCb.attach(&mqttData);
-                    mqtt.connect(MQTT_HOST,MQTT_PORT,false);
-                    DBG.printf("emma: success to setup mqtt\r\n");    
+            checkRxBuffer();
+            checkVoltagePower();
+            //panelEnergy, panelVoltage, and panelPower
+            if(t.read_ms() > 10000) {
+                DBG.printf("[%d]WattHR for each phase: %.2f, %.2f, %.2f\r\n", loop, AWattHr, BWattHr, CWattHr);
+                DBG.printf("VRMS for each phase: %.2f, %.2f, %.2f\r\n", AVrms, BVrms, CVrms);
+                DBG.printf("Watt for each phase: %.2f, %.2f, %.2f\r\n", AWatt, BWatt, CWatt);
+                
+                //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;
+                    }
+                    sprintf(r,"/emma/api/controller/energy/%d",i);
+                    sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"2015-06-09 12:32:12\",\"energy\":%.2f,\"voltage\":%.2f,\"power\":%.2f}",
+                    emmaUID.c_str(),hmac.c_str(),XWattHr,XVrms,XWatt);
+                    rest.post(r,s);
+                    wait(2);
+                    if(rxBuf.find("\"status\":\"success\"") != std::string::npos) {
+                        DBG.printf("send channel: %d success\r\n",i);    
+                    } else {
+                        DBG.printf("send channel: %d failed\r\n",i);    
+                    }
                 }
-                DBG.printf("exception handler - finish\r\n");
-            }
-            //wait(0.5);
-            
-            //energy
-            if(tEnergy.read_ms() > 10000) {
-                //DBG.printf("getEnergy\r\n");
-                DBG.printf("WattHR for each phase: %.2f, %.2f, %.2f\r\n", AWattHr, BWattHr, CWattHr);
-                
-                //send energy data
-                if(rest.begin("192.168.131.200",8080,false)) {
-                    DBG.printf("sending energy\r\n");
-                    for(int j=0; j<sizeof(s); j++) {
-                        s[j]=0; }
-                    sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"2015-06-09 12:32:12\",\"energy\":%.2f,\"voltage\":%.2f,\"power\":%.2f}",
-                    emmaUID.c_str(),hmac.c_str(),AWattHr,AWattHr,AWattHr);
-                    rest.post("/emma/api/controller/energy/1",s);
-                    for(int j=0; j<sizeof(s); j++) {
-                        s[j]=0; }
-                    rest.getResponse(s,sizeof(s));
-                    DBG.printf("Response: %s\r\n",s);
-                } else {
-                    DBG.printf("not sending energy\r\n");    
-                }
-                
-                tEnergy.reset();    
+                t.reset();
+                loop++;    
             }
             
             //nodeTemp
@@ -769,6 +808,7 @@
             //}
             
             //check for new command
+            /*
             if(newCommand) {
                 DBG.printf("newCommand\r\n");
                 MbedJSONValue jsonValue;
@@ -855,7 +895,8 @@
                 }
                 newCommand = false;
             }
-            osDelay(100);    
+            */
+            osDelay(5000);    
         }
     }
     //operation eth
@@ -1138,14 +1179,14 @@
     DBG.printf("download finished\r\n");
 }
 
-/*start energyThread*/
+/*start energy related*/
 void energyThread(void const*) {
     while(1) {
         //DBG.printf("insideEnergyThread\r\n");
         //osDelay(5000);
         
         //calculate energy
-        DBG.printf("[energyThread start]\r\n");
+        DBG.printf("energyThread-start\r\n");
         float period = 0;
         AWattHrSum = 0;
         BWattHrSum = 0;
@@ -1160,12 +1201,83 @@
         AWattHr = AWattHrSum * ADE.AWhLSB;
         BWattHr = BWattHrSum * ADE.BWhLSB;
         CWattHr = CWattHrSum * ADE.CWhLSB;
-        //osDelay(5000);
         
-        DBG.printf("[energyThread finish]\r\n");
+        DBG.printf("energyThread-finish\r\n");
     }
 }
-/*end energyThread*/
+void checkVoltagePower() {
+    //check if voltage or power violates threshold
+    char s[256];
+    string str;
+    
+    //DBG.printf("checkVoltagePower-start\r\n");
+
+    AVrms = ADE.VRMS(PHASE_A) * 2*0.000158;   //constants are from calculateVRMS function
+    BVrms = ADE.VRMS(PHASE_B) * 2*0.000157;
+    CVrms = ADE.VRMS(PHASE_C) * 2*0.000156;
+    
+    AIrms = ADE.IRMS(PHASE_A) * 0.0000125;  //constants are from calculateIRMS function
+    BIrms = ADE.IRMS(PHASE_B) * 0.0000123;
+    CIrms = ADE.IRMS(PHASE_C) * 0.0000124;
+    
+    AWatt = AVrms * AIrms;
+    BWatt = BVrms * BIrms;
+    CWatt = CVrms * CIrms;
+    
+    if(AVrms > VRMSTHRESHOLD || AWatt > WATTTHRESHOLD) {
+        DBG.printf("alert on ch1\r\n");
+        sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"2015-06-09 12:32:12\",\"voltage\":%.2f,\"power\":%.2f}",
+        emmaUID.c_str(),hmac.c_str(),AVrms,AWatt);
+        rest.post("/emma/api/controller/alert/1",s);
+        wait(2);
+        str = rxBuf;
+        if(str.rfind("/alert/1") != std::string::npos) {
+            str.erase(str.begin(),str.begin()+str.rfind("/alert/1"));
+            if(str.find("\"status\":\"success\"") != std::string::npos) {
+                DBG.printf("send alert ch1 success\r\n");
+            } else {
+                DBG.printf("send alert ch1 failed\r\n");
+            }
+        }
+    }
+    
+    if(BVrms > VRMSTHRESHOLD || BWatt > WATTTHRESHOLD) {
+        DBG.printf("alert on ch2\r\n");
+        sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"2015-06-09 12:32:12\",\"voltage\":%.2f,\"power\":%.2f}",
+        emmaUID.c_str(),hmac.c_str(),BVrms,BWatt);
+        rest.post("/emma/api/controller/alert/2",s);
+        wait(2);
+        str = rxBuf;
+        if(str.rfind("/alert/2") != std::string::npos) {
+            str.erase(str.begin(),str.begin()+str.rfind("/alert/2"));
+            if(str.find("\"status\":\"success\"") != std::string::npos) {
+                DBG.printf("send alert ch2 success\r\n");
+            } else {
+                DBG.printf("send alert ch2 failed\r\n");
+            }
+        }
+    }
+    
+    if(CVrms > VRMSTHRESHOLD || CWatt > WATTTHRESHOLD) {
+        DBG.printf("alert on channel C\r\n");
+        DBG.printf("alert on ch3\r\n");
+        sprintf(s,"{\"uid\":\"%s\",\"hmac\":\"%s\",\"time\":\"2015-06-09 12:32:12\",\"voltage\":%.2f,\"power\":%.2f}",
+        emmaUID.c_str(),hmac.c_str(),CVrms,CWatt);
+        rest.post("/emma/api/controller/alert/3",s);
+        wait(2);
+        str = rxBuf;
+        if(str.rfind("/alert/3") != std::string::npos) {
+            str.erase(str.begin(),str.begin()+str.rfind("/alert/3"));
+            if(str.find("\"status\":\"success\"") != std::string::npos) {
+                DBG.printf("send alert ch3 success\r\n");
+            } else {
+                DBG.printf("send alert ch3 failed\r\n");
+            }
+        }
+    }
+    //DBG.printf("checkVoltagePower-finish\r\n");
+}
+/*end energy related*/
 
 /*start wifi mqtt*/
 void wifiCb(void* response) {
@@ -1190,7 +1302,6 @@
     char mqttTopic[64];
     sprintf(mqttTopic,"%s/%s/command",platformDOMAIN.c_str(),emmaUID.c_str());
     mqtt.subscribe(mqttTopic);
-    //mqtt.subscribe(mqttTopic,1);
 }
 void mqttDisconnected(void* response) {
     DBG.printf("MQTT Disconnected\r\n");    
@@ -1237,6 +1348,32 @@
         }
     }
 }
+void rxInterrupt(void) {
+    char c;
+    
+    while(_ESP.readable()) {
+        c = _ESP.getc();
+        if(c != 0) {    //char is not null
+            rxBuf += c;
+        }
+    }
+}
+void checkRxBuffer(void) {
+    //check new command
+    if(rxBuf.rfind("/command") != std::string::npos) {
+        rxBuf.erase(rxBuf.begin(),rxBuf.begin()+rxBuf.rfind("/command"));
+        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;
+            //DBG.printf("gC:%s\r\n",globalCommand.c_str());
+            newCommand = true;
+        }
+    }
+    
+    //clear rxBuf
+    rxBuf.clear();
+}
 /*end wifi rest*/
 
 /*start eth mqtt*/
@@ -1539,13 +1676,13 @@
             sscanf(proxyPORT.c_str(),"%d",&connPort);
             for(int i=0; i<sizeof(s); i++) {
                 s[i]=0; }
-            sprintf(s,"http://%s:%d/emma/api/web/test HTTP/1.0\nHost: %s\r\n\r\n",EMMA_SERVER_HOST,EMMA_SERVER_PORT,EMMA_SERVER_HOST);
+            sprintf(s,"http://%s:%d/emma/api/controller/test HTTP/1.0\nHost: %s\r\n\r\n",EMMA_SERVER_HOST,EMMA_SERVER_PORT,EMMA_SERVER_HOST);
         } else {
             connHost = EMMA_SERVER_HOST;
             connPort = EMMA_SERVER_PORT;
             for(int i=0; i<sizeof(s); i++) {
                 s[i]=0; }
-            sprintf(s,"/emma/api/web/test");
+            sprintf(s,"/emma/api/controller/test");
         }
         wait(1);
         t.start();