node-red-contrib-unifi-ultimate 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,53 @@ const {
21
21
 
22
22
  module.exports = function(RED) {
23
23
  const API_KEY_HEADER = "X-API-Key";
24
+ const MIN_POWER_OBSERVER_INTERVAL_SECONDS = 5;
25
+ const DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS = 15;
26
+ const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
27
+
28
+ function normalizePowerObserverIntervalSeconds(value) {
29
+ const parsed = Number(value);
30
+ if (!Number.isFinite(parsed)) {
31
+ return DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS;
32
+ }
33
+ const integer = Math.trunc(parsed);
34
+ if (integer < MIN_POWER_OBSERVER_INTERVAL_SECONDS) {
35
+ return MIN_POWER_OBSERVER_INTERVAL_SECONDS;
36
+ }
37
+ return integer;
38
+ }
39
+
40
+ function resolveObservedPortIdx(value) {
41
+ const parsed = Number(value);
42
+ if (!Number.isFinite(parsed) || parsed < 0) {
43
+ return NaN;
44
+ }
45
+ return Math.trunc(parsed);
46
+ }
47
+
48
+ function hasObservedPowerChanged(previousPowerW, nextPowerW) {
49
+ const previous = Number(previousPowerW);
50
+ const next = Number(nextPowerW);
51
+ if (!Number.isFinite(previous) && !Number.isFinite(next)) {
52
+ return false;
53
+ }
54
+ if (!Number.isFinite(previous) || !Number.isFinite(next)) {
55
+ return true;
56
+ }
57
+ return Math.abs(previous - next) >= 0.001;
58
+ }
59
+
60
+ function buildStatusTimestampText() {
61
+ const now = new Date();
62
+ const time = now.toTimeString().split(" ")[0];
63
+ return `(day ${now.getDate()}, ${time})`;
64
+ }
65
+
66
+ function appendStatusTimestamp(text) {
67
+ const normalized = String(text === undefined || text === null ? "" : text).trim();
68
+ const suffix = buildStatusTimestampText();
69
+ return normalized ? `${normalized} ${suffix}` : suffix;
70
+ }
24
71
 
25
72
  function UnifiNetworkConfigNode(config) {
26
73
  RED.nodes.createNode(this, config);
@@ -30,10 +77,30 @@ module.exports = function(RED) {
30
77
  node.host = String(config.host || "").trim();
31
78
  node.baseUrl = buildBaseUrlFromHost(node.host);
32
79
  node.rejectUnauthorized = config.rejectUnauthorized !== false && config.rejectUnauthorized !== "false";
80
+ node.powerObservationIntervalSeconds = normalizePowerObserverIntervalSeconds(config.powerObservationIntervalSeconds);
33
81
  node.nodeClients = [];
34
82
  node.wsNetworkEvents = null;
35
83
  node.reconnectTimer = null;
36
84
  node.isClosing = false;
85
+ node.powerObserverNodeState = new Map();
86
+ node.powerObserverTimer = null;
87
+ node.powerObserverPollInProgress = false;
88
+ node.presenceObserverNodeState = new Map();
89
+ node.presenceObserverTimer = null;
90
+ node.presenceObserverPollInProgress = false;
91
+ node.unofficialPollObserverNodeState = new Map();
92
+ node.unofficialPollObserverTimer = null;
93
+ node.unofficialPollObserverPollInProgress = false;
94
+
95
+ function setNodeStatus(status) {
96
+ if (!status || typeof status !== "object" || Array.isArray(status)) {
97
+ return;
98
+ }
99
+ node.status({
100
+ ...status,
101
+ text: appendStatusTimestamp(status.text)
102
+ });
103
+ }
37
104
 
38
105
  node.getApiKey = () => node.credentials && node.credentials.apiKey;
39
106
 
@@ -75,6 +142,9 @@ module.exports = function(RED) {
75
142
  );
76
143
  };
77
144
 
145
+ // Leaf nodes must delegate outbound UniFi calls to the config node.
146
+ node.executeNetworkRequest = async (request) => node.apiRequest(request || {});
147
+
78
148
  node.legacyApiRequest = async ({
79
149
  path,
80
150
  method = "GET",
@@ -112,6 +182,9 @@ module.exports = function(RED) {
112
182
  );
113
183
  };
114
184
 
185
+ // Leaf nodes must delegate outbound UniFi legacy calls to the config node.
186
+ node.executeLegacyNetworkRequest = async (request) => node.legacyApiRequest(request || {});
187
+
115
188
  node.fetchPagedCollection = async ({
116
189
  path,
117
190
  baseQuery,
@@ -1430,6 +1503,747 @@ module.exports = function(RED) {
1430
1503
  });
1431
1504
  };
1432
1505
 
1506
+ node.fetchDevicePortsPowerLite = async (deviceId) => {
1507
+ const device = await node.fetchDeviceByTypeAndId("device", deviceId);
1508
+ const ports = extractDevicePorts(device);
1509
+ if (!Array.isArray(ports) || ports.length === 0) {
1510
+ return [];
1511
+ }
1512
+
1513
+ const hasOfficialPower = ports.some((port) => Number.isFinite(Number(port && port.poePowerW)));
1514
+ if (hasOfficialPower) {
1515
+ return ports.map((port) => ({
1516
+ ...port,
1517
+ poePowerW: Number.isFinite(Number(port && port.poePowerW))
1518
+ ? Math.round(Number(port.poePowerW) * 1000) / 1000
1519
+ : undefined
1520
+ }));
1521
+ }
1522
+
1523
+ const scopedDevice = resolveScopedIdentifiers("device", deviceId, device);
1524
+ if (!scopedDevice.siteId || !scopedDevice.resourceId) {
1525
+ return ports;
1526
+ }
1527
+
1528
+ const selectedDevice = device && typeof device === "object" && !Array.isArray(device)
1529
+ ? device
1530
+ : {};
1531
+ const selectedDeviceKeys = new Set();
1532
+ [
1533
+ scopedDevice.resourceId,
1534
+ selectedDevice.id,
1535
+ selectedDevice.deviceId,
1536
+ selectedDevice.device_id,
1537
+ selectedDevice.macAddress,
1538
+ selectedDevice.mac,
1539
+ selectedDevice.mac_address
1540
+ ].forEach((value) => addIdentifierKeys(selectedDeviceKeys, value));
1541
+
1542
+ let legacyPortPowerByIdx = new Map();
1543
+ try {
1544
+ const legacyDevices = await fetchLegacyDevices(scopedDevice.siteId);
1545
+ const selectedLegacyDevice = legacyDevices.find((legacyDevice) => {
1546
+ return [
1547
+ legacyDevice && legacyDevice.device_id,
1548
+ legacyDevice && legacyDevice.id,
1549
+ legacyDevice && legacyDevice._id,
1550
+ legacyDevice && legacyDevice.mac
1551
+ ].some((value) => {
1552
+ const rawKey = normalizeString(value).toLowerCase();
1553
+ const compactKey = normalizeIdentifierKey(value);
1554
+ return selectedDeviceKeys.has(rawKey) || selectedDeviceKeys.has(compactKey);
1555
+ });
1556
+ });
1557
+
1558
+ const legacyPortTable = Array.isArray(selectedLegacyDevice && selectedLegacyDevice.port_table)
1559
+ ? selectedLegacyDevice.port_table
1560
+ : [];
1561
+ legacyPortTable.forEach((legacyPort, index) => {
1562
+ const idx = parsePortIndex(
1563
+ legacyPort && (
1564
+ legacyPort.port_idx
1565
+ ?? legacyPort.idx
1566
+ ?? legacyPort.port_index
1567
+ ?? legacyPort.index
1568
+ ?? (index + 1)
1569
+ )
1570
+ );
1571
+ if (!Number.isInteger(idx) || idx < 0) {
1572
+ return;
1573
+ }
1574
+ const powerW = extractLegacyPortPoePowerWatts(legacyPort);
1575
+ if (Number.isFinite(powerW)) {
1576
+ legacyPortPowerByIdx.set(idx, powerW);
1577
+ }
1578
+ });
1579
+ } catch (error) {
1580
+ legacyPortPowerByIdx = new Map();
1581
+ }
1582
+
1583
+ return ports.map((port) => {
1584
+ const mergedPowerW = Number.isFinite(Number(port && port.poePowerW))
1585
+ ? Number(port.poePowerW)
1586
+ : legacyPortPowerByIdx.get(port.idx);
1587
+ return {
1588
+ ...port,
1589
+ poePowerW: Number.isFinite(mergedPowerW)
1590
+ ? Math.round(mergedPowerW * 1000) / 1000
1591
+ : undefined
1592
+ };
1593
+ });
1594
+ };
1595
+
1596
+ node.fetchPowerObservationSnapshot = async (deviceId) => {
1597
+ const ports = await node.fetchDevicePortsPowerLite(deviceId);
1598
+ const portsByIdx = new Map();
1599
+ let powerSum = 0;
1600
+ let powerCount = 0;
1601
+
1602
+ ports.forEach((entry) => {
1603
+ const port = entry && typeof entry === "object" && !Array.isArray(entry)
1604
+ ? entry
1605
+ : {};
1606
+ const idx = resolveObservedPortIdx(port.idx);
1607
+ if (Number.isInteger(idx) && idx >= 0) {
1608
+ portsByIdx.set(idx, port);
1609
+ }
1610
+ const power = Number(port.poePowerW);
1611
+ if (Number.isFinite(power)) {
1612
+ powerSum += power;
1613
+ powerCount += 1;
1614
+ }
1615
+ });
1616
+
1617
+ const totalPower = Math.round(powerSum * 1000) / 1000;
1618
+ return {
1619
+ portsByIdx,
1620
+ powerConsumptionSwitchTotal: powerCount > 0 && Number.isFinite(totalPower)
1621
+ ? totalPower
1622
+ : undefined
1623
+ };
1624
+ };
1625
+
1626
+ node.notifyPowerObserverClient = (client, event) => {
1627
+ if (!client || typeof client.handleNetworkPoePowerObservationUpdate !== "function") {
1628
+ return;
1629
+ }
1630
+ try {
1631
+ client.handleNetworkPoePowerObservationUpdate(event);
1632
+ } catch (error) {
1633
+ }
1634
+ };
1635
+
1636
+ node.getPowerObservationClients = () => {
1637
+ return node.nodeClients
1638
+ .map((client) => {
1639
+ if (!client || typeof client.getNetworkPoePowerObservationDescriptor !== "function") {
1640
+ return null;
1641
+ }
1642
+ let descriptor;
1643
+ try {
1644
+ descriptor = client.getNetworkPoePowerObservationDescriptor();
1645
+ } catch (error) {
1646
+ return null;
1647
+ }
1648
+ if (!descriptor || typeof descriptor !== "object") {
1649
+ return null;
1650
+ }
1651
+
1652
+ const deviceId = normalizeString(descriptor.deviceId);
1653
+ const portIdx = resolveObservedPortIdx(descriptor.portIdx);
1654
+ if (!deviceId || !Number.isInteger(portIdx)) {
1655
+ return null;
1656
+ }
1657
+
1658
+ return {
1659
+ client,
1660
+ descriptor: {
1661
+ deviceId,
1662
+ portIdx,
1663
+ intervalSeconds: node.powerObservationIntervalSeconds
1664
+ }
1665
+ };
1666
+ })
1667
+ .filter(Boolean);
1668
+ };
1669
+
1670
+ node.refreshPowerObservationScheduler = () => {
1671
+ const activeClientIds = new Set(
1672
+ node.getPowerObservationClients()
1673
+ .map((entry) => normalizeString(entry.client && entry.client.id))
1674
+ .filter(Boolean)
1675
+ );
1676
+
1677
+ Array.from(node.powerObserverNodeState.keys()).forEach((clientId) => {
1678
+ if (!activeClientIds.has(clientId)) {
1679
+ node.powerObserverNodeState.delete(clientId);
1680
+ }
1681
+ });
1682
+
1683
+ if (activeClientIds.size === 0 || node.isClosing) {
1684
+ node.stopPowerObservationScheduler();
1685
+ return;
1686
+ }
1687
+
1688
+ if (!node.powerObserverTimer) {
1689
+ node.powerObserverTimer = setInterval(() => {
1690
+ node.pollPowerObservers().catch(() => {
1691
+ });
1692
+ }, POWER_OBSERVER_SCHEDULER_TICK_MS);
1693
+ }
1694
+ node.updateObserverDebugStatus();
1695
+ };
1696
+
1697
+ node.getPowerObservationClientState = (clientId) => {
1698
+ const normalizedClientId = normalizeString(clientId);
1699
+ if (!normalizedClientId) {
1700
+ return null;
1701
+ }
1702
+ if (!node.powerObserverNodeState.has(normalizedClientId)) {
1703
+ node.powerObserverNodeState.set(normalizedClientId, {
1704
+ nextRunAt: Date.now(),
1705
+ hasObservedPower: false,
1706
+ lastObservedPowerW: undefined
1707
+ });
1708
+ }
1709
+ return node.powerObserverNodeState.get(normalizedClientId);
1710
+ };
1711
+
1712
+ node.stopPowerObservationScheduler = () => {
1713
+ if (node.powerObserverTimer) {
1714
+ clearInterval(node.powerObserverTimer);
1715
+ node.powerObserverTimer = null;
1716
+ }
1717
+ node.updateObserverDebugStatus();
1718
+ };
1719
+
1720
+ node.pollPowerObservers = async () => {
1721
+ if (node.powerObserverPollInProgress) {
1722
+ return;
1723
+ }
1724
+ node.powerObserverPollInProgress = true;
1725
+
1726
+ try {
1727
+ const observedClients = node.getPowerObservationClients();
1728
+ if (observedClients.length === 0) {
1729
+ node.stopPowerObservationScheduler();
1730
+ return;
1731
+ }
1732
+
1733
+ const now = Date.now();
1734
+ const dueByDevice = new Map();
1735
+ observedClients.forEach((entry) => {
1736
+ const clientId = normalizeString(entry.client && entry.client.id);
1737
+ if (!clientId) {
1738
+ return;
1739
+ }
1740
+ const state = node.getPowerObservationClientState(clientId);
1741
+ if (!state || Number(state.nextRunAt) > now) {
1742
+ return;
1743
+ }
1744
+
1745
+ state.nextRunAt = now + (entry.descriptor.intervalSeconds * 1000);
1746
+ const list = dueByDevice.get(entry.descriptor.deviceId) || [];
1747
+ list.push({
1748
+ client: entry.client,
1749
+ descriptor: entry.descriptor,
1750
+ state
1751
+ });
1752
+ dueByDevice.set(entry.descriptor.deviceId, list);
1753
+ });
1754
+
1755
+ if (dueByDevice.size === 0) {
1756
+ return;
1757
+ }
1758
+
1759
+ for (const [deviceId, entries] of dueByDevice.entries()) {
1760
+ let snapshot;
1761
+ try {
1762
+ snapshot = await node.fetchPowerObservationSnapshot(deviceId);
1763
+ } catch (error) {
1764
+ continue;
1765
+ }
1766
+
1767
+ entries.forEach((entry) => {
1768
+ const selectedPort = snapshot.portsByIdx.get(entry.descriptor.portIdx) || null;
1769
+ if (!selectedPort) {
1770
+ node.notifyPowerObserverClient(entry.client, {
1771
+ source: entry.state.hasObservedPower ? "poll" : "startup",
1772
+ available: false,
1773
+ deviceId: entry.descriptor.deviceId,
1774
+ portIdx: entry.descriptor.portIdx,
1775
+ intervalSeconds: entry.descriptor.intervalSeconds
1776
+ });
1777
+ return;
1778
+ }
1779
+
1780
+ const source = entry.state.hasObservedPower ? "poll" : "startup";
1781
+ const numericPower = Number(selectedPort.poePowerW);
1782
+ const powerW = Number.isFinite(numericPower) ? numericPower : undefined;
1783
+ const powerChanged = hasObservedPowerChanged(entry.state.lastObservedPowerW, powerW);
1784
+
1785
+ entry.state.lastObservedPowerW = powerW;
1786
+ entry.state.hasObservedPower = true;
1787
+
1788
+ node.notifyPowerObserverClient(entry.client, {
1789
+ source,
1790
+ available: true,
1791
+ deviceId: entry.descriptor.deviceId,
1792
+ portIdx: entry.descriptor.portIdx,
1793
+ intervalSeconds: entry.descriptor.intervalSeconds,
1794
+ selectedPort,
1795
+ powerConsumptionSwitchTotal: snapshot.powerConsumptionSwitchTotal,
1796
+ portPowerW: powerW,
1797
+ powerChanged
1798
+ });
1799
+ });
1800
+ }
1801
+ } finally {
1802
+ node.powerObserverPollInProgress = false;
1803
+ node.updateObserverDebugStatus();
1804
+ }
1805
+ };
1806
+
1807
+ node.fetchPresenceObservationSnapshot = async (clientId, timeout) => {
1808
+ const scoped = resolveScopedIdentifiers("client", clientId);
1809
+ if (!scoped.siteId || !scoped.resourceId) {
1810
+ throw new Error("Client selection is invalid. Re-select the client from the editor.");
1811
+ }
1812
+
1813
+ const response = await node.apiRequest({
1814
+ path: `/v1/sites/${encodeURIComponent(scoped.siteId)}/clients/${encodeURIComponent(scoped.resourceId)}`,
1815
+ method: "GET",
1816
+ timeout: Number(timeout) > 0 ? Number(timeout) : 8000
1817
+ });
1818
+
1819
+ if (response.statusCode === 404) {
1820
+ return {
1821
+ found: false,
1822
+ connected: false,
1823
+ statusCode: 404,
1824
+ client: null
1825
+ };
1826
+ }
1827
+ if (response.statusCode < 200 || response.statusCode >= 300) {
1828
+ return {
1829
+ found: false,
1830
+ connected: false,
1831
+ statusCode: response.statusCode,
1832
+ client: null,
1833
+ error: `Client lookup failed (${response.statusCode})`
1834
+ };
1835
+ }
1836
+
1837
+ const client = extractNetworkData(response.payload);
1838
+ return {
1839
+ found: true,
1840
+ connected: true,
1841
+ statusCode: response.statusCode,
1842
+ client: client && typeof client === "object" && !Array.isArray(client) ? client : null
1843
+ };
1844
+ };
1845
+
1846
+ node.requestPresenceObservationNow = async (descriptor) => {
1847
+ if (!descriptor || typeof descriptor !== "object") {
1848
+ throw new Error("Invalid presence descriptor.");
1849
+ }
1850
+ const snapshot = await node.fetchPresenceObservationSnapshot(descriptor.clientId, descriptor.timeout);
1851
+ return {
1852
+ source: normalizeString(descriptor.source) || "manual-input",
1853
+ ...snapshot,
1854
+ clientId: descriptor.clientId
1855
+ };
1856
+ };
1857
+
1858
+ node.notifyPresenceObserverClient = (client, event) => {
1859
+ if (!client || typeof client.handleNetworkPresenceObservationUpdate !== "function") {
1860
+ return;
1861
+ }
1862
+ try {
1863
+ client.handleNetworkPresenceObservationUpdate(event);
1864
+ } catch (error) {
1865
+ }
1866
+ };
1867
+
1868
+ node.getPresenceObservationClients = () => {
1869
+ return node.nodeClients
1870
+ .map((client) => {
1871
+ if (!client || typeof client.getNetworkPresenceObservationDescriptor !== "function") {
1872
+ return null;
1873
+ }
1874
+ let descriptor;
1875
+ try {
1876
+ descriptor = client.getNetworkPresenceObservationDescriptor();
1877
+ } catch (error) {
1878
+ return null;
1879
+ }
1880
+ if (!descriptor || typeof descriptor !== "object") {
1881
+ return null;
1882
+ }
1883
+
1884
+ const clientId = normalizeString(descriptor.clientId);
1885
+ const pollIntervalSeconds = Number(descriptor.pollIntervalSeconds);
1886
+ const timeout = Number(descriptor.timeout);
1887
+ if (!clientId || !Number.isFinite(pollIntervalSeconds) || pollIntervalSeconds <= 0) {
1888
+ return null;
1889
+ }
1890
+
1891
+ return {
1892
+ client,
1893
+ descriptor: {
1894
+ clientId,
1895
+ pollIntervalMs: Math.max(1000, Math.trunc(pollIntervalSeconds * 1000)),
1896
+ timeout: Number.isFinite(timeout) && timeout > 0 ? Math.trunc(timeout) : 8000
1897
+ }
1898
+ };
1899
+ })
1900
+ .filter(Boolean);
1901
+ };
1902
+
1903
+ node.refreshPresenceObservationScheduler = () => {
1904
+ const activeClientIds = new Set(
1905
+ node.getPresenceObservationClients()
1906
+ .map((entry) => normalizeString(entry.client && entry.client.id))
1907
+ .filter(Boolean)
1908
+ );
1909
+
1910
+ Array.from(node.presenceObserverNodeState.keys()).forEach((clientId) => {
1911
+ if (!activeClientIds.has(clientId)) {
1912
+ node.presenceObserverNodeState.delete(clientId);
1913
+ }
1914
+ });
1915
+
1916
+ if (activeClientIds.size === 0 || node.isClosing) {
1917
+ node.stopPresenceObservationScheduler();
1918
+ return;
1919
+ }
1920
+
1921
+ if (!node.presenceObserverTimer) {
1922
+ node.presenceObserverTimer = setInterval(() => {
1923
+ node.pollPresenceObservers().catch(() => {
1924
+ });
1925
+ }, 1000);
1926
+ }
1927
+ node.updateObserverDebugStatus();
1928
+ };
1929
+
1930
+ node.getPresenceObservationClientState = (clientId) => {
1931
+ const normalizedClientId = normalizeString(clientId);
1932
+ if (!normalizedClientId) {
1933
+ return null;
1934
+ }
1935
+ if (!node.presenceObserverNodeState.has(normalizedClientId)) {
1936
+ node.presenceObserverNodeState.set(normalizedClientId, {
1937
+ nextRunAt: Date.now()
1938
+ });
1939
+ }
1940
+ return node.presenceObserverNodeState.get(normalizedClientId);
1941
+ };
1942
+
1943
+ node.stopPresenceObservationScheduler = () => {
1944
+ if (node.presenceObserverTimer) {
1945
+ clearInterval(node.presenceObserverTimer);
1946
+ node.presenceObserverTimer = null;
1947
+ }
1948
+ node.updateObserverDebugStatus();
1949
+ };
1950
+
1951
+ node.pollPresenceObservers = async () => {
1952
+ if (node.presenceObserverPollInProgress) {
1953
+ return;
1954
+ }
1955
+ node.presenceObserverPollInProgress = true;
1956
+
1957
+ try {
1958
+ const observedClients = node.getPresenceObservationClients();
1959
+ if (observedClients.length === 0) {
1960
+ node.stopPresenceObservationScheduler();
1961
+ return;
1962
+ }
1963
+
1964
+ const now = Date.now();
1965
+ const dueGroups = new Map();
1966
+ observedClients.forEach((entry) => {
1967
+ const clientNodeId = normalizeString(entry.client && entry.client.id);
1968
+ if (!clientNodeId) {
1969
+ return;
1970
+ }
1971
+ const state = node.getPresenceObservationClientState(clientNodeId);
1972
+ if (!state || Number(state.nextRunAt) > now) {
1973
+ return;
1974
+ }
1975
+
1976
+ state.nextRunAt = now + entry.descriptor.pollIntervalMs;
1977
+ const key = entry.descriptor.clientId;
1978
+ const group = dueGroups.get(key) || {
1979
+ clientId: entry.descriptor.clientId,
1980
+ timeout: entry.descriptor.timeout,
1981
+ entries: []
1982
+ };
1983
+ group.timeout = Math.max(group.timeout, entry.descriptor.timeout);
1984
+ group.entries.push(entry);
1985
+ dueGroups.set(key, group);
1986
+ });
1987
+
1988
+ for (const group of dueGroups.values()) {
1989
+ let snapshot;
1990
+ try {
1991
+ snapshot = await node.fetchPresenceObservationSnapshot(group.clientId, group.timeout);
1992
+ } catch (error) {
1993
+ snapshot = {
1994
+ found: false,
1995
+ connected: false,
1996
+ statusCode: 0,
1997
+ client: null,
1998
+ error: error && error.message ? error.message : String(error)
1999
+ };
2000
+ }
2001
+
2002
+ group.entries.forEach((entry) => {
2003
+ node.notifyPresenceObserverClient(entry.client, {
2004
+ source: "poll",
2005
+ clientId: group.clientId,
2006
+ ...snapshot
2007
+ });
2008
+ });
2009
+ }
2010
+ } finally {
2011
+ node.presenceObserverPollInProgress = false;
2012
+ node.updateObserverDebugStatus();
2013
+ }
2014
+ };
2015
+
2016
+ node.notifyUnofficialPollObserverClient = (client, event) => {
2017
+ if (!client || typeof client.handleUnofficialNetworkPollUpdate !== "function") {
2018
+ return;
2019
+ }
2020
+ try {
2021
+ client.handleUnofficialNetworkPollUpdate(event);
2022
+ } catch (error) {
2023
+ }
2024
+ };
2025
+
2026
+ node.getUnofficialPollObservationClients = () => {
2027
+ return node.nodeClients
2028
+ .map((client) => {
2029
+ if (!client || typeof client.getUnofficialNetworkPollDescriptor !== "function") {
2030
+ return null;
2031
+ }
2032
+ let descriptor;
2033
+ try {
2034
+ descriptor = client.getUnofficialNetworkPollDescriptor();
2035
+ } catch (error) {
2036
+ return null;
2037
+ }
2038
+ if (!descriptor || typeof descriptor !== "object") {
2039
+ return null;
2040
+ }
2041
+
2042
+ const deviceType = normalizeString(descriptor.deviceType);
2043
+ const deviceId = normalizeString(descriptor.deviceId);
2044
+ const intervalMs = Number(descriptor.intervalMs);
2045
+ if (!deviceType || !deviceId || !Number.isFinite(intervalMs) || intervalMs <= 0) {
2046
+ return null;
2047
+ }
2048
+
2049
+ return {
2050
+ client,
2051
+ descriptor: {
2052
+ deviceType,
2053
+ deviceId,
2054
+ intervalMs: Math.max(1000, Math.trunc(intervalMs))
2055
+ }
2056
+ };
2057
+ })
2058
+ .filter(Boolean);
2059
+ };
2060
+
2061
+ node.refreshUnofficialPollObservationScheduler = () => {
2062
+ const activeClientIds = new Set(
2063
+ node.getUnofficialPollObservationClients()
2064
+ .map((entry) => normalizeString(entry.client && entry.client.id))
2065
+ .filter(Boolean)
2066
+ );
2067
+
2068
+ Array.from(node.unofficialPollObserverNodeState.keys()).forEach((clientId) => {
2069
+ if (!activeClientIds.has(clientId)) {
2070
+ node.unofficialPollObserverNodeState.delete(clientId);
2071
+ }
2072
+ });
2073
+
2074
+ if (activeClientIds.size === 0 || node.isClosing) {
2075
+ node.stopUnofficialPollObservationScheduler();
2076
+ return;
2077
+ }
2078
+
2079
+ if (!node.unofficialPollObserverTimer) {
2080
+ node.unofficialPollObserverTimer = setInterval(() => {
2081
+ node.pollUnofficialObservers().catch(() => {
2082
+ });
2083
+ }, 1000);
2084
+ }
2085
+ node.updateObserverDebugStatus();
2086
+ };
2087
+
2088
+ node.getUnofficialPollObserverClientState = (clientId) => {
2089
+ const normalizedClientId = normalizeString(clientId);
2090
+ if (!normalizedClientId) {
2091
+ return null;
2092
+ }
2093
+ if (!node.unofficialPollObserverNodeState.has(normalizedClientId)) {
2094
+ node.unofficialPollObserverNodeState.set(normalizedClientId, {
2095
+ nextRunAt: Date.now()
2096
+ });
2097
+ }
2098
+ return node.unofficialPollObserverNodeState.get(normalizedClientId);
2099
+ };
2100
+
2101
+ node.stopUnofficialPollObservationScheduler = () => {
2102
+ if (node.unofficialPollObserverTimer) {
2103
+ clearInterval(node.unofficialPollObserverTimer);
2104
+ node.unofficialPollObserverTimer = null;
2105
+ }
2106
+ node.updateObserverDebugStatus();
2107
+ };
2108
+
2109
+ node.pollUnofficialObservers = async () => {
2110
+ if (node.unofficialPollObserverPollInProgress) {
2111
+ return;
2112
+ }
2113
+ node.unofficialPollObserverPollInProgress = true;
2114
+
2115
+ try {
2116
+ const observedClients = node.getUnofficialPollObservationClients();
2117
+ if (observedClients.length === 0) {
2118
+ node.stopUnofficialPollObservationScheduler();
2119
+ return;
2120
+ }
2121
+
2122
+ if (typeof node.isUnofficialNetworkWebSocketConnected === "function" && node.isUnofficialNetworkWebSocketConnected()) {
2123
+ return;
2124
+ }
2125
+
2126
+ const now = Date.now();
2127
+ const dueByDevice = new Map();
2128
+ observedClients.forEach((entry) => {
2129
+ const clientNodeId = normalizeString(entry.client && entry.client.id);
2130
+ if (!clientNodeId) {
2131
+ return;
2132
+ }
2133
+ const state = node.getUnofficialPollObserverClientState(clientNodeId);
2134
+ if (!state || Number(state.nextRunAt) > now) {
2135
+ return;
2136
+ }
2137
+
2138
+ state.nextRunAt = now + entry.descriptor.intervalMs;
2139
+ const key = `${entry.descriptor.deviceType}::${entry.descriptor.deviceId}`;
2140
+ const list = dueByDevice.get(key) || [];
2141
+ list.push(entry);
2142
+ dueByDevice.set(key, list);
2143
+ });
2144
+
2145
+ for (const entries of dueByDevice.values()) {
2146
+ if (!Array.isArray(entries) || entries.length === 0) {
2147
+ continue;
2148
+ }
2149
+ const base = entries[0].descriptor;
2150
+ let latest;
2151
+ try {
2152
+ latest = await node.fetchDeviceByTypeAndId(base.deviceType, base.deviceId);
2153
+ } catch (error) {
2154
+ continue;
2155
+ }
2156
+
2157
+ entries.forEach((entry) => {
2158
+ node.notifyUnofficialPollObserverClient(entry.client, {
2159
+ source: "poll-fallback",
2160
+ deviceType: base.deviceType,
2161
+ deviceId: base.deviceId,
2162
+ latest
2163
+ });
2164
+ });
2165
+ }
2166
+ } finally {
2167
+ node.unofficialPollObserverPollInProgress = false;
2168
+ node.updateObserverDebugStatus();
2169
+ }
2170
+ };
2171
+
2172
+ node.getObserverDebugMetrics = () => {
2173
+ const powerObservers = node.getPowerObservationClients();
2174
+ const presenceObservers = node.getPresenceObservationClients();
2175
+ const unofficialObservers = node.getUnofficialPollObservationClients();
2176
+
2177
+ const powerDeviceCount = new Set(powerObservers.map((entry) => entry.descriptor.deviceId)).size;
2178
+ const presenceTargetCount = new Set(presenceObservers.map((entry) => entry.descriptor.clientId)).size;
2179
+ const unofficialDeviceCount = new Set(
2180
+ unofficialObservers.map((entry) => `${entry.descriptor.deviceType}::${entry.descriptor.deviceId}`)
2181
+ ).size;
2182
+
2183
+ return {
2184
+ timestamp: new Date().toISOString(),
2185
+ registeredClients: node.nodeClients.length,
2186
+ observers: {
2187
+ power: {
2188
+ count: powerObservers.length,
2189
+ targets: powerDeviceCount
2190
+ },
2191
+ presence: {
2192
+ count: presenceObservers.length,
2193
+ targets: presenceTargetCount
2194
+ },
2195
+ unofficialPoll: {
2196
+ count: unofficialObservers.length,
2197
+ targets: unofficialDeviceCount
2198
+ }
2199
+ },
2200
+ schedulers: {
2201
+ power: {
2202
+ active: Boolean(node.powerObserverTimer),
2203
+ inFlight: node.powerObserverPollInProgress === true
2204
+ },
2205
+ presence: {
2206
+ active: Boolean(node.presenceObserverTimer),
2207
+ inFlight: node.presenceObserverPollInProgress === true
2208
+ },
2209
+ unofficialPoll: {
2210
+ active: Boolean(node.unofficialPollObserverTimer),
2211
+ inFlight: node.unofficialPollObserverPollInProgress === true
2212
+ }
2213
+ }
2214
+ };
2215
+ };
2216
+
2217
+ node.updateObserverDebugStatus = () => {
2218
+ if (node.isClosing) {
2219
+ return;
2220
+ }
2221
+
2222
+ const metrics = node.getObserverDebugMetrics();
2223
+ const activeObserverCount = metrics.observers.power.count
2224
+ + metrics.observers.presence.count
2225
+ + metrics.observers.unofficialPoll.count;
2226
+ const hasActiveScheduler = metrics.schedulers.power.active
2227
+ || metrics.schedulers.presence.active
2228
+ || metrics.schedulers.unofficialPoll.active;
2229
+
2230
+ let fill = "grey";
2231
+ let shape = "ring";
2232
+ let text = "ready";
2233
+ if (activeObserverCount > 0 || hasActiveScheduler) {
2234
+ fill = "blue";
2235
+ shape = "ring";
2236
+ text = `obs p:${metrics.observers.power.count}/${metrics.observers.power.targets} pr:${metrics.observers.presence.count}/${metrics.observers.presence.targets} u:${metrics.observers.unofficialPoll.count}/${metrics.observers.unofficialPoll.targets}`;
2237
+ }
2238
+
2239
+ const nextKey = `${fill}|${shape}|${text}`;
2240
+ if (node.lastObserverDebugStatusKey === nextKey) {
2241
+ return;
2242
+ }
2243
+ node.lastObserverDebugStatusKey = nextKey;
2244
+ setNodeStatus({ fill, shape, text });
2245
+ };
2246
+
1433
2247
  node.resolveClientAttachment = async (clientId) => {
1434
2248
  const normalizedClientId = normalizeString(clientId);
1435
2249
  if (!normalizedClientId) {
@@ -1747,19 +2561,39 @@ module.exports = function(RED) {
1747
2561
  } catch (error) {
1748
2562
  node.warn(`Unable to initialize Network websocket: ${error && error.message ? error.message : error}`);
1749
2563
  }
2564
+ node.refreshPowerObservationScheduler();
2565
+ node.refreshPresenceObservationScheduler();
2566
+ node.refreshUnofficialPollObservationScheduler();
1750
2567
  };
1751
2568
 
1752
2569
  node.removeClient = (client) => {
1753
2570
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
2571
+ const clientId = normalizeString(client && client.id);
2572
+ if (clientId) {
2573
+ node.powerObserverNodeState.delete(clientId);
2574
+ node.presenceObserverNodeState.delete(clientId);
2575
+ node.unofficialPollObserverNodeState.delete(clientId);
2576
+ }
1754
2577
  if (!node.hasUnofficialNetworkStreamSubscribers()) {
1755
2578
  node.closeUnofficialNetworkWebSocket();
1756
2579
  }
2580
+ node.refreshPowerObservationScheduler();
2581
+ node.refreshPresenceObservationScheduler();
2582
+ node.refreshUnofficialPollObservationScheduler();
1757
2583
  };
1758
2584
 
2585
+ node.updateObserverDebugStatus();
2586
+
1759
2587
  node.on("close", function(done) {
1760
2588
  try {
1761
2589
  node.isClosing = true;
1762
2590
  node.nodeClients = [];
2591
+ node.powerObserverNodeState.clear();
2592
+ node.stopPowerObservationScheduler();
2593
+ node.presenceObserverNodeState.clear();
2594
+ node.stopPresenceObservationScheduler();
2595
+ node.unofficialPollObserverNodeState.clear();
2596
+ node.stopUnofficialPollObservationScheduler();
1763
2597
  node.closeUnofficialNetworkWebSocket();
1764
2598
  } catch (error) {
1765
2599
  } finally {
@@ -1956,4 +2790,24 @@ module.exports = function(RED) {
1956
2790
  }
1957
2791
  });
1958
2792
 
2793
+ RED.httpAdmin.get("/unifiNetwork/observer-metrics", RED.auth.needsPermission("unifi-network-config.read"), async (req, res) => {
2794
+ try {
2795
+ const serverId = String(req.query.serverId || "").trim();
2796
+ if (!serverId) {
2797
+ res.status(400).json({ error: "Missing serverId" });
2798
+ return;
2799
+ }
2800
+
2801
+ const server = RED.nodes.getNode(serverId);
2802
+ if (!server || typeof server.getObserverDebugMetrics !== "function") {
2803
+ res.status(404).json({ error: "Configuration node not found" });
2804
+ return;
2805
+ }
2806
+
2807
+ res.json(server.getObserverDebugMetrics());
2808
+ } catch (error) {
2809
+ res.status(500).json({ error: error.message });
2810
+ }
2811
+ });
2812
+
1959
2813
  };