chenyc
2026-05-09 c7d690bc224fb84e88d3033bf324876e4a64b008
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"use strict";
 
const { DeviceConnection } = require("./device-connection");
 
class DeviceManager {
  constructor({ config, dataCache, logger, uploadManager }) {
    this.config = config;
    this.dataCache = dataCache;
    this.logger = logger;
    this.uploadManager = uploadManager;
    this._connections = new Map();
  }
 
  startAll() {
    const enabled = this.config.devices.filter((d) => d.enabled !== false);
    const disabled = this.config.devices.length - enabled.length;
 
    for (const device of this.config.devices) {
      this.dataCache.update(device.ip, {
        serialNumber: device.serialNumber,
        status: device.enabled === false ? "disabled" : "pending",
        lastPollAt: null, lastDataAt: null,
        rawFrame: null, parsed: null, errorMessage: null, reconnectCount: 0,
      });
    }
 
    this.logger.sys(`启动 ${enabled.length} 台设备` + (disabled > 0 ? ` (${disabled} 台已禁用)` : ""));
 
    for (const device of enabled) {
      const conn = new DeviceConnection({
        ip: device.ip,
        port: device.port,
        serialNumber: device.serialNumber,
        config: this.config,
        dataCache: this.dataCache,
        logger: this.logger,
        uploadManager: this.uploadManager,
      });
      this._connections.set(device.ip, conn);
      conn.start();
    }
  }
 
  stopAll() {
    this.logger.sys(`停止 ${this._connections.size} 台设备连接`);
    for (const [, conn] of this._connections) {
      conn.stop();
    }
    this._connections.clear();
  }
 
  restart(ip) {
    const conn = this._connections.get(ip);
    if (conn) {
      this.logger.sys(`${ip} 手动重启`);
      conn.stop();
      conn.start();
    }
  }
}
 
module.exports = { DeviceManager };