index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const WebSocket = require('ws');
  2. const { generateAmplitudeCycle } = require('./generator');
  3. const { ThresholdManager } = require('./threshold');
  4. const Parse = require('parse/node');
  5. // Parse初始化
  6. Parse.initialize('dev', 'devmk'); // appId, masterKey
  7. Parse.serverURL = 'http://dev.fmode.cn:1337/parse';
  8. const wss = new WebSocket.Server({ port: 8080 });
  9. console.log('WebSocket server started on ws://localhost:8080');
  10. // 阈值管理器实例
  11. const thresholdManager = new ThresholdManager();
  12. function getStageByIndex(index, stageDurations) {
  13. let sum = 0;
  14. for (let i = 0; i < stageDurations.length; i++) {
  15. sum += stageDurations[i];
  16. if (index < sum) return i;
  17. }
  18. return stageDurations.length - 1;
  19. }
  20. wss.on('connection', (ws, req) => {
  21. const url = new URL(req.url, `http://${req.headers.host}`);
  22. const device = url.searchParams.get('device') || 'A';
  23. console.log('Client connected, device:', device);
  24. ws.send(JSON.stringify({ type: 'info', msg: 'Connected to amplitude server.', device }));
  25. let { cycle, stages, duration } = generateAmplitudeCycle();
  26. let index = 0;
  27. const timer = setInterval(() => {
  28. if (index >= cycle.length) {
  29. thresholdManager.addNormalCycle(cycle, stages);
  30. ({ cycle, stages, duration } = generateAmplitudeCycle());
  31. index = 0;
  32. }
  33. const value = cycle[index];
  34. const { isAbnormal, lower, upper } = thresholdManager.checkAbnormal(value, index, stages);
  35. const stage = getStageByIndex(index, stages);
  36. const data = {
  37. value,
  38. index,
  39. isAbnormal,
  40. lower,
  41. upper,
  42. stage,
  43. timestamp: Date.now()
  44. };
  45. console.log('index:', index, 'stage:', stage, 'lower:', lower, 'upper:', upper);
  46. ws.send(JSON.stringify(data));
  47. // 写入 Parse Server
  48. const AmplitudeData = Parse.Object.extend('AmplitudeData');
  49. const amplitudeData = new AmplitudeData();
  50. amplitudeData.set('value', value);
  51. amplitudeData.set('index', index);
  52. amplitudeData.set('isAbnormal', isAbnormal);
  53. amplitudeData.set('lower', lower);
  54. amplitudeData.set('upper', upper);
  55. amplitudeData.set('stage', stage);
  56. amplitudeData.set('timestamp', new Date());
  57. amplitudeData.save().catch(err => {
  58. console.error('Parse save error:', err.message);
  59. });
  60. index++;
  61. }, 1000);
  62. ws.on('close', () => {
  63. clearInterval(timer);
  64. console.log('Client disconnected');
  65. });
  66. });