设备实时电量监听
530字约2分钟
2025-7-16
当网页/小程序/app 端需要对设备进行控制或者获取设备信息时,需要先和服务进行 WS
连接,然后就可以对设备进行操作。
案例代码
import { useEffect, useRef, useState } from "react";
function App() {
/**
* 连接 ws 服务的一系列逻辑
*/
const wsIns = useRef();
const lockReconnect = useRef();
const tt = useRef();
const heartbeatTimer = useRef();
function sendHeartbeat() {
wsIns.current.send("ping")
heartbeatTimer.current = setTimeout(sendHeartbeat, 20 * 1000);
}
function reconnect() {
if (lockReconnect.current) return;
lockReconnect.current = true;
//没连接上会一直重连,设置延迟避免请求过多, 有定时任务 先取消再设置
tt.current && clearTimeout(tt.current);
tt.current = setTimeout(function () {
connectWsServer();
lockReconnect.current = false;
}, 5000);
}
// 收到 ws 服务的数据处理逻辑
function onWSMessage(args) {
// console.log('收到数据:', args)
const { type, device_id, data } = args;
switch (type) {
case "battery":
// 设备电量
console.log("battery:", data);
break;
case "device_is_online_res":
// 设备在线状态
console.log("device_is_online_res:", data);
break;
case "on_iat_end_cb":
// iat 识别完毕回调
console.log("on_iat_end_cb: ", data);
break;
case "on_llm_cb":
// llm 推理回调
console.log("on_llm_cb: ", data);
break;
case "ota_update_res":
// ota升级是否触发成功
console.log("ota_update_res: ", data);
break;
case "ota_progress":
// OTA 升级进度, 实际 50% 左右设备就会断网准备重启
console.log("ota_progress: ", data);
break;
case "ota_update_error":
// OTA 升级错误
console.log("ota_update_error: ", data);
break;
case "endpoint_data":
// 有被控终端数据接入或者变动时会触发
console.log('收到终端数据:', data)
break;
case "get_local_data_res":
// 由 get_local_data 消息触发
console.log('收到本地数据:', args)
break;
default:
break;
}
}
const connectWsServer = () => {
const api_key = "超体 api_key";
const ws = new WebSocket(`wss://api.espai2.fun/connect_espai_node/?device_type=client_page&api_key=${api_key}`);
wsIns.current = ws;
ws.onopen = function open() {
console.log('连接成功:', api_key);
// 开始发送心跳
sendHeartbeat();
};
ws.onclose = function close() {
console.log('断开连接:', api_key);
// 清除心跳计时器
clearTimeout(heartbeatTimer);
reconnect();
};
ws.onmessage = function incoming(evt) {
if (evt.data === "pong") {
return;
}
// console.log('收到数据:', evt)
onWSMessage(JSON.parse(evt.data));
};
}
// 进行ws连接
useEffect(() => {
if (api_key) {
if (wsIns.current) {
wsIns.current?.close();
}
connectWsServer();
}
return () => {
wsIns.current?.close();
}
}, [api_key])
// 设置设备音量案例
// 实际业务中在需要的地方调用即可
function setDeviceVolume() {
wsIns.current?.send(JSON.stringify({
type: 'set_volume',
data: 0.5, // 音量范围0-1
}))
}
// 获取设备存储的数据, 发送后会收到 get_local_data_res 消息
// 实际业务中在需要的地方调用即可
function setDeviceVolume() {
wsIns.current?.send(JSON.stringify({
type: 'get_local_data'
}))
}
return <>
ESP-AI 服务端 WebScoket 示例
</>
}