Browse Source

测试文件上传multer, 封装wsProxy

master
zhangjiming 4 months ago
parent
commit
f10a11044a
  1. 249
      package-lock.json
  2. 4
      package.json
  3. 2
      public/index.html
  4. 21
      public/main.js
  5. 63
      src/index.ts
  6. 1
      src/routes/auth.ts
  7. 1
      src/routes/calibration.ts
  8. 1
      src/routes/cmd.ts
  9. 58
      src/routes/debug.ts
  10. 16
      src/routes/measure.ts
  11. 1
      src/routes/measureAnalysis.ts
  12. 14
      src/routes/measureData.ts
  13. 1
      src/routes/rail.ts
  14. 53
      src/utils/wss.ts

249
package-lock.json

@ -10,14 +10,18 @@
"license": "ISC",
"dependencies": {
"body-parser": "^2.1.0",
"cors": "^2.8.5",
"express": "^5.0.1",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"ws": "^8.18.1"
},
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/morgan": "^1.9.9",
"@types/multer": "^1.4.12",
"@types/node": "^22.13.4",
"@types/ws": "^8.5.14",
"nodemon": "^3.1.9",
@ -115,6 +119,16 @@
"@types/node": "*"
}
},
"node_modules/@types/cors": {
"version": "2.8.17",
"resolved": "https://registry.npmmirror.com/@types/cors/-/cors-2.8.17.tgz",
"integrity": "sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/express": {
"version": "5.0.0",
"resolved": "https://registry.npmmirror.com/@types/express/-/express-5.0.0.tgz",
@ -165,6 +179,16 @@
"@types/node": "*"
}
},
"node_modules/@types/multer": {
"version": "1.4.12",
"resolved": "https://registry.npmmirror.com/@types/multer/-/multer-1.4.12.tgz",
"integrity": "sha512-pQ2hoqvXiJt2FP9WQVLPRO+AmiIm/ZYkavPlIQnx282u4ZrVdztx0pkh3jjpQt0Kz+YI0YhSG264y08UJKoUQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/express": "*"
}
},
"node_modules/@types/node": {
"version": "22.13.4",
"resolved": "https://registry.npmmirror.com/@types/node/-/node-22.13.4.tgz",
@ -275,6 +299,12 @@
"node": ">= 8"
}
},
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmmirror.com/arg/-/arg-4.1.3.tgz",
@ -402,6 +432,23 @@
"node": ">=8"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmmirror.com/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz",
@ -472,6 +519,21 @@
"dev": true,
"license": "MIT"
},
"node_modules/concat-stream": {
"version": "1.6.2",
"resolved": "https://registry.npmmirror.com/concat-stream/-/concat-stream-1.6.2.tgz",
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
"engines": [
"node >= 0.8"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^2.2.2",
"typedarray": "^0.0.6"
}
},
"node_modules/content-disposition": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-1.0.0.tgz",
@ -511,6 +573,25 @@
"node": ">=6.6.0"
}
},
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmmirror.com/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"license": "MIT"
},
"node_modules/cors": {
"version": "2.8.5",
"resolved": "https://registry.npmmirror.com/cors/-/cors-2.8.5.tgz",
"integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==",
"license": "MIT",
"dependencies": {
"object-assign": "^4",
"vary": "^1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/create-require/-/create-require-1.1.1.tgz",
@ -976,6 +1057,12 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/isarray": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"license": "MIT"
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmmirror.com/make-error/-/make-error-1.3.6.tgz",
@ -1056,6 +1143,27 @@
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmmirror.com/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmmirror.com/morgan/-/morgan-1.10.0.tgz",
@ -1105,6 +1213,67 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
"license": "MIT"
},
"node_modules/multer": {
"version": "1.4.5-lts.1",
"resolved": "https://registry.npmmirror.com/multer/-/multer-1.4.5-lts.1.tgz",
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/multer/node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmmirror.com/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/negotiator": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-1.0.0.tgz",
@ -1178,6 +1347,15 @@
"node": ">=0.10.0"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmmirror.com/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz",
@ -1251,6 +1429,12 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz",
@ -1322,6 +1506,27 @@
"node": ">=0.10.0"
}
},
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmmirror.com/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.3",
"isarray": "~1.0.0",
"process-nextick-args": "~2.0.0",
"safe-buffer": "~5.1.1",
"string_decoder": "~1.1.1",
"util-deprecate": "~1.0.1"
}
},
"node_modules/readable-stream/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-3.6.0.tgz",
@ -1562,6 +1767,29 @@
"node": ">= 0.8"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmmirror.com/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/string_decoder/-/string_decoder-1.1.1.tgz",
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.1.0"
}
},
"node_modules/string_decoder/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
"node_modules/supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-5.5.0.tgz",
@ -1665,6 +1893,12 @@
"node": ">= 0.6"
}
},
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmmirror.com/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/typescript": {
"version": "5.7.3",
"resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.7.3.tgz",
@ -1702,6 +1936,12 @@
"node": ">= 0.8"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/utils-merge/-/utils-merge-1.0.1.tgz",
@ -1754,6 +1994,15 @@
}
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmmirror.com/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/yn/-/yn-3.1.1.tgz",

