控制逻辑加入后台保活 以防哪个浏览器且后台websocket断联

This commit is contained in:
mmc
2026-06-02 10:48:27 +08:00
parent b479664c3b
commit 368ae2d0c8
2 changed files with 69 additions and 108 deletions

View File

@@ -90,7 +90,6 @@ export default function RobotTaskPage() {
const [isTaskModalOpen, setIsTaskModalOpen] = useState(false); const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
const [selectedPathWork, setSelectedPathWork] = useState(null); const [selectedPathWork, setSelectedPathWork] = useState(null);
// 获取任务列表数据
// 获取任务列表数据 // 获取任务列表数据
const fetchTaskList = async () => { const fetchTaskList = async () => {
try { try {
@@ -151,7 +150,7 @@ export default function RobotTaskPage() {
const fetchRouteList = async () => { const fetchRouteList = async () => {
if (!stationId) return; if (!stationId) return;
getRobotRouteList({ siteId: stationId }).then(res => { getRobotRouteList({ siteId: stationId }).then(res => {
if (res.code === 200 && res.data) { if (res.code == 200 && res.data) {
setRouteList(res.data); setRouteList(res.data);
} else { } else {
setRouteList([]); setRouteList([]);
@@ -599,13 +598,13 @@ export default function RobotTaskPage() {
> >
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{routeList {routeList
.filter(item => { //.filter(item => {
if (!routeSearch) return true; // if (!routeSearch) return true;
const name = (item.workName || item.name || '').toLowerCase(); // const name = (item.workName || item.name || '').toLowerCase();
const id = String(item.id || '').toLowerCase(); // const id = String(item.id || '').toLowerCase();
const key = routeSearch.toLowerCase(); // const key = routeSearch.toLowerCase();
return name.includes(key) || id.includes(key); // return name.includes(key) || id.includes(key);
}) //})
.map(route => ( .map(route => (
<div <div
key={route.id} key={route.id}

View File

@@ -16,6 +16,7 @@ export default class DeviceController {
envConfig.WS_URL || 'wss://ri.satabot.com/ws/'; envConfig.WS_URL || 'wss://ri.satabot.com/ws/';
this.connectedDeviceSn = null; this.connectedDeviceSn = null;
this.currentDevice = null; // 保存当前设备
this.requestDeviceId = ''; this.requestDeviceId = '';
@@ -26,8 +27,8 @@ export default class DeviceController {
this.wsStatus = 'disconnected'; this.wsStatus = 'disconnected';
this.wsDeviceInfo = {}; this.wsDeviceInfo = {};
this.controlTimeout = null; this.controlTimeout = null;
this.keepAliveInterval = null; // 后台保活定时器
this.onDeviceInfoUpdate = null; this.onDeviceInfoUpdate = null;
this.onControlStatusChange = null; this.onControlStatusChange = null;
@@ -38,30 +39,62 @@ export default class DeviceController {
this.handleWsMessage = this.handleWsMessage.bind(this); this.handleWsMessage = this.handleWsMessage.bind(this);
this.handleWsStatus = this.handleWsStatus.bind(this); this.handleWsStatus = this.handleWsStatus.bind(this);
this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
this.sendGamepad = throttle( this.sendGamepad = throttle(
this.sendGamepad.bind(this), this.sendGamepad.bind(this),
50, 50,
{ { leading: true, trailing: true }
leading: true,
trailing: true,
},
); );
} }
init() { init() {
this.unSubMessage = wsManager.onMessage( this.unSubMessage = wsManager.onMessage(this.handleWsMessage);
this.handleWsMessage, this.unSubStatus = wsManager.onStatusChange(this.handleWsStatus);
);
this.unSubStatus = wsManager.onStatusChange( // ========== 【集成】页面可见性监听 ==========
this.handleWsStatus, document.addEventListener('visibilitychange', this.handleVisibilityChange);
);
// ========== 【集成】后台保活定时 ==========
this.startKeepAlive();
}
// ========== 【集成】页面切前台重连 ==========
handleVisibilityChange() {
if (document.visibilityState === 'visible' && this.currentDevice) {
console.log('✅ 页面切回前台,自动重连 WebSocket');
setTimeout(() => {
this.connectDevice(this.currentDevice);
}, 500);
}
}
// ========== 【集成】后台保活 ==========
startKeepAlive() {
this.keepAliveInterval = setInterval(() => {
if (
this.connectedDeviceSn &&
this.wsStatus !== 'connected' &&
this.currentDevice
) {
console.log('🔄 后台保活:尝试重连 WebSocket');
this.connectDevice(this.currentDevice);
}
}, 8000);
} }
destroy() { destroy() {
this.clearControlTimeout(); this.clearControlTimeout();
// 清理保活
if (this.keepAliveInterval) {
clearInterval(this.keepAliveInterval);
this.keepAliveInterval = null;
}
// 移除监听
document.removeEventListener('visibilitychange', this.handleVisibilityChange);
this.unSubMessage?.(); this.unSubMessage?.();
this.unSubStatus?.(); this.unSubStatus?.();
@@ -70,27 +103,25 @@ export default class DeviceController {
handleWsStatus(status) { handleWsStatus(status) {
this.wsStatus = status; this.wsStatus = status;
this.onWsStatusChange?.(status); this.onWsStatusChange?.(status);
if (status === 'disconnected') { if (status === 'disconnected') {
this.isControlled = false; this.isControlled = false;
this.onControlStatusChange?.(false); this.onControlStatusChange?.(false);
} }
} }
async connectDevice(device) { async connectDevice(device) {
if (!device) return; if (!device) return;
const sn =
device.serialNumber || device.device_sn; // 保存当前设备,用于保活/重连
this.currentDevice = device;
const sn = device.serialNumber || device.device_sn;
this.connectedDeviceSn = null; this.connectedDeviceSn = null;
this.wsDeviceInfo = {}; this.wsDeviceInfo = {};
this.isControlled = false; this.isControlled = false;
this.onControlStatusChange?.(false); this.onControlStatusChange?.(false);
wsManager.close(); wsManager.close();
@@ -102,12 +133,8 @@ export default class DeviceController {
token: this.userInfo.token, token: this.userInfo.token,
}); });
this.hasControlRight = res?.code === 200; this.hasControlRight = res?.code === 200;
this.onHasControlRightChange?.(this.hasControlRight);
this.onHasControlRightChange?.(
this.hasControlRight,
);
if (!this.hasControlRight) { if (!this.hasControlRight) {
this.messageApi.warning('其他端正在控制'); this.messageApi.warning('其他端正在控制');
@@ -115,13 +142,11 @@ export default class DeviceController {
} }
wsManager.connect(sn, this.wsUrl); wsManager.connect(sn, this.wsUrl);
this.connectedDeviceSn = sn; this.connectedDeviceSn = sn;
await this.getControl(sn); await this.getControl(sn);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
this.messageApi.error('权限校验失败'); this.messageApi.error('权限校验失败');
} }
} }
@@ -133,35 +158,23 @@ export default class DeviceController {
deviceId: serialnum, deviceId: serialnum,
}); });
this.isControlled = res?.code === 200 && res?.data?.remoteControl === true;
this.isControlled = this.onControlStatusChange?.(this.isControlled);
res?.code === 200 &&
res?.data?.remoteControl === true;
this.onControlStatusChange?.(
this.isControlled,
);
} catch (err) { } catch (err) {
console.error(err); console.error(err);
this.isControlled = false; this.isControlled = false;
this.onControlStatusChange?.(false); this.onControlStatusChange?.(false);
} }
} }
requestControl() { requestControl() {
if (this.isRequestControl) { if (this.isRequestControl) return;
return;
}
if (!this.hasControlRight) { if (!this.hasControlRight) {
this.messageApi.warning('无控制权限'); this.messageApi.warning('无控制权限');
return; return;
} }
this.isRequestControl = true; this.isRequestControl = true;
this.onRequestControlStatusChange?.(true); this.onRequestControlStatusChange?.(true);
this.messageApi.loading({ this.messageApi.loading({
@@ -170,22 +183,14 @@ export default class DeviceController {
duration: 0, duration: 0,
}); });
this.sendPermissionRequest( this.sendPermissionRequest(true, 'switchPermission');
true,
'switchPermission',
);
this.clearControlTimeout(); this.clearControlTimeout();
this.controlTimeout = setTimeout(() => { this.controlTimeout = setTimeout(() => {
if (!this.isRequestControl) return; if (!this.isRequestControl) return;
this.isRequestControl = false; this.isRequestControl = false;
this.onRequestControlStatusChange?.(false); this.onRequestControlStatusChange?.(false);
this.messageApi.destroy('control'); this.messageApi.destroy('control');
this.messageApi.error('控制请求超时'); this.messageApi.error('控制请求超时');
}, 10000); }, 10000);
} }
@@ -202,10 +207,7 @@ export default class DeviceController {
type, type,
switchResult: data, switchResult: data,
token: this.userInfo.token, token: this.userInfo.token,
deviceId: deviceId: type === 'switchPermission' ? this.connectedDeviceSn : this.requestDeviceId,
type === 'switchPermission'
? this.connectedDeviceSn
: this.requestDeviceId,
userName: this.userInfo.username, userName: this.userInfo.username,
}); });
} }
@@ -214,15 +216,11 @@ export default class DeviceController {
switch (msg.type) { switch (msg.type) {
case 'deviceInfo': { case 'deviceInfo': {
const data = {}; const data = {};
msg.data.forEach((item) => { msg.data.forEach((item) => {
data[item.name] = item.value; data[item.name] = item.value;
}); });
this.wsDeviceInfo = data; this.wsDeviceInfo = data;
this.onDeviceInfoUpdate?.(data); this.onDeviceInfoUpdate?.(data);
break; break;
} }
@@ -230,64 +228,36 @@ export default class DeviceController {
if (msg.isAuth) { if (msg.isAuth) {
this.getControl(this.connectedDeviceSn); this.getControl(this.connectedDeviceSn);
} }
break; break;
} }
case 'switchResult': { case 'switchResult': {
console.log(msg, "msg2222222222")
this.clearControlTimeout(); this.clearControlTimeout();
this.isRequestControl = false; this.isRequestControl = false;
this.onRequestControlStatusChange?.(false); this.onRequestControlStatusChange?.(false);
if ( if (msg.success === false || msg.switchResult === false) {
msg.success === false ||
msg.switchResult === false
) {
this.isControlled = false; this.isControlled = false;
this.onControlStatusChange?.(false); this.onControlStatusChange?.(false);
this.messageApi.error({ key: 'control', content: msg.message || '控制失败' });
this.messageApi.error({
key: 'control',
content: msg.message || '控制失败',
});
return; return;
} }
this.isControlled = true; this.isControlled = true;
this.onControlStatusChange?.(true); this.onControlStatusChange?.(true);
this.messageApi.success({ key: 'control', content: '控制成功' });
this.messageApi.success({
key: 'control',
content: '控制成功',
});
break; break;
} }
case 'switchPermission': { case 'switchPermission': {
console.log(msg, "msg111111111111111") const platform = (msg.platform || '').toLowerCase();
const platform = ( if (!platform || platform === 'web' || platform === 'null') return;
msg.platform || ''
).toLowerCase();
if (!platform || platform === 'web' || platform == "null") {
return;
}
this.requestDeviceId = msg.deviceId; this.requestDeviceId = msg.deviceId;
this.onPermissionRequest?.({ this.onPermissionRequest?.({
title: '权限请求', title: '权限请求',
content: `${msg.platform} 请求控制设备`, content: `${msg.platform} 请求控制设备`,
}); });
break; break;
} }
@@ -311,20 +281,12 @@ export default class DeviceController {
} }
sendGamepad(state) { sendGamepad(state) {
if ( if (!this.isControlled || !this.connectedDeviceSn) return;
!this.isControlled ||
!this.connectedDeviceSn
) {
return;
}
console.log(state, "state")
wsManager.send({ wsManager.send({
type: 'remoteControl', type: 'remoteControl',
remoteData: state, remoteData: state,
token: this.userInfo.token, token: this.userInfo.token,
userName: this.userInfo.username, userName: this.userInfo.username,
}); });
} }
} }