106 regels
2.9 KiB
JavaScript
106 regels
2.9 KiB
JavaScript
import { WebSocket, WebSocketServer } from "ws";
|
|
import template from "./template.json";
|
|
import utils from "./utils";
|
|
|
|
const wss = new WebSocketServer({ port: 9800 });
|
|
const frequency = 10; // seconds
|
|
const frequency1 = 1200; // seconds
|
|
wss.on("connection", function (ws, req) {
|
|
// console.log("ws", ws);
|
|
console.log(
|
|
"Client in: ",
|
|
req.socket.remoteAddress,
|
|
"current users:",
|
|
wss.clients.size
|
|
);
|
|
// ws.on("error", console.error);
|
|
// ws.emit("message", "connected");
|
|
ws.on("open", function () {
|
|
console.log("connected");
|
|
ws.send("connected");
|
|
});
|
|
ws.on("message", function (msg) {
|
|
console.log("message from client", msg);
|
|
ws.send("echo " + msg.toString());
|
|
});
|
|
ws.on("error", console.error);
|
|
|
|
const timer = setInterval(() => {
|
|
sendMsg(ws, "kiln-info"); // 窑炉信息
|
|
sendMsg(ws, "energy-cost"); // 运行状态
|
|
sendMsg(ws, "run-state"); // 运行状态
|
|
sendMsg(ws, "realtime");
|
|
sendMsg(ws, "his-trend");
|
|
// sendMsg(ws, 'gas');
|
|
// sendMsg(ws, 'kiln-top');
|
|
// sendMsg(ws, 'kiln-bottom');
|
|
}, frequency * 1000);
|
|
|
|
const timer1 = setInterval(() => {
|
|
// sendMsg(ws, 'run-state'); // 运行状态
|
|
}, frequency1 * 1000);
|
|
|
|
ws.on("close", function () {
|
|
console.log("停止监听");
|
|
clearInterval(timer);
|
|
clearInterval(timer1);
|
|
});
|
|
});
|
|
|
|
function sendMsg(ws, type) {
|
|
let data = {};
|
|
switch (type) {
|
|
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 }));
|
|
}
|