Saturday, 4 May 2019

Postpone HTTP GET response until the user changes the value in the database

I have a NodeMCU (ESP8266) board that sends HTTP GET requests to a shared hosting database. To avoid port forwarding on my router the NodeMCU board sends periodically (for example every 5 seconds) a HTTP GET request to the database to see if the device status is changed by the user.

void loop() 
{
   HTTPClient http; //Declare object of class HTTPClient
   String getData, Link;

   //HTTP GET REQUEST

   getData = "?device="+ deviceName ;
   Link = "http://.../getStatus.php" + getData;

   http.begin(Link); 

   int httpCode = http.GET(); //Send the request

   String payload = http.getString(); //Get the response from database

   if(payload=="ON")
   {
      digitalWrite(LEDPin, HIGH);//change pin status
   }
   else if(payload=="OFF")
   {
      digitalWrite(LEDPin, LOW);//change pin status
   }

   http.end(); 

   delay(5000);//Send GET request every 5 seconds
}  

The user changes the device status over a website and the device status is then saved in the database. When the device sends the HTTP GET request the getStatus.php file queries the database for the current device status and sends the response back to the device.

<?php

    $db = mysqli_connect(...);

    if(!empty($_GET['device']))
    {
        $device_name = $_GET['device'];

        $query_status = "SELECT status FROM devices WHERE device = ?";

        $stmt = mysqli_prepare($db, $query_status);
        if ($stmt === false) {
            error_log(mysqli_error($db));
            die("Sorry, there has been a software error");
        }
        $ok = mysqli_stmt_bind_param($stmt, "s", $device_name);
        if ($ok === false) {
            error_log(mysqli_stmt_error($db));
            die("Sorry, there has been a software error");
        }
        $ok = mysqli_stmt_execute($stmt);
        if ($ok === false) {
            error_log(mysqli_stmt_error($db));
            die("Sorry, there has been a software error");
        }

        $result = $stmt->get_result();

        if ($result->num_rows > 0) 
        {
            while($row = $result->fetch_assoc()) 
            {
                echo $row["status"];
            }
        } 
    }
?>

I am trying to find a solution where I don't have to query the database every 5 second, but instead when the user changes the device status.

So my question is how to modify these two files so that the HTTP GET request postpones the response until the moment that the user changes the device status in the database. How long can such an request be active on the server and what happens to the request when the device losses the internet connection?



from Postpone HTTP GET response until the user changes the value in the database

No comments:

Post a Comment