我有一个向共享主机数据库发送HTTP GET
请求的 NodeMCU (ESP8266) 板。为了避免路由器上的端口转发,我想出了一个解决方案,我的 NodeMCU 板会定期(每 5 秒)HTTP GET
向数据库发送一个请求,以查看用户是否更改了设备状态。
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
}
用户通过网站更改设备状态(单击按钮),然后将设备状态保存在数据库中。当设备向HTTP GET
服务器发送请求时,getStatus.php
文件会查询数据库以获取当前设备状态并将响应发送回设备。
<?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"];
}
}
}
?>
我试图找到一个解决方案,我不必每 5 秒查询一次数据库,而是仅在用户更改设备状态时查询。
所以我的问题是如何将HTTP GET
响应推迟到用户通过单击按钮更改设备状态的那一刻?