【问题标题】:Receive sensor data, publish on webpage - http.POST(jsonData)接收传感器数据,在网页上发布 - http.POST(jsonData)
【发布时间】:2023-02-05 21:18:18
【问题描述】:

我是 php 页面编程的新手,所以我可能会问太多,希望你能忍受我。

我的情况:我有一个 Arduino Bee Hive 监控系统,可以发送实时数据、温度和重量。 在我的 LAN 上,我的 Synology NAS 上有一个运行 php 7.4 的网络服务器

我认为这段代码是基于 websocket,而不是 shure。

Arduino 设备的 IP 为 192.168.0.52 服务器 IP 192.168.0.5,http 端口 9978,未启用 https

在网络服务器上看不到任何值,如果收到我不知道。

Arduino 发送端的代码正在运行,并且还声明“数据发送成功”:

#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);
  }
}

Arduino output

服务器端: 我在网上找到的代码,做了一些修改

保存为 index.php

<html>
  <head>
    <script>
      function updateData() {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", "http://192.168.0.52:80");
        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>

Web page

上面的代码现在正在运行。

我没有尝试太多,但我在网络服务器代码中测试输入网络服务器 ip 192.168.0.5 而不是 192.168.0.52 没有帮助

【问题讨论】:

  • 嘿,你检查过其他社区吗?我还建议在这里发布您的问题:arduino.stackexchange.com
  • 我对上面的代码有点困惑。 Arduino 似乎向您的网络服务器(在 Synology 上)发送一个 POST 请求,而 Javascript AJAX 代码每 1 秒向 Arduino 发送一个 GET 请求?当然 AJAX 请求应该触发 Arduino 代码简单地print数据而不是发送 http 请求(因为 Javascript 不会处理 POST 请求)
  • 据推测,temperature_fhumidity_f 是 Arduino 上基于传感器读数的变量——在调用 Serial.println() 之前未声明这些变量

标签: php json http post


【解决方案1】:

我猜您正在尝试在您的网页上“实时”更新您的传感器数据,对吗?

如果是这样,我可能会建议实施以下模式:

从上面来看,您只缺少请求处理程序!

这种机制很简单;当 Arduino 发送请求时,它告诉请求处理程序将数据临时保存到数据处理程序中,并且每当 Web 应用程序提取数据时,请求处理程序都会使用 Arduino 先前提交的数据进行响应。

所以下面是实现这个的代码

请求处理程序.php(在您的根文件夹中创建)

<?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;
}

并将您的 arduino 代码稍微更改为:

#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);
  }
}

最后你的索引.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>

希望能帮助到你!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-15
    • 2020-11-11
    • 2017-07-25
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多