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
"use strict";
 
class DataCache {
  constructor() {
    this._map = new Map();
    this._onUpdate = null;
  }
 
  setUpdateListener(fn) {
    this._onUpdate = fn;
  }
 
  update(ip, data) {
    const existing = this._map.get(ip) || {};
    this._map.set(ip, { ...existing, ...data });
    if (this._onUpdate) {
      this._onUpdate(ip, this._map.get(ip));
    }
  }
 
  get(ip) {
    return this._map.get(ip) || null;
  }
 
  getAll() {
    const devices = [];
    for (const [ip, data] of this._map) {
      devices.push({ ip, ...data });
    }
    return devices;
  }
 
  getSummary() {
    let total = 0;
    let connected = 0;
    let hasData = 0;
    let abnormal = 0;
 
    for (const [, data] of this._map) {
      total++;
      if (data.status === "connected") {
        connected++;
        if (data.lastDataAt) hasData++;
      } else if (data.status === "disconnected" || data.status === "error") {
        abnormal++;
      }
    }
 
    return { total, connected, hasData, abnormal };
  }
}
 
module.exports = { DataCache };