Home > Net >  Receive sensor data, publish on webpage - http.POST(jsonData)
Receive sensor data, publish on webpage - http.POST(jsonData)

Time:02-06

I'm new to programming a php page, so I may ask too much, hope you bear out with me.

My case: I have an Arduino Bee Hive monitoring system that sends live data, temperature and weight. On my LAN I have a web server on my Synology NAS running php 7.4

I think this code is based websocket,not shure.

Arduino device has IP 192.168.0.52 Server IP 192.168.0.5, http port 9978, https not enabled

On web server no values are seen, if received I dont know.

Code for Arduino sender side is running and also state that "Data sent successfully":

#include <HTTPClient.h>
#include <WiFi.h>
#include <Ethernet.h>

const char* host = "192.168.0.5"; //web server synology NAS
const int port = 9978;  // http port Synology

const char* ssid = "nettUser";
const char* password = "nettPass";
//web login
char username[] = "serverUser";
char userpassword[] = "serverPass";


void loop() {
  // Read sensor values and store in temperature and humidity
  // Read the temperature and weight values
  float temperature = 25.0;    // for php test purpose, fixed values
  float weight = 50.0;

  // Create a JSON object to store the data
  String jsonData = "{\"temperature\":"   String(temperature)   ",\"weight\":"   String(weight)   "}";

  // Create an instance of the HTTPClient class
  HTTPClient http;

  // Make a POST request to the server
  http.begin("http://"   String(host)   ":"   String(port));
  http.addHeader("Content-Type", "application/json");
  http.setAuthorization(username, userpassword);
  int httpCode = http.POST(jsonData);

  // Check the response code
  if (httpCode > 0) {
    Serial.println("Data sent successfully");
  } else {
    Serial.println("Error sending data");
  }

  // Close the connection
  http.end();
 
  Serial.print("[WiFi] IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println(temperature_f);
  Serial.println(humidity_f);

  delay(5000);
  }
}

enter image description here

From the above, you are only missing the request handler!

This mechanism is straightforward; when Arduino sends a request, it tells the request handler to save the data temporarily into the data handler and any time the web app pulls data, the request handler responds with the data previously submitted by Arduino.

So following is the code that implements this

request_handler.php (Created at your root folder)

<?php
$post_data = file_get_contents("php://input"); //as you send data as raw json

if ($post_data) { //when request comes from arduino, you will have post data
    $json_data = json_encode($post_data);
    if (file_put_contents("data.txt", $json_data)) {
        echo "Ok";
    } else {
        http_response_code(400); //when data did not save
        echo "Bad Request";
    }
} else { //when the web app make a call to the request handler
    $previous_data = file_get_contents("data.txt");
    echo $previous_data;
}

And slightly change your arduino code to :

#include <HTTPClient.h>
#include <WiFi.h>
#include <Ethernet.h>

const char* host = "192.168.0.5"; //web server synology NAS
const int port = 9978;  // http port Synology

const char* ssid = "nettUser";
const char* password = "nettPass";
//web login
char username[] = "serverUser";
char userpassword[] = "serverPass";


void loop() {
  // Read sensor values and store in temperature and humidity
  // Read the temperature and weight values
  float temperature = 25.0;    // for php test purpose, fixed values
  float weight = 50.0;

  // Create a JSON object to store the data
  String jsonData = "{\"temperature\":"   String(temperature)   ",\"weight\":"   String(weight)   "}";

  // Create an instance of the HTTPClient class
  HTTPClient http;

  // Make a POST request to the server
  http.begin("http://"   String(host)   ":"   String(port)   "/request_handler.php");
  http.addHeader("Content-Type", "application/json");
  http.setAuthorization(username, userpassword);
  int httpCode = http.POST(jsonData);

  // Check the response code
  if (httpCode > 0) {
    Serial.println("Data sent successfully");
  } else {
    Serial.println("Error sending data");
  }

  // Close the connection
  http.end();
 
  Serial.print("[WiFi] IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println(temperature_f);
  Serial.println(humidity_f);

  delay(5000);
  }
}

Finally your index.php

<html>
  <head>
    <script>
      function updateData() {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "http://192.168.0.52:80/request_handler.php");
        xhr.onreadystatechange = function() {
          if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
              const data = JSON.parse(xhr.responseText);
              document.getElementById("temperature").innerHTML = data.temperature;
              document.getElementById("weight").innerHTML = data.weight;
            } else {
              console.error(xhr.statusText);
            }
          }
        };
        xhr.send();
      }
      setInterval(updateData, 1000);
    </script>
  </head>
  <body>
    <h1>HiveMon - v 1</h3>
    <h3>Temperature: <span id="temperature"></span>&#8451;</h3>
    <h3>Weight: <span id="weight"></span>%</h3>
  </body>
</html>

Hope it helps!

CodePudding user response:

Thanks so much.

I have used your code, uploaded to my arduino and madethe 2 files on server.

I dont get thevariables on the web page, page is like this: enter image description here

Any Idea?

  • Related