a sensor hub for monitoring home environment

Dependencies:   HTS221 LIS3MDL LPS22HB LSM303AGR LSM6DSL VL53L0X picojson

Fork of HelloWorld_ST_Sensors by ST

Revision:
14:0c8967e20f93
Parent:
13:f8e84b12665c
--- a/main.cpp	Tue Dec 19 19:31:23 2017 +0000
+++ b/main.cpp	Mon Jan 29 14:41:02 2018 +0000
@@ -11,6 +11,7 @@
   - add light sensor to monitor illuminance --> low priority
   - improve reading by either: reduce power on time of WiFi module (batch logging)
     or by compensating for board own temperature --> WiP
+  - use a local toolchain to compile mbed projects (with trueStudio) --> WiP 
   - add option to choose location from a list and update location tag
   - incrementally convert the project to electric energy monitoring:
         - read 2x simultaneous adc channels using DMA
@@ -27,8 +28,6 @@
     printf("***      Home Env on STM32 IoT Discovery                    ***\n");
     printf("***************************************************************\n");
 
-    RESET_NEXTION;
-
     printf("> Initializing sensors and WiFi... \n");
     
     int range_status;
@@ -40,11 +39,11 @@
     acc_gyro.init(NULL);
     range_status = range.init_sensor(VL53L0X_DEFAULT_ADDRESS);
 
-    /* Enable all sensors */
+    /* enable sensors */
     hum_temp.enable();
     press_temp.enable();
-    acc_gyro.enable_x();
-    acc_gyro.enable_g();
+    // acc_gyro.enable_x();
+    // acc_gyro.enable_g();
     
     uint8_t id;
     hum_temp.read_id(&id);
@@ -60,6 +59,7 @@
     sense_enabled = true;
 
     /* Setup display */
+    WAKE_UP_DISPLAY;
     WIFI_ICON_OFF;
     UPLOAD_ICON_OFF;
     NO_WAKEUP_ON_SERIALIN;// no wakeup on serial in
@@ -73,6 +73,12 @@
         led3 = 1;
         //WiFi_led_ticker.attach(&toggle_led3_cb, 0.25);
         rtc_synced = sync_rtc();
+        // enter power save mode
+        /*if (WIFI_SetPowerSaveMode(1, (UPLOAD_PERIOD_S - 1)*1000) == WIFI_STATUS_OK) {
+            printf("> es-wifi entered power save mode\n");
+        } else {
+            printf("> ERROR: es-wifi did not enter power save mode\n");
+        }*/
     }
 
     // start event tickers
@@ -111,12 +117,12 @@
         */
 
         // print results to terminal
-        
+        /*
         printf("HTS221:  temp= %.2f C, hum= %.2f%%\r\n", tempC_val, RH_val);
         printf("         temp= %.2f F\n", tempF_val);
         printf("LPS22HB: patm= %.2f mbar, temp= %.2f C\r\n", Patm_val, tempC_val2);
         printf("VL53L0X [mm] = %6ld\r\n", distance_val);
-
+        */
         // refresh screen with updated measurements
         nextion.printf("valC.txt=\"%.1f\"\xff\xff\xff", tempC_val);
         nextion.printf("valF.txt=\"%.1f\"\xff\xff\xff", tempF_val);
@@ -125,18 +131,19 @@
         nextion.printf("valRange.val=%d\xff\xff\xff", distance_val);
 
         take_measurements = false;
