STM32L476

Dependencies:   MbedJSONValue SDFileSystem WConstants mbed-dev DS1820 TinyGPSPlus epd1in54

Fork of A_SSL_Main by SilentSensors

Revision:
10:a4526c9b8332
Parent:
9:4ac09d77e2a0
Child:
11:9b49bd5a5f8c
--- a/main.cpp	Wed Nov 07 03:42:37 2018 +0000
+++ b/main.cpp	Fri Nov 09 03:12:35 2018 +0000
@@ -36,6 +36,19 @@
 PinName rst; PinName dc; PinName busy; PinName mosi; PinName miso; PinName sclk; PinName cs;
 unsigned char frame_black[EPD_HEIGHT*EPD_WIDTH/8];
 Epd epd = Epd(PB_5, PB_4, PB_3, PA_8, PC_4, PC_7, PB_10);
+
+const  char * system_message;                       //Journey configuration to be received from server
+int deviceID = 1;
+double longTest,latTest;
+int tyear,tmonth,tday,thour,tmin,tsec;     
+float liquidTemp = 0;
+char cValt[32];
+char chr_s[600];
+std::string s;
+const char * parameter;
+int msg_index;
+double geofencesNum;
+int geotest;
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 
@@ -43,19 +56,20 @@
 //      Polygon geofence
 // the last vertix should be the same as the first vertix
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
-int pnpoly(int nvert, double *vertx, double *verty, double testx, double testy)
+int pnpoly(int nvert, double *vertLong, double *vertLat, double testLong, double testLat)
 {
+  //Returns 1 if test point is inside polygon, zero otherwise
+  //last vertix should be the same as the first
   int i, j, c = 0;
   for (i = 0, j = nvert-1; i < nvert; j = i++) {
-    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
-     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
+    if ( ((vertLat[i]>testLat) != (vertLat[j]>testLat)) &&
+     (testLong < (vertLong[j]-vertLong[i]) * (testLat-vertLat[i]) / (vertLat[j]-vertLat[i]) + vertLong[i]) )
        c = !c;
   }
   return c;
 }
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
-
 double distanceBetween(double lat1, double long1, double lat2, double long2)
 {
   // returns distance in meters between two positions, both specified
@@ -85,6 +99,8 @@
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 int inCircle(double xcentre, double ycentre, double xedge, double yedge, double testx, double testy)
 {
+    //Returns 1 if test point is inside circle, zero otherwise
+    //The circle is defined by centre and a point on the circumference 
     double distance;
     int test;
     double radius;
@@ -128,10 +144,9 @@
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 int Display(float t, int g)
 {
-
-    char cValt[32];
-    sprintf(cValt,"%.2f", t);   
-     
+Epd epd = Epd(PB_5, PB_4, PB_3, PA_8, PC_4, PC_7, PB_10);
+    
+    sprintf(cValt,"%.2f", t);    
     memset(frame_black, 0xFF, sizeof(unsigned char)*EPD_HEIGHT*EPD_WIDTH/8);
     if (epd.Init(lut_full_update) != 0) {
         return -1;
@@ -141,7 +156,7 @@
     epd.DrawStringAt(frame_black, 60, 30, cValt, &Font24, COLORED);
     epd.DrawStringAt(frame_black, 0, 70, "In Geofence?", &Font24, COLORED);
     if (g == 1){
-    epd.DrawStringAt(frame_black, 60, 90, "In G1", &Font24, COLORED);
+    epd.DrawStringAt(frame_black, 60, 90, "In Geo", &Font24, COLORED);
     }
     else {
         epd.DrawStringAt(frame_black, 60, 90, "No", &Font24, COLORED);
@@ -166,7 +181,7 @@
         serial.printf("Unable to write the file\r\n");
         return -1;
     } else {
-        fprintf(fp, "----New File----\r\n");
+        fprintf(fp, "Silent Hub - Log\r\n");
         fclose(fp);
         serial.printf("File successfully written!\r\n");
         return 0; //success
@@ -210,29 +225,29 @@
 //      JSON serialize
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 //ToDo: pass arguments, currently some dummy values
-string jsonSerializeDeviceToSystem(int deviceID, float xtest, float ytest, float liquidTemp, int tday, int tmonth, int tyear, int thour, int tmin, int tsec)
+//geoFenceNum: the geofence entered or left, value: 1(entered), 2(left)
+string jsonSerializeDeviceToSystem(int deviceID, float longTest, float latTest, int geoFenceNum, int value, float liquidTemp, int tday, int tmonth, int tyear, int thour, int tmin, int tsec)
 {
     MbedJSONValue statusReport;
     std::string s;
     char SDtime[100];
-    sprintf(SDtime,"%d/%d/%d - %d:%d:%d\r\n", tday, tmonth, tyear, thour, tmin, tsec);
+    sprintf(SDtime,"%d-%d-%d - %d:%d:%d", tday, tmonth, tyear, thour, tmin, tsec);
     
     //fill the object
     statusReport["timestamp"]= SDtime;
     statusReport["device"] = deviceID;
-    statusReport["latitude"]= ytest;
-    statusReport["longitude"] = xtest;
-    statusReport["geoFenceEntery"] = 1;
-    statusReport["geoFenceleft"] = 1;
+    statusReport["latitude"]= latTest;
+    statusReport["longitude"] = longTest;
+    statusReport["geoFenceNum"] = geoFenceNum;
+    statusReport["geoFenceEnteryDeparture"] = value;
     statusReport["container"] = liquidTemp;
     statusReport["heater"] = 34.5;
-    statusReport["batteryVoltage"] = 4.98;
+    statusReport["batteryVoltage"] = 3.67;
     statusReport["network"] = "Tele2";
     statusReport["signalStrength"] = -89;
     
     //serialize it into a JSON string
     s = statusReport.serialize();
-    //serial.printf("status: %s\r\n",s );
     
   return s;
 }
@@ -245,9 +260,10 @@
 ////////////////////////////////////////////////////////////////////////////////////////////////////////
 double jsonParseSystemToDevice(const char * parameter, int msg_index)
 {
+// Journey message received from system parsed into values. Message description:
+//"{\"config\":[device,temperatureRequired,temperatureInterval,numberOfGeos],\"route1\":[geoFenceNum,heating,temperatureRequired,pingOnArrival,pingOnDeparture,shape,outerCircle,latCentre,longCentre,latEdge,LongEdge,latEdge2,longEdge2],.........,\"routeX\":[geoFenceNum,heating,temperatureRequired,pingOnArrival,pingOnDeparture,shape,numOfVertices,lat1,long1,lat2,long2,..............,lat1,long1]}
+
 MbedJSONValue journey;
-const  char * system_message = "{\"config\":[5.0,1.0,1.0,240.0],\"route1\":[1.0,0.0,1.0,1.0,1.0,1.0,54.5983852,-1.5708491,54.5969549,-1.5663735],\"route2\":[2.0,0.0,1.0,1.0,1.0,1.0,54.6542957,-1.4459836,54.6495902,-1.4430425],\"route3\":[3.0,0.0,1.0,1.0,1.0,1.0,54.7051416,-1.5638412,54.7101814,-1.5615844],\"route4\":[4.0,0.0,1.0,1.0,1.0,1.0,54.6298560,-1.3059736,54.6267899,-1.3075833],\"route5\":[5.0,0.0,1.0,1.0,1.0,2.0,5.0,54.6710093,-1.4587418,54.6730758,-1.4461951,54.6672642,-1.4436423,54.6678548,-1.4562232,54.6710093,-1.4587418]}";
-
 parse(journey, system_message);
 double msg; msg = journey[parameter][msg_index].get<double>(); return msg;
 }
@@ -261,53 +277,48 @@
     wait(0.001);
     DigitalOut SD_EN(PB_12);            //SD SPI enable (active low)
     DigitalOut Epd_EN(PA_8);            //Epd SPI enable (active low)
-    
-    Epd_EN = 1;                         //Disable Epd SPI to only enable uSD
-    new_file("/sd/coordinate.txt");     //create new "empty" juste wrote "New file"
-    Epd_EN = 0;                         //Enable Epd
+
+    //ToDo: To be replaced by the value received when subscribed to the Iot hub
+    //Subscribe and save the message in system_message
+    system_message = "{\"config\":[1.0,1.0,240.0,5.0],\"route1\":[1.0,0.0,1.0,1.0,1.0,1.0,54.5983852,-1.5708491,54.5969549,-1.5663735],\"route2\":[2.0,0.0,1.0,1.0,1.0,1.0,54.6542957,-1.4459836,54.6495902,-1.4430425],\"route3\":[3.0,0.0,1.0,1.0,1.0,1.0,54.7051416,-1.5638412,54.7101814,-1.5615844],\"route4\":[4.0,0.0,1.0,1.0,1.0,1.0,54.6298560,-1.3059736,54.6267899,-1.3075833],\"route5\":[5.0,0.0,1.0,1.0,1.0,2.0,5.0,54.6710093,-1.4587418,54.6730758,-1.4461951,54.6672642,-1.4436423,54.6678548,-1.4562232,54.6710093,-1.4587418]}";
+
     
     //Variables
-    int deviceID = 1;
-    double xtest,ytest;
-    int tyear,tmonth,tday,thour,tmin,tsec; 
-    
-    
-    
-    float liquidTemp = 0;
-    char chr_s[600];
-    std::string s;
-    wait(2);
-    
 
-   while(1) {
-        //wait (1);
-      
+    wait(1);
+    serial.printf("Silent Hub v1.0  ........................\r\n"); 
+    serial.printf("SystemCoreClock is %d Hz...........\r\n", SystemCoreClock); 
+    wait (1);
+   
+   while(1) {     
+          
         if(tgps.encode(GPSSerial.getc()))
         {
-            xtest = tgps.location.lat(); ytest = tgps.location.lng();                           //Location  
+            latTest = tgps.location.lat(); longTest = tgps.location.lng();                      //Location  
             tyear = tgps.date.year(); tmonth = tgps.date.month(); tday = tgps.date.day();       //Date
             thour = tgps.time.hour(); tmin = tgps.time.minute(); tsec = tgps.time.second();     //Time
        
             //this part is just for local terminal monitoring 
-            serial.printf("\r\nLocation: %3.6f, %3.6f, Date: %d-%d-%d, Time: %d:%d:%d \r\n", xtest, ytest, tday, tmonth, tyear, thour, tmin, tsec);
+            serial.printf("\r\nLocation: %3.6f, %3.6f, Date: %d-%d-%d, Time: %d:%d:%d \r\n", latTest, longTest, tday, tmonth, tyear, thour, tmin, tsec);
 
+            
+            liquidTemp = getTemp();
+            Display(liquidTemp, geotest);
             wait(5); //little delay to prevent double writing
-            liquidTemp = getTemp();
-            
+           
             //geofence testing
-            const char * parameter;
-            int msg_index;
-            double geofencesNum;
             parameter = "config";
-            msg_index = 0;
+            msg_index = 3;
             geofencesNum = jsonParseSystemToDevice(parameter,msg_index);
             serial.printf("\r\nNumber of geofences: %2.0f", geofencesNum);
             
-            int geotest = 0;
+            geotest = 0;
             int count=1; 
             int count2;
             double geo_lat_c; double geo_long_c; double geo_lat_e; double geo_long_e;
-            while ((count <= geofencesNum)&&(geotest == 0))
+            while ((count <= geofencesNum)&&(geotest == 0)) 
+            //Can also check latTest,longTest: to make sure we have a fix
+            //while ((count <= geofencesNum)&&(geotest == 0)&& ((latTest != 0)||(longTest != 0)))     
             {
                 char geo_extract[6];
                 sprintf(geo_extract,"route%d",count);
@@ -317,16 +328,11 @@
                 if (jsonParseSystemToDevice(geo_extract,msg_index) == 1)    //circular geofence
                 {
                     msg_index = 6;  geo_lat_c = jsonParseSystemToDevice(parameter,msg_index);
-                            serial.printf("\r\n%4.8f", geo_lat_c); 
                     msg_index = 7;  geo_long_c = jsonParseSystemToDevice(parameter,msg_index);
-                            serial.printf("\r\n%4.8f", geo_long_c);
                     msg_index = 8;  geo_lat_e = jsonParseSystemToDevice(parameter,msg_index);
-                            serial.printf("\r\n%4.8f", geo_lat_e);
                     msg_index = 9;  geo_long_e = jsonParseSystemToDevice(parameter,msg_index);
-                            serial.printf("\r\n%4.8f", geo_long_e);
                 
-                    geotest = inCircle(geo_lat_c, geo_long_c, geo_lat_e, geo_long_e, xtest, ytest);
-                    Display(liquidTemp, geotest);
+                    geotest = inCircle(geo_lat_c, geo_long_c, geo_lat_e, geo_long_e, latTest, longTest);
                     serial.printf("\r\nGeofence number = %d: \r\nIn geofence = %d:\r\n", count, geotest);
                 }
                 
@@ -342,42 +348,44 @@
                             geo_lat[count2] = jsonParseSystemToDevice(geo_extract,msg_index);
                             geo_long[count2] = jsonParseSystemToDevice(geo_extract,msg_index+1);
                             msg_index = msg_index + 2;   
-                            serial.printf("\r\ncount2: %d",count2);
-                            serial.printf("\r\n vertices lat: %4.8f  vertices long: %4.8f\r\n",geo_lat[count2],geo_long[count2]);
                         }
                     
-                    
-                    wait (1);
-                    
-                    geotest = pnpoly(vertices, geo_long, geo_lat, ytest, xtest);
-                    Display(liquidTemp, geotest);
+                    geotest = pnpoly(vertices, geo_long, geo_lat,longTest, latTest);
                     serial.printf("\r\nGeofence number = %d: \r\nIn geofence = %d:\r\n", count, geotest);
                 }    
                 count++;
             }
-            
-            //msg to be saved on SD and published
-            s = jsonSerializeDeviceToSystem(deviceID, xtest, ytest, liquidTemp, tday, tmonth, tyear, thour, tmin, tsec);
-            sprintf(chr_s,s.c_str());
+            if (geotest == 1)       //ToDo &&make sure the last publish handshake was successful 
+                {
+                //msg to be saved on SD and published, will overwrite last saved message
+                s = jsonSerializeDeviceToSystem(deviceID, longTest, latTest, count, geotest, liquidTemp, tday, tmonth, tyear, thour, tmin, tsec);
+                sprintf(chr_s,s.c_str());
+                Epd_EN = 1;
+                new_file("/sd/DeviceToSystemLog.txt");
+                add_data("/sd/DeviceToSystemLog.txt",chr_s);
+                read_file("/sd/DeviceToSystemLog.txt");
                 
-            
-            /*
-            Epd_EN = 1;
-            read_file("/sd/coordinate.txt");
-            add_data("/sd/coordinate.txt",chr_s);
-            Epd_EN = 0;
-            */
-       
+                //Save last geofence, will overwrite last saved value 
+                char cValGeoNum[8];
+                sprintf(cValGeoNum,"%d", count);
+                new_file("/sd/LastGeofence.txt");
+                add_data("/sd/LastGeofence.txt",cValGeoNum);
+                read_file("/sd/LastGeofence.txt"); 
+                Epd_EN = 0;
+                
+                //If it is a heating station log temperature 
+                
+                
+                }
+          
         }
 
         if (millis() > 5000 && tgps.charsProcessed() < 10)
         {
             serial.printf("No GPS detected: check wiring.\r\n");
-//            while(true);
             break;
         }
    
-        
     }
   }