chenyc
2026-05-20 c8ba0f92b3f84273a78f06de25359db20c1b2a4d
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
function cloneObject(value) {
  return JSON.parse(JSON.stringify(value || {}));
}
 
class StateCache {
  constructor(options = {}) {
    this.includeDeviceIdField = options.includeDeviceIdField !== false;
    this.deviceIdField = options.deviceIdField || 'n';
    this.entries = new Map();
  }
 
  update(device, metric = {}, meta = {}) {
    if (!device || !device.deviceId) {
      throw new Error('设备缺少 deviceId');
    }
 
    const entry = this.getOrCreateEntry(device);
    entry.device = device;
    entry.lastUpdateAt = Date.now();
 
    if (meta.messageType === 'realtime') {
      entry.lastRealtimeAt = entry.lastUpdateAt;
    }
 
    if (meta.messageType === 'blood-pressure') {
      entry.lastBloodPressureAt = entry.lastUpdateAt;
    }
 
    Object.assign(entry.payload, metric);
 
    if (this.includeDeviceIdField) {
      entry.payload[this.deviceIdField] = device.deviceId;
    }
 
    return this.getPayload(device.deviceId);
  }
 
  getOrCreateEntry(device) {
    if (!this.entries.has(device.deviceId)) {
      const payload = {};
 
      if (this.includeDeviceIdField) {
        payload[this.deviceIdField] = device.deviceId;
      }
 
      this.entries.set(device.deviceId, {
        device,
        payload,
        firstSeenAt: Date.now(),
        lastUpdateAt: 0,
        lastRealtimeAt: 0,
        lastBloodPressureAt: 0,
      });
    }
 
    return this.entries.get(device.deviceId);
  }
 
  getPayload(deviceId) {
    const entry = this.entries.get(deviceId);
    if (!entry) {
      return null;
    }
 
    return cloneObject(entry.payload);
  }
 
  getSnapshot(deviceId) {
    if (deviceId) {
      const entry = this.entries.get(deviceId);
      if (!entry) {
        return null;
      }
 
      return {
        deviceId,
        payload: cloneObject(entry.payload),
        firstSeenAt: entry.firstSeenAt,
        lastUpdateAt: entry.lastUpdateAt,
        lastRealtimeAt: entry.lastRealtimeAt,
        lastBloodPressureAt: entry.lastBloodPressureAt,
      };
    }
 
    return Array.from(this.entries.keys()).map((key) => this.getSnapshot(key));
  }
 
  getSnapshotMap() {
    const map = new Map();
 
    for (const item of this.getSnapshot()) {
      map.set(item.deviceId, item);
    }
 
    return map;
  }
}
 
module.exports = {
  StateCache,
};