96 lignes
2.5 KiB
JavaScript
96 lignes
2.5 KiB
JavaScript
const { WebSocket } = require("ws");
|
|
const { getRandomAlarmList } = require("./fakedata/alarmList");
|
|
|
|
const wss = new WebSocket.Server({ port: 9800 });
|
|
console.log('[websocket] server created');
|
|
|
|
wss.on("connection", function (ws, req) {
|
|
console.log(
|
|
"[用户连接]: ",
|
|
req.socket.remoteAddress,
|
|
"当前总用户数:",
|
|
wss.clients.size
|
|
);
|
|
ws.on("open", function () {
|
|
console.log('[websocket] opened');
|
|
ws.send("connected");
|
|
});
|
|
ws.on("message", function (msg) {
|
|
console.log("[==>]", msg);
|
|
});
|
|
ws.on("error", console.error);
|
|
|
|
const timer = setInterval(() => {
|
|
sendMsg(ws, "alarmList"); // 报警信息
|
|
}, 10 * 1000);
|
|
|
|
ws.on("close", function () {
|
|
console.log("停止监听");
|
|
clearInterval(timer);
|
|
});
|
|
});
|
|
|
|
function sendMsg(ws, type) {
|
|
let data = {};
|
|
switch (type) {
|
|
case "alarmList":
|
|
const alarmList = getRandomAlarmList(Math.floor(Math.random() * 10) + 1);
|
|
alarmList.forEach((str) => {
|
|
const [code, detail] = str.split(",");
|
|
data[code] = detail;
|
|
});
|
|
break;
|
|
case "kiln-info":
|
|
for (const key in template.kilnInfo) {
|
|
data[key] = utils.getRandom(template.kilnInfo[key]);
|
|
}
|
|
break;
|
|
case "energy-cost":
|
|
for (const key in template.energyCost) {
|
|
data[key] = utils.getRandom(template.energyCost[key]);
|
|
}
|
|
break;
|
|
case "run-state":
|
|
data = template.runState;
|
|
data.fireDirection =
|
|
Math.floor(Math.random() * 10) % 2 === 0 ? "南火" : "北火";
|
|
break;
|
|
case "realtime":
|
|
/** 天然气 实时流量 */
|
|
data.gasii = template.realtime.gasii.map((v) => utils.getRandom(v));
|
|
/** 助燃风 实时流量 */
|
|
data.wind = template.realtime.wind.map((v) => utils.getRandom(v));
|
|
break;
|
|
case "his-trend":
|
|
const hisTrend = {
|
|
gas: {},
|
|
wind: {},
|
|
};
|
|
Object.keys(template.hisTrend.gas).forEach((key) => {
|
|
hisTrend.gas[key] = template.hisTrend.gas[key].map((v) =>
|
|
utils.getRandom(v)
|
|
);
|
|
});
|
|
Object.keys(template.hisTrend.wind).forEach((key) => {
|
|
hisTrend.wind[key] = template.hisTrend.wind[key].map((v) =>
|
|
utils.getRandom(v)
|
|
);
|
|
});
|
|
data = hisTrend;
|
|
break;
|
|
case "gas":
|
|
// data = template.gas;
|
|
break;
|
|
case "kiln-top":
|
|
// data = template.kilnTop;
|
|
break;
|
|
case "kiln-bottom":
|
|
// data = template.kilnBottom;
|
|
break;
|
|
default:
|
|
// data = 'You are connected!';
|
|
break;
|
|
}
|
|
ws.send(JSON.stringify({ type, data }));
|
|
}
|