anxiao_web/pages/index/api/moveDeviceWebsocket.js

89 lines
2.4 KiB
JavaScript

import { movedevicewebsocketurl } from "../../../public/js/url.js";
let mdWsFlag = 60;
let mdWsTimer = null;
let mdWebsocketConnect = null;
let deviceHash={};
function moveDeviceWebsocket(){
return new Promise((resolve, reject) => {
mdWebsocketConnect = new WebSocket(movedevicewebsocketurl);
mdWebsocketConnect.onopen = function (evt) {
mdWsFlag = 3;
if (mdWsTimer != null) {
clearInterval(mdWsTimer);
mdWsTimer = null;
mdWsFlag=60;
}
resolve({
"msg":"移动设备websocket连接成功",
"code":0,
"mdWebsocketConnect":mdWebsocketConnect
})
setInterval(()=>{
let messageObj = {
"msgcode": 99,
"msgname": "hb",
"message":"hb"
}
if(mdWebsocketConnect!=null){
mdWebsocketConnect.send(JSON.stringify(messageObj));
}
},5000)
};
mdWebsocketConnect.onclose = function (evt) {
console.log("移动设备的websocket已经断开onclose");
mdWebsocketConnect.close();
mdevWebsocketReconnection();
};
mdWebsocketConnect.onerror = function (evt) {
console.log("移动设备的websocket已经断开onerror")
mdWebsocketConnect.close();
mdevWebsocketReconnection();
};
mdWebsocketConnect.onmessage = function (evt) {
var data=JSON.parse(evt.data);
var msgcode=data["msgcode"];
var message=data["message"];
if(msgcode=="4000"){//设备心跳
//websoceketDeviceBear(message);
}else if(msgcode=="4001"){//这是普通的事件
//查询设备的事件跟报警
//getDevicePhotoAndSos();
}else if(msgcode=="4002"){//设备在线,离线状态
//deviceStatusUpdate(message);
}else if(msgcode=="403"){//获取移动设备的设备列表
//这里需要判断一下,如果是重连,就不做任何事情,只需要连接一下
var list=message["list"];
var pagepro=message["pagepro"];
for(var dev=0;dev<list.length;dev++){
var deviceid=list[dev]["deviceid"];
deviceHash[deviceid]=list[dev];
}
if(pagepro=="end"||pagepro=="start-end"){
console.log(deviceHash);
}
}
}
})
}
function mdevWebsocketReconnection(){
mdWebsocketConnect = null;
mdWsTimer = null;
if (mdWsTimer == null) {
mdWsTimer = setInterval(function () {
connectWebsocket();
mdWsFlag--;
if(mdWsFlag==0){
layer.msg("网络中断,请重新连接...");
clearInterval(mdWsTimer);
mdWsTimer = null;
}
}, 5000)
}
}
export {moveDeviceWebsocket,deviceHash}