PHP代码检查人在传感器状态
1、安装homeassistant后并安装HCS,添加米家账号并登陆
2、在homeassistant的概览页找到传感器,并点击该传感器

3、点击右上角的齿轮按钮

4、记录实体标识符

5、homeassistant里获取长期令牌
6、宝塔新建一个站点,检查状态代码如下:
<?php
function getState($entityId, $token) {
// 构造请求的 URL
$url = "{HA的站点}:8123/api/states/".$entityId;
// 初始化 cURL 会话
$ch = curl_init();
// 设置请求的 URL
curl_setopt($ch, CURLOPT_URL, $url);
// 设置请求头,包括授权令牌和内容类型
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $token",
"Content-Type: application/json"
]);
// 设置返回结果为字符串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行请求
$response = curl_exec($ch);
// 获取 HTTP 状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 检查是否有错误
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
return null;
}
// 关闭 cURL 会话
curl_close($ch);
// 根据 HTTP 状态码处理响应
if ($httpCode == 200) {
// 解析 JSON 响应
$result = json_decode($response, true);
// 提取 state 和 last_changed 参数
$state = $result['state'] ?? null;
$lastChanged = $result['last_changed'] ?? null;
return [
'state' => $state,
'last_changed' => $lastChanged
];
} elseif ($httpCode == 404) {
echo "Error: Entity not found.";
return null;
} else {
echo "Error: HTTP Status Code $httpCode.";
return null;
}
}
// 示例调用
$entityId = "{填写实体标识符}";
$token = "{长期令牌}"; // 替换为你的授权令牌
$result = getState($entityId, $token);
if ($result) {
echo "State:{" . $result['state'] . "}\n";
}
?>7、VB中的调用检测代码:
Dim N_Zt As Long
Public Function getHtmlStr(strUrl As String) As String ' 获取远程网页源码
On Error Resume Next
Dim XmlHttp As Object, stime, ntime
Set XmlHttp = CreateObject("Microsoft.XMLHTTP")
' 添加时间戳参数以避免缓存
Dim timestamp As String
timestamp = "?timestamp=" & Now
If InStr(strUrl, "?") > 0 Then
timestamp = "×tamp=" & Now
End If
' 设置请求头,强制不使用缓存
XmlHttp.open "GET", strUrl & timestamp, True
XmlHttp.setRequestHeader "Cache-Control", "no-cache"
XmlHttp.setRequestHeader "Pragma", "no-cache"
XmlHttp.send
stime = Now ' 获取当前时间
While XmlHttp.ReadyState <> 4
DoEvents
ntime = Now ' 获取循环时间
If DateDiff("s", stime, ntime) > 3 Then
getHtmlStr = ""
Exit Function
End If
Wend
getHtmlStr = StrConv(XmlHttp.responseBody, vbUnicode)
Set XmlHttp = Nothing
End Function
Private Sub Timer1_Timer()
Text1.Text = getHtmlStr("{新项目的链接}/check.php")
List1.AddItem Format(Now, "YYYY/MM/DD HH:MM:SS") & " " & Text1.Text, 0
If InStr(Text1.Text, "{no one}") > 0 Then
N_Zt = N_Zt + 1
If N_Zt >= 2 Then
N_Zt = 0
Timer1.Enabled = False
Form1.Visible = True
End If
Else
N_Zt = 0
End If
End Sub

