xuchang-new/src/utils/index.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-11-30 16:07:41 +08:00
import { store } from "../store";
2023-11-09 13:36:21 +08:00
export function randomInt(min, max, includeMax = false) {
2023-11-30 16:07:41 +08:00
let Fn = includeMax ? Math.ceil : Math.floor;
let num = Fn(Math.random() * max);
while (num < min) {
num = Fn(Math.random() * max);
}
return num;
2023-11-09 13:36:21 +08:00
}
export class WsClient {
2023-11-30 16:07:41 +08:00
static wsServer = "ws://192.168.1.12:8081/xc-screen/websocket/info";
static socket = null;
static tryCount = 0;
2023-11-09 13:36:21 +08:00
2023-11-30 16:07:41 +08:00
constructor() {
if (WsClient.socket) return;
WsClient.socket = new WebSocket(WsClient.wsServer);
WsClient.socket.onopen = () => {
console.log("[*] websocket connected!");
};
WsClient.socket.onmessage = (e) => {
let serializedData = null;
try {
serializedData = JSON.parse(e.data);
} catch (error) {
console.log("[*] websocket: [unable to serialize] ---> ", e);
}
switch (serializedData?.type) {
case "KilnInfo": {
store.dispatch({
type: "kiln/setKilnInfo",
payload: serializedData.data,
});
break;
}
default: {
console.log("websocket message: [unknown] ---> ", e.data);
}
}
};
WsClient.socket.onerror = (e) => {
console.log("[*] websocket error!", e, e.data);
};
WsClient.socket.onclose = (e) => {
let timer = setTimeout(() => {
if (WsClient.tryCount < 3) {
const wsc = new WsClient();
wsc.init();
WsClient.tryCount += 1;
} else clearTimeout(timer);
}, 30000);
};
}
2023-11-09 13:36:21 +08:00
}