Webserver controller with url trimming for value controls

Dependencies:   LCD_DISCO_F746NG BSP_DISCO_F746NG

Revision:
10:f941e0750773
Parent:
9:161bed13b17e
--- a/main.cpp	Mon Jul 01 17:23:49 2019 +0000
+++ b/main.cpp	Mon Aug 26 10:15:34 2019 +0000
@@ -1,13 +1,17 @@
 #include "mbed.h"
 #include "EthernetInterface.h"
 #include "TCPSocket.h"
+#include "LCD_DISCO_F746NG.h"
 #include <stdio.h>
-#include <string>
+#include <vector>
+#include <sstream>
+#include <iostream>       // std::cout
+#include <string>         // std::string
 
 using namespace std;
 
-#define IP      "192.168.1.181"
-#define GATEWAY "192.168.1.1"
+#define IP      "192.168.137.200"
+#define GATEWAY "192.168.137.1"
 #define NETMASK "255.255.255.0"
 #define PORT    80
 
@@ -16,12 +20,24 @@
 TCPSocket           server;
 TCPSocket*          clientSocket;
 SocketAddress       clientAddress;
+LCD_DISCO_F746NG    displayLCD;
+
+Thread              tempUpdater;            // Multithreaded temp updater
+Thread              urlManager;             // Thread for url management
+
 char                receiveBuf[1024];
-const int           OFF = 0;
-const int           ON = 1;
+const int           OFF = 0;                // Switch off
+const int           ON = 1;                 // Switch on
 DigitalOut          sw(LED1);               // A digital output to be switched on/off
-float               roomTemp = 21.8;        // A temperature sensor output
-const string        PASSWORD = "secret";    // Change as you like
+PwmOut              PwrLED(D3);             // Simulation of motor control
+AnalogIn            tempSensor(A0);         // Temperature sensor
+float               roomTemp = 0.0;         // A temperature sensor output
+float               units;                  // Final variable to contain temp value
+unsigned int        a, beta = 3975;         // Unsigned int's to use for temperature calculations
+float               resistance;             // LE PIECE OF RESISTAAAANCE
+float               temperature;            // Temperature variable to use for calculations
+int                 sliderVal               // Value of the slider
+const string        PASSWORD = "daddyshark";    // Change as you like
 const string        HTTP_OK = "HTTP/1.0 200 OK";
 const string        MOVED_PERM = "HTTP/1.0 301 Moved Permanently\r\nLocation: ";
 const string        UNAUTHORIZED = "HTTP/1.0 401 Unauthorized";
@@ -66,10 +82,8 @@
 
     if (cmd == "?sw=1")
         return(1);
-
     return(-3);
 }
-
 /**
  * @brief
  * @note
@@ -108,6 +122,7 @@
         "<meta name=\"viewport\" content=\" initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;\"/>"
         "<title>Smart Home</title>"
         "<link href='http://fonts.googleapis.com/css?family=Droid+Sans&v1' rel='stylesheet' type='text/css'>"
+        "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>"
         "<style>"
         ".switch {"
             "position: relative;"
@@ -152,11 +167,24 @@
             "transform: translateX(26px);"
         "}"
         "</style>"
+        "<script>"
+        "$(document).ready(function(){"
+                "setInterval(function() {"
+                    "$(\"#readTemp\").load(\" #readTemp\");"
+                "}, 10000);"
+            "$(\"#click\").click(function(){"
+                    "$(\"#readTemp\").load(\" #readTemp\");"
+            "});"
+        "});"
+        "</script>"
         "</head>"
-
         "<body>"
         "<h2><a href=\".\" title=\"Click to refresh the page\">Smart Home</a></h2>"
+        "<button id=\"click\">Click on this.</button>"
+        "<div id=\"readTemp\">"
         "<pre>Temperature:\t" + string(roomTempStr) + "&deg;C</pre>"
+        "<pre>Temperature:\t" + string(roomTempStr) + "&deg;C</pre>"
+        "</div>"
         "<pre>Heating:\t";
 
     if(status == ON) {
@@ -172,10 +200,6 @@
 
     httpContent +=
         "<div class=\"slider\"></div>"
-        "</a>"
-        "</pre>"
-        "<hr>"
-        "<pre>2017 ARMmbed</pre>"
         "</body>";
 
     return httpContent;
@@ -208,6 +232,71 @@
     /*$on*/
 }
 
