【发布时间】: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);
}
}
服务器端: 我在网上找到的代码,做了一些修改
保存为 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>℃</h3>
<h3>Weight: <span id="weight"></span>%</h3>
</body>
</html>
上面的代码现在正在运行。
我没有尝试太多,但我在网络服务器代码中测试输入网络服务器 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_f和humidity_f是 Arduino 上基于传感器读数的变量——在调用Serial.println()之前未声明这些变量