-    }// take measurements
+    }
 
     if (send_measurements) {
 
-        //printf("HTS221:  temp= %.2f C, hum= %.2f%%\r\n", tempC_val, RH_val);
+        printf("HTS221:  temp= %.2f C, hum= %.2f%%\r\n", tempC_val, RH_val);
 
         // body of the request
         char request_body[256];
+        char *InfluxServerUrl = INFLUX_SERVER_URL;
         sprintf(request_body, "disco_iot,loc=%s temperature=%.2f,humidity=%.1f,pressure=%.1f \n","playroom", tempC_val, RH_val, Patm_val);
 
         // build header of the request
-        sprintf((char *)http_request, "POST %s HTTP/1.1\r\nHost: %s \r\n", influx_query, InfluxServerUrl);
+        sprintf((char *)http_request, "POST %s HTTP/1.1\r\nHost: %s \r\n", INFLUX_WRITE_EP, InfluxServerUrl);
         strcat((char *)http_request, "Accept: */*\r\n");
         strcat((char *)http_request, "User-agent: ES-WIFI TcpClient\r\n");
         strcat((char *)http_request, "Connection: Close\r\n"); //"Connection: Keep-Alive\r\n"
@@ -152,11 +159,11 @@
         uint8_t socketid = 1;
         if (checkWiFi()) {
             led3 = 1;
-            if (connectToServer(InfluxServerUrl, InfluxServerPort, socketid)) {
+            if (connectToServer(INFLUX_SERVER_URL, INFLUX_SERVER_PORT, socketid)) {
                 ledhttp =1;
                 // submit POST request
-                printf("> Sending a POST request with length=%d including a body length=%d\n", reqLen, strlen(request_body));
-                printf((char *)http_request);
+                // printf("> Sending a POST request with length=%d including a body length=%d\n", reqLen, strlen(request_body));
+                // printf((char *)http_request);
                 uint16_t dataLen;
                 if (WIFI_SendData(socketid, http_request, reqLen, &dataLen, WIFI_WRITE_TIMEOUT) != WIFI_STATUS_OK) {
                     printf("> ERROR: Could not send request to %s", InfluxServerUrl);
@@ -180,8 +187,8 @@
                     // extract the response code
                     int response_code = 0;
                     sscanf(buffer, "HTTP/1.1 %d", &response_code);
-                    printf("> Response code: %d \n", response_code);
-                    /* c ommon response codes from InfluxDB API:
+                    // printf("> Response code: %d \n", response_code);
+                    /* common response codes from InfluxDB API:
                     HTTP/1.1 204 No Content
                     HTTP/1.1 400 Bad Request
                     HTTP/1.1 404 Not Found
@@ -196,8 +203,16 @@
                 ledhttp = 0;
                 WIFI_CloseClientConnection(socketid);
             } else {
-                printf("> ERROR: Could not connect to %s \n", InfluxServerUrl);
+                printf("> ERROR: Could not open connection to %s \n", InfluxServerUrl);
             }
+            
+            // enter power save mode for UPLOAD_PERIOD_S - 1 sec, beacon interval = 100ms
+            if (WIFI_SetPowerSaveMode(1, (UPLOAD_PERIOD_S - 1)*1000) == WIFI_STATUS_OK) {
+               printf("> es-wifi entered power save mode\n");
+            } else {
+                printf("> ERROR: es-wifi did not enter power save mode\n");
+            }
+            
         } else {
             printf("> ERROR: Could not connect to WiFi \n");
             led3 = 0;
@@ -206,14 +221,14 @@
         if (rtc_synced) {
             time(&rawtime);
             pTime = localtime(&rawtime);
-            printf ("Current local time and date: %s", asctime(pTime));
-            //printf("> %d:%d:%d\n", pTime->tm_hour, pTime->tm_min, pTime->tm_sec);
+            // printf ("Current local time and date: %s", asctime(pTime));
+            // printf("> %d:%d:%d\n", pTime->tm_hour, pTime->tm_min, pTime->tm_sec);
         } else {
-            sync_rtc();
+            rtc_synced = sync_rtc();
         }   
         
         send_measurements = false;
-    } // sendMeasurement()
+    }
 
     if (check_proximity) {
         // make sure display is awake when somebody get close to the screen
@@ -234,13 +249,14 @@
         if (rtc_synced) {
             time(&rawtime);
             pTime = localtime(&rawtime);
-            nextion.printf("hour.txt=\"%d\"\xff\xff\xff", pTime->tm_hour);
-            nextion.printf("minute.txt=\"%d\"\xff\xff\xff", pTime->tm_min);
+            nextion.printf("hour.txt=\"%02d\"\xff\xff\xff", pTime->tm_hour);
+            nextion.printf("minute.txt=\"%02d\"\xff\xff\xff", pTime->tm_min);
+            nextion.printf("vis sec,1\xff\xff\xff");
             //nextion.printf("vis sec,%d\xff\xff\xff", pTime->tm_sec % 2 == 0 ? 1 : 0);
         }
         
         check_proximity = false;
-    } // check proximity        
+    }       
 } // Loop
 
 
@@ -296,11 +312,12 @@
     uint8_t  MAC_Addr[6];
 
     if(WIFI_Init() ==  WIFI_STATUS_OK) {
-        /* printf("> WiFi module initialized.\n");
+        // printf("> WiFi module initialized.\n");
         char fwVer[32];
         if(WIFI_GetModuleFwRevision(fwVer) == WIFI_STATUS_OK) {
           printf("> Firmware version: %s\n", fwVer);
         }
+        /*
         if(WIFI_GetMAC_Address(MAC_Addr) == WIFI_STATUS_OK) {
             printf("> WiFi module MAC Address : %X:%X:%X:%X:%X:%X\n",
                    MAC_Addr[0],
@@ -311,13 +328,8 @@
                    MAC_Addr[5]);
         } else {
             printf("> ERROR : CANNOT get MAC address\n");
-        }
-        */
-        if (WIFI_SetPowerSaveMode(1, 1000) == WIFI_STATUS_OK) {
-            printf("> es-wifi entered power save mode\n");
-        } else {
-            printf("> ERROR: es-wifi did not enter power save mode\n");
-        }
+        }*/
+        
         if( WIFI_Connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, WIFI_ECN_WPA2_PSK) == WIFI_STATUS_OK) {
             if(WIFI_GetIP_Address(IP_Addr) == WIFI_STATUS_OK) {
                 printf("> IP Address : %d.%d.%d.%d\n",
@@ -326,6 +338,7 @@
                        IP_Addr[2],
                        IP_Addr[3]);
                 WIFI_ICON_ON;
+                UPLOAD_ICON_OFF; // reset db sync status if (re-)connect happened
                 return true;
             } else {
                 printf("> ERROR : es-wifi module CANNOT get IP address\n");
@@ -337,6 +350,7 @@
         printf("> ERROR : WIFI Module cannot be initialized.\n");
     }
     WIFI_ICON_OFF;
+    UPLOAD_ICON_OFF;
     return false;
 }
 
@@ -350,8 +364,10 @@
 bool checkWiFi(void)
 {
     uint8_t  ip_addr[4];
-    if(WIFI_GetIP_Address(ip_addr) == WIFI_STATUS_OK) return true;
-    else {
+    if(WIFI_GetIP_Address(ip_addr) == WIFI_STATUS_OK) {
+        WIFI_ICON_ON;
+        return true;
+    } else {
         return connectWiFi();
     }
 }
@@ -370,12 +386,12 @@
     while (trials--) {
         // get the server IP through a (local) DNS resolve
         if (WIFI_GetHostAddress(serverUrl, serverIP) == WIFI_STATUS_OK) {
-            /*
+            
             printf("> %s resolved to: %d.%d.%d.%d\n", serverUrl,
                    serverIP[0],
                    serverIP[1],
                    serverIP[2],
-                   serverIP[3]);*/
+                   serverIP[3]);
             // establish TCP connection to server
             if( WIFI_OpenClientConnection(socket_id, WIFI_TCP_PROTOCOL, "TCP_Client", serverIP, serverPort, 0) == WIFI_STATUS_OK) {
                 printf("> Connected to %s .\n", serverUrl);
@@ -383,8 +399,10 @@
             }
         } else {
             printf("> ERROR : Cannot resolve URL: %s\n", serverUrl);
+            printf("> Trials left: %d\n", trials);
         }
     }
+    
     if(!trials) {
         printf("> ERROR : Cannot establish connection\n");
     }
@@ -402,7 +420,7 @@
     uint16_t dataLen;
     if (checkWiFi()) {
         if (connectToServer(TIME_SERVER_URL, TIME_SERVER_PORT, socketid)) {
-            sprintf((char *)http_request, "GET %s HTTP/1.1\r\nHost: %s \r\n", TIME_SERVER_QUERY, TIME_SERVER_URL);
+            sprintf((char *)http_request, "GET %s HTTP/1.1\r\nHost: %s \r\n", TIME_SERVER_EP, TIME_SERVER_URL);
             strcat((char *)http_request, "Connection: Close\r\n\r\n");
             reqLen = strlen((char *)http_request);
             if (WIFI_SendData(socketid, http_request, reqLen, &dataLen, WIFI_WRITE_TIMEOUT) != WIFI_STATUS_OK) {