+void clearLineLCD(int line) {
+    displayLCD.DisplayStringAt(0, LINE(line),(uint8_t *)("                                           "), CENTER_MODE);
+}
+
+int findURL(string mainString,string stringToFind) {
+    int foundAt;
+    int number;
+    
+    //printf("String to search in: %s\r\n", mainString);
+    //printf("String to search for: %s\r\n", stringToFind);
+    
+    std::size_t found = mainString.find(stringToFind); 
+    if (found != string::npos) {
+        foundAt = found;
+        //printf("Found at %i\r\n", foundAt);
+        string getString = mainString.substr(foundAt, 7);
+        string trimString = getString.substr(stringToFind.length(), 3);
+        std::istringstream iss (trimString);
+        iss >> number;
+        
+        //printf("%s found: %s\r\n", stringToFind, getString);
+        
+        //printf("Converting: %s\r\n", trimString);
+        
+        //printf("Final Number = %i\r\n", number);
+    }
+    else {
+        number = -1;    
+    }
+    return number;
+}
+
+void tempReader() {
+    while (true) {
+        a = tempSensor.read_u16(); /* Read analog value */
+    
+        // Calculate the resistance of the thermistor from analog voltage read.
+        resistance= (float) 10000.0 * ((65536.0 / a) - 1.0);
+            
+        // Convert the resistance to temperature using Steinhart's Hart equation
+        temperature=(1/((log(resistance/10000.0)/beta) + (1.0/298.15)))-273.15;
+            
+        units = (float) temperature;
+                    
+        roomTemp = units;
+        
+        if (sw == ON) {
+            if (roomTemp >= 30) {
+                PwrLED = 0.80;
+            }
+            else {
+                PwrLED = 0.20;
+            }
+        }
+        if (sw == OFF) {
+            PwrLED = 0;   
+        }
+        char    tempStr[20];
+        sprintf(tempStr, "Temperature is: %3.1f C", roomTemp);
+
+        displayLCD.DisplayStringAt(0, LINE(6),(uint8_t *)(tempStr), CENTER_MODE);
+        Thread::wait(1000);
+    }
+}
+
 /**
  * @brief
  * @note
@@ -216,6 +305,10 @@
  */
 int main(void)
 {
+    displayLCD.Clear(LCD_COLOR_BLACK);
+    displayLCD.SetBackColor(LCD_COLOR_BLACK);
+    displayLCD.SetTextColor(LCD_COLOR_WHITE);
+    
     pc.printf("Starting.. \r\n\r\n");
 
     net = new EthernetInterface();
@@ -225,7 +318,7 @@
         return 0;
     }
 
-    //net->set_network (IP, NETMASK, GATEWAY);  // include this for using static IP address
+    net->set_network (IP, NETMASK, GATEWAY);  // include this for using static IP address
     nsapi_size_or_error_t   r = net->connect();
 
     if (r != 0) {
@@ -238,10 +331,14 @@
     const char*     netmask = net->get_netmask();
     const char*     gateway = net->get_gateway();
     
+    displayLCD.DisplayStringAt(0, LINE(2),(uint8_t *)("IP Address"), CENTER_MODE);
+    displayLCD.DisplayStringAt(0, LINE(4),(uint8_t *)( ip ? ip : "None"), CENTER_MODE);
     pc.printf("IP address: %s\r\n", ip ? ip : "None");
     pc.printf("Netmask: %s\r\n", netmask ? netmask : "None");
     pc.printf("Gateway: %s\r\n\r\n", gateway ? gateway : "None");
     pc.printf("Usage: Type %s/%s/ into your web browser and hit ENTER\r\n\r\n", ip, PASSWORD.c_str());
+    
+    tempUpdater.start(tempReader); // Starting the multithreaded workload so it won't affect main program
 
     /* Open the server on ethernet stack */
     server.open(net);
@@ -290,6 +387,15 @@
 
         int cmd = analyseURL(received);
 
+        int testFind = findURL(received, "val=");
+        
+        if (testFind == -1) {
+            printf("--------------Couldn't find 'val='\r\n");
+        }
+        if (testFind >= 0) {
+            printf("--------------Found 'val=': %i\r\n", testFind);   
+        }
+
         switch (cmd) {
             case -3:
                 // update webpage
@@ -311,17 +417,21 @@
 
             case 0:
                 sw = OFF;   // turn the switch off
+                PwrLED = 0; // turn the "motor" led off
+                clearLineLCD(8);
+                displayLCD.DisplayStringAt(0, LINE(8),(uint8_t *)("Heating OFF"), CENTER_MODE);
                 httpHeader = HTTP_OK;
                 sendHTTP(*clientSocket, httpHeader, showWebPage(sw));
                 break;
 
             case 1:
                 sw = ON;    // turn the switch on
+                clearLineLCD(8);
+                displayLCD.DisplayStringAt(0, LINE(8),(uint8_t *)("Heating ON"), CENTER_MODE);
                 httpHeader = HTTP_OK;
                 sendHTTP(*clientSocket, httpHeader, showWebPage(sw));
                 break;
         }
-
         clientSocket->close();
     }
 }