4
package.json

@ -15,14 +15,18 @@
"description": "",
"dependencies": {
"body-parser": "^2.1.0",
"cors": "^2.8.5",
"express": "^5.0.1",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"ws": "^8.18.1"
},
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/morgan": "^1.9.9",
"@types/multer": "^1.4.12",
"@types/node": "^22.13.4",
"@types/ws": "^8.5.14",
"nodemon": "^3.1.9",

2
public/index.html

@ -11,7 +11,7 @@
<div>
<button id="startRecord">开始测量</button>
<button id="upload">连续上报</button>
<!-- <button id="upload">连续上报</button> -->
<button id="endRecord">结束测量</button>
</div>

21
public/main.js

@ -2,7 +2,7 @@ const ws = new WebSocket(`ws://${window.location.host}`);
ws.onopen = () => {
console.log("Connected to server");
ws.send("Hello from client!");
// ws.send("Hello from client!");
};
ws.onmessage = event => {
@ -16,7 +16,7 @@ ws.onclose = () => {
$("#startRecord").on("click", () => {
$.ajax({
type: "POST",
url: "/api/debug/record-sig/start",
url: "/api/measurement-task/start-measurement",
data: JSON.stringify({}),
contentType: "application/json",
success: res => {
@ -30,21 +30,7 @@ $("#startRecord").on("click", () => {
$("#endRecord").on("click", () => {
$.ajax({
type: "POST",
url: "/api/debug/record-sig/stop",
data: JSON.stringify({}),
contentType: "application/json",
success: res => {
console.log("Success", res);
},
error: err => {
console.error("Error", err);
},
});
});
$("#upload").on("click", () => {
$.ajax({
type: "POST",
url: "/api/debug/record-sig/upload",
url: "/api/measurement-task/stop-measurement",
data: JSON.stringify({}),
contentType: "application/json",
success: res => {
@ -55,3 +41,4 @@ $("#upload").on("click", () => {
},
});
});

63
src/index.ts

@ -3,9 +3,12 @@ import { Server } from "ws";
import http from "http";
import bodyParser from "body-parser";
import morgan from "morgan";
import multer from "multer";
import cors from 'cors';
import path from "path";
import cmdRouter from "./routes/cmd";
import debugRouter from "./routes/debug";
import authRouter from "./routes/auth";
import measureRouter from "./routes/measure";
import measureAnalysisRouter from "./routes/measureAnalysis";
@ -14,7 +17,7 @@ import railRouter from "./routes/rail";
import calibrationRouter from "./routes/calibration";
// import { defaultStatus, StatusDatagram } from "./types/wsTypes";
import { wsSend } from "./utils/wss";
import { WsProxy } from "./utils/wss";
import { ContextMessage, defaultContext, defaultMeasureState } from "./types/wsTypes";
const app = express();
@ -22,23 +25,11 @@ app.use(express.static("public"));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cors());
const server = http.createServer(app);
// 在HTTP服务器上初始化WebSocket服务器
const wss = new Server({ server });
wss.on("connection", ws => {
console.log("Client connected");
// ws.send("Welcome to the WebSocket server!");
// ws.on("message", message => {
// console.log(`Received message: ${message}`);
// wss.clients.forEach(client => {
// if (client.readyState === ws.OPEN) {
// client.send(message.toString());
// }
// });
// });
WsProxy.addActionForClientConnect((ws) => {
// DeviceContext
ws.send(
JSON.stringify({
@ -47,27 +38,18 @@ wss.on("connection", ws => {
path: "/deviceContext",
})
);
// MeasureState
ws.send(
JSON.stringify({
messageType: "EVENT",
data: app.locals["measure"],
path: "/measurement-task/get-task-state",
})
);
ws.on("close", () => {
console.log("Client disconnected");
});
});
// 在HTTP服务器上初始化WebSocket服务器
WsProxy.init(server);
// const wss = new Server({ server });
app.locals["wss"] = wss;
app.locals["context"] = defaultContext;
app.locals["measure"] = defaultMeasureState;
// app.get("/", (req, res) => {
// res.send("Hello World!");
// });
app.use("/api/debug", debugRouter);
app.use("/api/cmd", cmdRouter);
app.use("/api/auth", authRouter);
app.use("/api/measurement-analysis", measureAnalysisRouter);
@ -75,6 +57,29 @@ app.use("/api/measurement-task", measureRouter);
app.use("/api/measurement-data", measureDataRouter);
app.use("/api/standard-rail", railRouter);
app.use("/api/calibration", calibrationRouter);
const storage = multer.diskStorage({
destination: function (req, file, cb) {
// 指定文件存储的目录
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
// 指定文件保存的文件名
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// 创建上传文件的路由
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
res.status(400).json({msg:'未收到文件'});
} else {
res.json({msg:'文件上传成功!文件路径:' + req.file.path});
}
});
//@ts-ignore
app.use((err, req, res, next) => {
console.error(err.stack);

1
src/routes/auth.ts

@ -1,6 +1,5 @@
import express from "express";
const router = express.Router();
import { wsSend } from "../utils/wss";
import { delay } from "../utils/helper";
router.post("/login", async (req, res) => {

1
src/routes/calibration.ts

@ -1,6 +1,5 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
import { calibrationController } from "../controllers/calibration";
const router = express.Router();

1
src/routes/cmd.ts

@ -1,6 +1,5 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
const router = express.Router();
router.post("/", async (req, res) => {

58
src/routes/debug.ts

@ -1,58 +0,0 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
import { TrackRecordSig } from "../types/wsTypes";
const router = express.Router();
import points from "../utils/measure.json";
let ptIndex = 0;
let intervalId: ReturnType<typeof setInterval>;
// // console.log(points)
// router.post("/record-sig/:action", async (req, res) => {
// // await delay(200);
// if (req.params["action"] === "start") {
// ptIndex = 0;
// setTimeout(() => {
// wsSend(req.app.locals["wss"], {
// messageType: "EVENT",
// data: {
// event: "START_RECORD_SIG",
// },
// path: "/measurement-task/get-task-state",
// });
// }, 1000);
// } else if (req.params["action"] === "stop") {
// ptIndex = 0;
// setTimeout(() => {
// wsSend(req.app.locals["wss"], {
// messageType: "EVENT",
// data: {
// event: "END_RECORD_SIG",
// },
// path: "/measurement-task/get-task-state",
// });
// }, 1000);
// } else if (req.params["action"] === "upload") {
// intervalId = setInterval(() => {
// if (ptIndex >= points.length) {
// clearInterval(intervalId);
// // ptIndex = 0;
// return;
// }
// wsSend(req.app.locals["wss"], {
// messageType: "EVENT",
// data: {
// x: points[ptIndex].x,
// y: points[ptIndex].y,
// },
// path: "/measurement-task/profile-record-ctrl-sig",
// });
// ptIndex = ptIndex + 2;
// }, 10);
// }
// // const curr: StatusDatagram["data"] = req.app.locals["status"];
// res.json({ code: "00000", msg: "执行成功" });
// });
export default router;

16
src/routes/measure.ts

@ -1,10 +1,10 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
const router = express.Router();
import points from "../utils/measure.json";
import { MeasureState } from "../types/wsTypes";
import { WsProxy } from "../utils/wss";
let ptIndex = 0;
let intervalId1: ReturnType<typeof setInterval>;
let intervalId2: ReturnType<typeof setInterval>;
@ -35,22 +35,22 @@ router.post("/cache-measurement", async (req, res) => {
router.post("/start-measurement", (req, res) => {
setTimeout(() => {
ptIndex = 0;
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "EVENT",
data: "START_RECORD_LEFT",
path: "/api/measurement-task/event",
});
})
});
intervalId1 = setInterval(() => {
if (ptIndex >= points.length / 2) {
clearInterval(intervalId1);
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "EVENT",
data: "FINISH_RECORD_LEFT",
path: "/api/measurement-task/event",
});
setTimeout(() => {
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "EVENT",
data: "START_RECORD_RIGHT",
path: "/api/measurement-task/event",
@ -59,14 +59,14 @@ router.post("/start-measurement", (req, res) => {
if (ptIndex >= points.length) {
clearInterval(intervalId2);
ptIndex = 0;
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "EVENT",
data: "FINISH_RECORD_RIGHT",
path: "/api/measurement-task/event",
});
return;
}
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "STATE",
data: {
x: points[ptIndex].x,
@ -79,7 +79,7 @@ router.post("/start-measurement", (req, res) => {
}, 2000);
return;
}
wsSend(req.app.locals["wss"], {
WsProxy.send({
messageType: "STATE",
data: {
x: points[ptIndex].x,

1
src/routes/measureAnalysis.ts

@ -1,6 +1,5 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
const router = express.Router();
import points from "../utils/measure.json";

14
src/routes/measureData.ts

@ -1,21 +1,10 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
const router = express.Router();
router.post("/list", async (req, res) => {
await delay(100);
wsSend(req.app.locals["wss"], {
messageType: "STATE",
data: {
isConnect: true,
"connectPort": "COM4",//串口名
"sn": "xyz-abc",//连接的设备ID
"descriptivePortName": "COM4 serial ch340" //用于详细系
},
path: "/api/subdevice/uartchanel/get-channel-state",
});
res.json({
status: 0 ,
data:{
@ -63,5 +52,4 @@ router.post("/getDevice", async (req, res) => {
})
})
export default router

1
src/routes/rail.ts

@ -1,6 +1,5 @@
import express from "express";
import { delay } from "../utils/helper";
import { wsSend } from "../utils/wss";
import { railController } from "../controllers/rail";
const router = express.Router();

53
src/utils/wss.ts

@ -1,11 +1,50 @@
import { Server } from "ws";
import { Datagram } from "../types/wsTypes";
import http from 'http';
import { Server, WebSocket } from 'ws';
import { Datagram } from '../types/wsTypes';
export function wsSend(wss: Server, data: Datagram) {
// 广播消息给所有连接的客户端
wss.clients.forEach(client => {
if (client.readyState === client.OPEN) {
client.send(JSON.stringify(data));
export class WsProxy {
public static server: Server;
private static actionsWhenClientConnect: ((ws: WebSocket) => void)[] = [];
static addActionForClientConnect(act: (ws: WebSocket) => void) {
this.actionsWhenClientConnect.push(act);
}
static init(server: http.Server) {
this.server = new Server({ server });
this.onConnection();
}
private static onConnection() {
this.server.on('connection', ws => {
console.log('Client connected');
// ws.send("Welcome to the WebSocket server!");
// ws.on("message", message => {
// console.log(`Received message: ${message}`);
// wss.clients.forEach(client => {
// if (client.readyState === ws.OPEN) {
// client.send(message.toString());
// }
// });
// });
this.actionsWhenClientConnect.forEach(act => act(ws));
ws.on('close', () => {
console.log('Client disconnected');
});
});
}
public static send(data: Datagram, ws?: WebSocket) {
// DeviceContext
if (ws) {
ws.send(JSON.stringify(data));
} else {
this.server.clients.forEach(ws => {
if (ws.readyState === ws.OPEN) {
ws.send(JSON.stringify(data));
}
});
}
}
}
Loading…
Cancel
Save