update websocket

This commit is contained in:
lb
2023-09-10 20:35:29 +08:00
parent ab954d3695
commit f13e543c0a
6 changed files with 87 additions and 34 deletions

View File

@@ -1,11 +1,13 @@
{
"baseInfo": {
"fireChangeTime": "20分钟",
"waterInTemp": "75.0",
"lastFireChangeTime": "10分15秒",
"kilnPressure": "94.0",
"fireDirection": "南火",
"waterOutTemp": "26.0"
"kilnInfo": {
"kilnPressure": "***Kpa",
"waterLoopTemperature": "...℃",
"waterLoopFlow": "+++m³/h",
"waterLoopPressure": "***Kpa",
"windPressure": "***Kpa",
"gasPressure": "***Kpa",
"topTemperature": "...℃",
"meltTemperature": "...℃"
},
"fan": [
["8#压延冷却风机", "4373Hz", "正常"],

View File

@@ -1,5 +1,6 @@
import { WebSocket, WebSocketServer } from 'ws';
import demoData from './demo.json';
import utils from './utils';
const wss = new WebSocketServer({ port: 9800 });
const frequency = 3; // seconds
@@ -24,7 +25,7 @@ wss.on('connection', function (ws, req) {
ws.on('error', console.error);
const timer = setInterval(() => {
sendMsg(ws, 'base-info');
sendMsg(ws, 'kiln-info'); // 窑炉信息
sendMsg(ws, 'fan');
sendMsg(ws, 'gas');
sendMsg(ws, 'kiln-top');
@@ -37,31 +38,37 @@ wss.on('connection', function (ws, req) {
});
});
type MsgType = 'base-info' | 'fan' | 'gas' | 'kiln-top' | 'kiln-bottom';
type MsgType = 'kiln-info' | 'fan' | 'gas' | 'kiln-top' | 'kiln-bottom';
function sendMsg(ws: WebSocket, type: MsgType) {
let data: any;
let data: {
[key: string]: string;
} = {};
switch (type) {
case 'base-info':
data = demoData.baseInfo;
case 'kiln-info':
for (const key in demoData.kilnInfo) {
data[key] = utils.getRandom(
demoData.kilnInfo[key as keyof typeof demoData.kilnInfo],
);
}
break;
case 'fan':
data = demoData.fan;
// data = demoData.fan;
break;
case 'gas':
data = demoData.gas;
// data = demoData.gas;
break;
case 'kiln-top':
data = demoData.kilnTop;
// data = demoData.kilnTop;
break;
case 'kiln-bottom':
data = demoData.kilnBottom;
// data = demoData.kilnBottom;
break;
default:
data = 'You are connected!';
// data = 'You are connected!';
break;
}
// console.log("sendMsg: ", ws);
// ws.emit("message", JSON.stringify(data));
ws.send(JSON.stringify(data));
ws.send(JSON.stringify({ type, data }));
}

39
websocket/utils.ts Normal file
View File

@@ -0,0 +1,39 @@
export default {
// 生成随机数
randomNum({ min, max }: { min: number; max: number }) {
return Math.floor(Math.random() * (max - min + 1) + min);
},
getMinmax(type: '*' | '.' | '+') {
let min: number, max: number;
switch (type) {
case '*':
min = 30;
max = 150;
break;
case '.':
min = 60;
max = 200;
break;
case '+':
min = 20;
max = 70;
break;
}
return { min, max };
},
getRandom(value: string) {
value = value.replace(
'***',
'' + this.randomNum({ ...this.getMinmax('*') }),
);
value = value.replace(
'...',
'' + this.randomNum({ ...this.getMinmax('.') }),
);
value = value.replace(
'+++',
'' + this.randomNum({ ...this.getMinmax('+') }),
);
return value;
},
};