node-red-contrib-unifi-ultimate 1.0.9 → 1.1.0

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.
package/README.md CHANGED
@@ -85,6 +85,7 @@ Things you can do:
85
85
  - Switch PoE on/off or power-cycle it, and **enable/disable the whole switch port** (the UniFi _Port State_ toggle), driven by the editor or by `msg.payload`.
86
86
  - Let **Clients Control** automatically find which switch port a client is connected to.
87
87
  - Restart a whole list of switches/APs at once, or power-cycle all their active PoE ports, with the **Restart** node.
88
+ - Get notified when any client **joins or leaves a specific network** (for example your **Guest** network), including the device name — set the **Presence Detection** node's **Watch by** to **Network (join/leave)**.
88
89
 
89
90
  <br/>
90
91
  <br/>
@@ -1,5 +1,8 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
3
6
  const {
4
7
  buildBaseUrlFromHost,
5
8
  normalizePort,
@@ -12,6 +15,7 @@ const {
12
15
  normalizeNetworkCollection
13
16
  } = require("./utils/unifi-network-utils");
14
17
  const {
18
+ decodeScopedDeviceId,
15
19
  encodeScopedDeviceId,
16
20
  getCapabilitiesForType,
17
21
  getCapabilityOptions,
@@ -26,6 +30,28 @@ module.exports = function(RED) {
26
30
  const MIN_POWER_OBSERVER_INTERVAL_SECONDS = 5;
27
31
  const DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS = 15;
28
32
  const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
33
+ const PORT_OVERRIDE_CACHE_VERSION = 1;
34
+ const PORT_OVERRIDE_CACHE_SAVE_DEBOUNCE_MS = 1000;
35
+ // Sentinel stored for a port that was enabled but had no override at all, so
36
+ // re-enabling knows to remove the override we added (instead of restoring one).
37
+ const PORT_OVERRIDE_NONE = { __noOverride: true };
38
+
39
+ function portOverrideCacheKey(deviceMac, portIdx) {
40
+ const mac = String(deviceMac || "").trim().toLowerCase();
41
+ const idx = Number(portIdx);
42
+ if (!mac || !Number.isFinite(idx)) {
43
+ return "";
44
+ }
45
+ return `${mac}|${Math.trunc(idx)}`;
46
+ }
47
+
48
+ function resolvePortOverrideCacheFile(nodeId) {
49
+ const dir = (RED.settings && RED.settings.userDir)
50
+ ? RED.settings.userDir
51
+ : os.tmpdir();
52
+ const safeId = String(nodeId || "shared").replace(/[^a-z0-9._-]/gi, "_");
53
+ return path.join(dir, `unifi-ultimate-portcache-${safeId}.json`);
54
+ }
29
55
 
30
56
  function normalizePowerObserverIntervalSeconds(value) {
31
57
  const parsed = Number(value);
@@ -97,6 +123,159 @@ module.exports = function(RED) {
97
123
  node.unofficialPollObserverTimer = null;
98
124
  node.unofficialPollObserverPollInProgress = false;
99
125
 
126
+ // Persistent mirror of each switch port's "last known enabled" override.
127
+ // Disabling a port destroys its VLAN/native-network config on the
128
+ // controller, so we cannot read it back to re-enable the port correctly.
129
+ // Instead we snapshot every port's override while it is still enabled —
130
+ // seeded at startup, refreshed on every device read, and persisted to disk
131
+ // so it survives Node-RED restarts. Keyed by `${mac}|${portIdx}`; the value
132
+ // is either the override object or PORT_OVERRIDE_NONE (enabled, no override).
133
+ node.portOverrideCache = new Map();
134
+ node.portOverrideCacheFile = resolvePortOverrideCacheFile(node.id);
135
+ node.portOverrideCacheSaveTimer = null;
136
+
137
+ function loadPortOverrideCache() {
138
+ try {
139
+ const raw = fs.readFileSync(node.portOverrideCacheFile, "utf8");
140
+ const data = JSON.parse(raw);
141
+ const entries = data && typeof data === "object" ? data.entries : null;
142
+ if (entries && typeof entries === "object") {
143
+ Object.keys(entries).forEach((key) => {
144
+ node.portOverrideCache.set(key, entries[key]);
145
+ });
146
+ }
147
+ } catch (error) {
148
+ // No cache file yet (or unreadable) — start empty.
149
+ }
150
+ }
151
+
152
+ function schedulePortOverrideCacheSave() {
153
+ if (node.portOverrideCacheSaveTimer || node.isClosing) {
154
+ return;
155
+ }
156
+ node.portOverrideCacheSaveTimer = setTimeout(() => {
157
+ node.portOverrideCacheSaveTimer = null;
158
+ try {
159
+ const entries = {};
160
+ node.portOverrideCache.forEach((value, key) => {
161
+ entries[key] = value;
162
+ });
163
+ fs.writeFileSync(
164
+ node.portOverrideCacheFile,
165
+ JSON.stringify({ version: PORT_OVERRIDE_CACHE_VERSION, entries }),
166
+ "utf8"
167
+ );
168
+ } catch (error) {
169
+ // Persistence is best-effort; the in-memory cache still works.
170
+ }
171
+ }, PORT_OVERRIDE_CACHE_SAVE_DEBOUNCE_MS);
172
+ if (typeof node.portOverrideCacheSaveTimer.unref === "function") {
173
+ node.portOverrideCacheSaveTimer.unref();
174
+ }
175
+ }
176
+
177
+ // Store the last known ENABLED override for a port. `override` is the raw
178
+ // override object, or null when the enabled port had no override at all.
179
+ node.rememberEnabledPortOverride = (deviceMac, portIdx, override) => {
180
+ const key = portOverrideCacheKey(deviceMac, portIdx);
181
+ if (!key) {
182
+ return;
183
+ }
184
+ const value = override
185
+ ? JSON.parse(JSON.stringify(override))
186
+ : { ...PORT_OVERRIDE_NONE };
187
+ node.portOverrideCache.set(key, value);
188
+ schedulePortOverrideCacheSave();
189
+ };
190
+
191
+ // Refresh the cache from a freshly fetched legacy device. Only ports that
192
+ // are currently enabled update the cache; a disabled port keeps whatever
193
+ // enabled snapshot we already have, so its VLAN can be restored later.
194
+ node.ingestPortOverridesFromDevice = (device) => {
195
+ if (!device || typeof device !== "object") {
196
+ return;
197
+ }
198
+ const mac = normalizeString(device.mac);
199
+ if (!mac) {
200
+ return;
201
+ }
202
+ const overridesByIdx = new Map();
203
+ (Array.isArray(device.port_overrides) ? device.port_overrides : []).forEach((override) => {
204
+ const idx = Number(override && override.port_idx);
205
+ if (Number.isFinite(idx)) {
206
+ overridesByIdx.set(Math.trunc(idx), override);
207
+ }
208
+ });
209
+ const indices = new Set();
210
+ (Array.isArray(device.port_table) ? device.port_table : []).forEach((port) => {
211
+ const idx = Number(port && port.port_idx);
212
+ if (Number.isFinite(idx)) {
213
+ indices.add(Math.trunc(idx));
214
+ }
215
+ });
216
+ overridesByIdx.forEach((_override, idx) => indices.add(idx));
217
+ indices.forEach((idx) => {
218
+ const override = overridesByIdx.get(idx) || null;
219
+ const forward = override ? normalizeString(override.forward) : "";
220
+ if (forward === "disabled") {
221
+ // Keep the last known enabled snapshot instead of overwriting it.
222
+ return;
223
+ }
224
+ node.rememberEnabledPortOverride(mac, idx, override);
225
+ });
226
+ };
227
+
228
+ // Return the remembered enabled override for a port (a deep clone so callers
229
+ // cannot mutate the cache), PORT_OVERRIDE_NONE when the enabled port had no
230
+ // override, or null when the port is unknown.
231
+ node.getEnabledPortOverride = (deviceMac, portIdx) => {
232
+ const key = portOverrideCacheKey(deviceMac, portIdx);
233
+ if (!key) {
234
+ return null;
235
+ }
236
+ const value = node.portOverrideCache.get(key);
237
+ if (!value) {
238
+ return null;
239
+ }
240
+ if (value.__noOverride) {
241
+ return { ...PORT_OVERRIDE_NONE };
242
+ }
243
+ return JSON.parse(JSON.stringify(value));
244
+ };
245
+
246
+ // Best-effort startup seed: read every site's devices once so the cache is
247
+ // populated with the current enabled configuration before any disable.
248
+ node.seedPortOverrideCache = async () => {
249
+ if (!String(node.getApiKey() || "").trim()) {
250
+ return;
251
+ }
252
+ let sites;
253
+ try {
254
+ sites = await node.fetchSites();
255
+ } catch (error) {
256
+ return;
257
+ }
258
+ for (const site of (Array.isArray(sites) ? sites : [])) {
259
+ if (node.isClosing) {
260
+ return;
261
+ }
262
+ const siteId = String(site && site.id || "").trim();
263
+ if (!siteId) {
264
+ continue;
265
+ }
266
+ try {
267
+ const devices = await fetchLegacyDevices(siteId);
268
+ (Array.isArray(devices) ? devices : []).forEach((device) => {
269
+ node.ingestPortOverridesFromDevice(device);
270
+ });
271
+ } catch (error) {
272
+ // Skip sites we cannot read; the cache still warms up on demand.
273
+ }
274
+ }
275
+ };
276
+
277
+ loadPortOverrideCache();
278
+
100
279
  function setNodeStatus(status) {
101
280
  if (!status || typeof status !== "object" || Array.isArray(status)) {
102
281
  return;
@@ -1342,10 +1521,18 @@ module.exports = function(RED) {
1342
1521
 
1343
1522
  async function fetchLegacyDevices(siteId) {
1344
1523
  const devices = await fetchLegacySiteCollection(siteId, "/stat/device");
1345
- return devices.map((device) => ({
1524
+ const mapped = devices.map((device) => ({
1346
1525
  ...device,
1347
1526
  siteId
1348
1527
  }));
1528
+ // Every device read is an opportunity to keep the port-override cache
1529
+ // aligned with the controller, so enable/disable can restore VLANs.
1530
+ try {
1531
+ mapped.forEach((device) => node.ingestPortOverridesFromDevice(device));
1532
+ } catch (error) {
1533
+ // Cache maintenance must never break the actual device fetch.
1534
+ }
1535
+ return mapped;
1349
1536
  }
1350
1537
 
1351
1538
  function buildLegacyClientSummary(client, siteId) {
@@ -2912,6 +3099,119 @@ module.exports = function(RED) {
2912
3099
  return attachedClients;
2913
3100
  };
2914
3101
 
3102
+ node.fetchNetworks = async () => {
3103
+ // List the L3 networks/VLANs configured on the controller so the
3104
+ // editor can offer them as watch targets. Uses the legacy
3105
+ // networkconf collection because it includes empty networks too.
3106
+ const sites = await node.fetchSites();
3107
+ const results = await Promise.all(sites.map(async (site) => {
3108
+ const siteId = normalizeString(site && site.id);
3109
+ if (!siteId) {
3110
+ return [];
3111
+ }
3112
+ const siteName = normalizeString(site.name || site.displayName || siteId);
3113
+ let networks = [];
3114
+ try {
3115
+ networks = await fetchLegacySiteCollection(siteId, "/rest/networkconf");
3116
+ } catch (error) {
3117
+ networks = [];
3118
+ }
3119
+
3120
+ return networks
3121
+ .filter((entry) => entry && typeof entry === "object" && !Array.isArray(entry))
3122
+ .map((entry) => {
3123
+ const networkId = normalizeString(entry._id || entry.id);
3124
+ const purpose = normalizeString(entry.purpose);
3125
+ return {
3126
+ id: encodeScopedDeviceId(siteId, networkId) || networkId,
3127
+ networkId,
3128
+ name: normalizeString(entry.name || networkId || "Network"),
3129
+ purpose,
3130
+ isGuest: purpose === "guest",
3131
+ vlan: entry.vlan_enabled ? Number(entry.vlan) : undefined,
3132
+ enabled: entry.enabled !== false,
3133
+ siteId,
3134
+ siteName
3135
+ };
3136
+ })
3137
+ .filter((entry) => entry.networkId);
3138
+ }));
3139
+
3140
+ const dedup = new Map();
3141
+ results.flat().forEach((entry) => {
3142
+ if (!dedup.has(entry.id)) {
3143
+ dedup.set(entry.id, entry);
3144
+ }
3145
+ });
3146
+
3147
+ return Array.from(dedup.values()).sort((a, b) => {
3148
+ return String(a.name).localeCompare(String(b.name));
3149
+ });
3150
+ };
3151
+
3152
+ node.fetchActiveClientsOnNetwork = async (scopedNetworkId, knownNetworkName) => {
3153
+ // Return the currently connected clients that belong to the given
3154
+ // network. Matching is done on the network id, with the network
3155
+ // name as a fallback when the controller omits the id.
3156
+ const scoped = decodeScopedDeviceId(scopedNetworkId);
3157
+ const siteId = normalizeString(scoped.siteId);
3158
+ const wantedNetworkId = normalizeString(scoped.resourceId);
3159
+ if (!siteId || !wantedNetworkId) {
3160
+ throw new Error("Network selection is invalid. Re-select the network from the editor.");
3161
+ }
3162
+
3163
+ // Resolve the watched network name (used by the name-based fallback
3164
+ // on controllers that omit the network id on stations). The caller
3165
+ // can pass it to skip this per-poll lookup.
3166
+ let wantedNetworkName = normalizeString(knownNetworkName);
3167
+ if (!wantedNetworkName) {
3168
+ try {
3169
+ const networks = await fetchLegacySiteCollection(siteId, "/rest/networkconf");
3170
+ const matched = networks.find((entry) => normalizeString(entry && (entry._id || entry.id)) === wantedNetworkId);
3171
+ wantedNetworkName = normalizeString(matched && matched.name);
3172
+ } catch (error) {
3173
+ wantedNetworkName = "";
3174
+ }
3175
+ }
3176
+
3177
+ const stations = await fetchLegacySiteCollection(siteId, "/stat/sta");
3178
+ const normalizedWantedName = wantedNetworkName.toLowerCase();
3179
+
3180
+ return stations
3181
+ .filter((station) => station && typeof station === "object" && !Array.isArray(station))
3182
+ .filter((station) => {
3183
+ const stationNetworkId = normalizeString(station.network_id || station.networkId);
3184
+ if (stationNetworkId) {
3185
+ return stationNetworkId === wantedNetworkId;
3186
+ }
3187
+ const stationNetworkName = normalizeString(station.network).toLowerCase();
3188
+ return normalizedWantedName !== "" && stationNetworkName === normalizedWantedName;
3189
+ })
3190
+ .map((station) => {
3191
+ const mac = normalizeString(station.mac || station.macAddress);
3192
+ const name = stripOfflineTag(firstNonEmptyString([
3193
+ station.name,
3194
+ station.hostname,
3195
+ station.display_name,
3196
+ mac
3197
+ ]));
3198
+ return {
3199
+ mac,
3200
+ clientId: normalizeString(station.user_id || station._id || mac),
3201
+ name: name || mac || "Client",
3202
+ network: normalizeString(station.network) || wantedNetworkName,
3203
+ networkId: normalizeString(station.network_id || station.networkId) || wantedNetworkId,
3204
+ networkName: wantedNetworkName || normalizeString(station.network),
3205
+ essid: normalizeString(station.essid),
3206
+ isGuest: station.is_guest === true,
3207
+ isWired: station.is_wired === true,
3208
+ ipAddress: firstNonEmptyString([station.ip, station.last_ip, station.fixed_ip]),
3209
+ siteId
3210
+ };
3211
+ })
3212
+ .filter((client) => client.mac);
3213
+ };
3214
+
2915
3215
  node.addClient = (client) => {
2916
3216
  if (!client) {
2917
3217
  return;
@@ -2948,9 +3248,22 @@ module.exports = function(RED) {
2948
3248
 
2949
3249
  node.updateObserverDebugStatus();
2950
3250
 
3251
+ // Warm the port-override cache in the background so a first-ever disable
3252
+ // already has the port's enabled configuration recorded. Best-effort.
3253
+ setTimeout(() => {
3254
+ if (node.isClosing) {
3255
+ return;
3256
+ }
3257
+ node.seedPortOverrideCache().catch(() => {});
3258
+ }, 0);
3259
+
2951
3260
  node.on("close", function(done) {
2952
3261
  try {
2953
3262
  node.isClosing = true;
3263
+ if (node.portOverrideCacheSaveTimer) {
3264
+ clearTimeout(node.portOverrideCacheSaveTimer);
3265
+ node.portOverrideCacheSaveTimer = null;
3266
+ }
2954
3267
  node.nodeClients = [];
2955
3268
  node.powerObserverNodeState.clear();
2956
3269
  node.stopPowerObservationScheduler();
@@ -3154,6 +3467,26 @@ module.exports = function(RED) {
3154
3467
  }
3155
3468
  });
3156
3469
 
3470
+ RED.httpAdmin.get("/unifiNetwork/networks", RED.auth.needsPermission("unifi-network-config.read"), async (req, res) => {
3471
+ try {
3472
+ const serverId = String(req.query.serverId || "").trim();
3473
+ if (!serverId) {
3474
+ res.status(400).json({ error: "Missing serverId" });
3475
+ return;
3476
+ }
3477
+
3478
+ const server = RED.nodes.getNode(serverId);
3479
+ if (!server || typeof server.fetchNetworks !== "function") {
3480
+ res.status(404).json({ error: "Configuration node not found" });
3481
+ return;
3482
+ }
3483
+
3484
+ res.json(await server.fetchNetworks());
3485
+ } catch (error) {
3486
+ res.status(500).json({ error: error.message });
3487
+ }
3488
+ });
3489
+
3157
3490
  RED.httpAdmin.get("/unifiNetwork/observer-metrics", RED.auth.needsPermission("unifi-network-config.read"), async (req, res) => {
3158
3491
  try {
3159
3492
  const serverId = String(req.query.serverId || "").trim();
@@ -1358,7 +1358,7 @@
1358
1358
  <p><b>Control</b> chooses what is controlled on each target port:</p>
1359
1359
  <ul>
1360
1360
  <li><code>PoE</code> — controls Power-over-Ethernet on the port (the attached device keeps its link but loses/gains power).</li>
1361
- <li><code>Enable/Disable port</code> — administratively enables or disables the whole switch port, exactly like the UniFi <em>Port State</em> toggle. Disabling cuts <em>all</em> traffic and PoE on that port, disconnecting whatever is attached. Implemented through the UniFi port override <code>forward</code> field (verified against the controller): Disable sets <code>forward=disabled</code> and preserves the rest of the port config. Enable acts only on a disabled port (an already-enabled port is left untouched): it sets <code>forward=all</code> and, if the port had been disabled from the UniFi UI (which also blocks VLANs and clears the native network), it restores <code>tagged_vlan_mgmt=auto</code>, <code>port_security_enabled=false</code> and the site default native network.</li>
1361
+ <li><code>Enable/Disable port</code> — administratively enables or disables the whole switch port, exactly like the UniFi <em>Port State</em> toggle. Disabling cuts <em>all</em> traffic and PoE on that port, disconnecting whatever is attached. Implemented through the UniFi port override <code>forward</code> field (verified against the controller): Disable sets <code>forward=disabled</code> and preserves the rest of the port config. Enable acts only on a disabled port (an already-enabled port is left untouched): it re-enables a disabled port and restores its full configuration. The config node keeps a persistent cache of each port's last known <em>enabled</em> override (seeded at startup, refreshed on every device read and saved to disk so it survives restarts), and enable restores that whole snapshot — so the VLAN and every other property come back exactly as they were. If the port has never been seen enabled it falls back to a best-effort revert: <code>forward=all</code>, <code>tagged_vlan_mgmt=auto</code>, <code>port_security_enabled=false</code> and the site default native network.</li>
1362
1362
  </ul>
1363
1363
  <p><b>Action</b> is applied to <em>every</em> target in the list, and its choices depend on <b>Control</b>:</p>
1364
1364
  <ul>
@@ -538,23 +538,46 @@ module.exports = function(RED) {
538
538
  const portOverrides = sourceOverrides.map((port) => ({ ...port }));
539
539
  const existing = portOverrides.find((port) => Number(port && port.port_idx) === portIdx);
540
540
 
541
+ const sourcePort = Array.isArray(device && device.port_table)
542
+ ? device.port_table.find((port) => Number(port && port.port_idx) === portIdx)
543
+ : null;
544
+
541
545
  // `patch` may be a function so callers can decide the change based on
542
546
  // the current override (e.g. only re-enable a port that is actually
543
- // disabled, without clobbering its VLAN/forward configuration).
544
- const resolvedPatch = typeof patch === "function" ? patch(existing || null) : patch;
547
+ // disabled, without clobbering its VLAN/forward configuration). The
548
+ // live port_table entry and the whole device are passed too so callers
549
+ // can read state the override does not carry (e.g. the device MAC used
550
+ // to look up the remembered pre-disable override).
551
+ const resolvedPatch = typeof patch === "function" ? patch(existing || null, sourcePort || null, device) : patch;
545
552
  if (!resolvedPatch || Object.keys(resolvedPatch).length === 0) {
546
553
  return portOverrides;
547
554
  }
548
555
 
556
+ // Wholesale restore: replace the entire override for this port with the
557
+ // provided snapshot (used to bring a port back to its exact pre-disable
558
+ // config). Falls back to a plain push when there was no override yet.
559
+ if (resolvedPatch.__replaceOverride) {
560
+ const replacement = { ...resolvedPatch.__replaceOverride, port_idx: portIdx };
561
+ if (existing) {
562
+ portOverrides[portOverrides.indexOf(existing)] = replacement;
563
+ } else {
564
+ portOverrides.push(replacement);
565
+ }
566
+ return portOverrides;
567
+ }
568
+
569
+ // Wholesale removal: drop the override entirely so the port reverts to
570
+ // its port-profile / device defaults (used when the port had no
571
+ // override before this node disabled it).
572
+ if (resolvedPatch.__removeOverride) {
573
+ return portOverrides.filter((port) => Number(port && port.port_idx) !== portIdx);
574
+ }
575
+
549
576
  if (existing) {
550
577
  Object.assign(existing, resolvedPatch);
551
578
  return portOverrides;
552
579
  }
553
580
 
554
- const sourcePort = Array.isArray(device && device.port_table)
555
- ? device.port_table.find((port) => Number(port && port.port_idx) === portIdx)
556
- : null;
557
-
558
581
  portOverrides.push({
559
582
  port_idx: portIdx,
560
583
  portconf_id: sourcePort && sourcePort.portconf_id,
@@ -586,6 +609,18 @@ module.exports = function(RED) {
586
609
  throw new Error("Unable to resolve UniFi legacy device id.");
587
610
  }
588
611
 
612
+ // Feed the just-fetched (still authoritative) device into the config
613
+ // node's port-override cache before we change anything. This keeps the
614
+ // "last known enabled" snapshot fresh so a later re-enable can restore
615
+ // the exact pre-disable configuration.
616
+ if (typeof node.server.ingestPortOverridesFromDevice === "function") {
617
+ try {
618
+ node.server.ingestPortOverridesFromDevice(legacyDevice);
619
+ } catch (error) {
620
+ // Cache maintenance is best-effort; never block the actual action.
621
+ }
622
+ }
623
+
589
624
  const path = `/api/s/${encodeURIComponent(legacySiteName)}/rest/device/${encodeURIComponent(legacyDevice._id)}`;
590
625
  const portOverrides = buildPortOverrides(legacyDevice, portIdx, patch);
591
626
  setNodeStatus({ fill: "blue", shape: "dot", text: statusText });
@@ -668,7 +703,10 @@ module.exports = function(RED) {
668
703
  // (verified against the controller). forward=disabled alone can be
669
704
  // rejected/ineffective while the native network and VLANs are still
670
705
  // set, so apply the full bundle: block VLANs, clear the native
671
- // network and turn on port security.
706
+ // network and turn on port security. The port's pre-disable config
707
+ // has already been captured into the config-node cache by
708
+ // applyLegacyPortOverridePatch (before this patch runs), so enabling
709
+ // can restore it later.
672
710
  patch = {
673
711
  forward: "disabled",
674
712
  tagged_vlan_mgmt: "block_all",
@@ -677,14 +715,36 @@ module.exports = function(RED) {
677
715
  };
678
716
  } else {
679
717
  // Enable only acts on a disabled port (never clobbers an enabled
680
- // one). Besides forward=all, undo the extra hardening the UI adds
681
- // when it disables a port (VLAN block + port security) and restore
682
- // the native network to the site default when it was cleared.
718
+ // one). If the config node remembers the port's last known enabled
719
+ // override, restore it wholesale so every property (VLAN and
720
+ // anything else, now or in the future) comes back exactly as it was.
721
+ // Otherwise fall back to a best-effort revert (used when we have no
722
+ // record of the port at all): undo the UI hardening and restore the
723
+ // site default native network.
683
724
  const defaultNativeId = await fetchDefaultNativeNetworkId(scoped);
684
- patch = (existing) => {
725
+ const lookupRemembered = (device) => {
726
+ if (!device || typeof node.server.getEnabledPortOverride !== "function") {
727
+ return null;
728
+ }
729
+ try {
730
+ return node.server.getEnabledPortOverride(device.mac, portIdx);
731
+ } catch (error) {
732
+ return null;
733
+ }
734
+ };
735
+ patch = (existing, _sourcePort, device) => {
685
736
  if (!existing || String(existing.forward) !== "disabled") {
686
737
  return {};
687
738
  }
739
+ const remembered = lookupRemembered(device);
740
+ if (remembered && remembered.__noOverride) {
741
+ // The port had no override while enabled — remove the one we
742
+ // added on disable so it reverts to its profile/defaults.
743
+ return { __removeOverride: true };
744
+ }
745
+ if (remembered) {
746
+ return { __replaceOverride: remembered };
747
+ }
688
748
  const recover = {
689
749
  forward: "all",
690
750
  tagged_vlan_mgmt: "auto",
@@ -3,37 +3,99 @@
3
3
 
4
4
 
5
5
  <script type="text/javascript">
6
+ // Resolve the active "Watch by" mode for validators: prefer the live editor
7
+ // value, fall back to the saved node value.
8
+ function currentWatchByValue(self) {
9
+ try {
10
+ const live = $("#node-input-watchBy").val();
11
+ if (live) {
12
+ return String(live).trim();
13
+ }
14
+ } catch (error) {
15
+ // jQuery/DOM not available in this context.
16
+ }
17
+ return (self && self.watchBy) ? String(self.watchBy).trim() : "presence";
18
+ }
19
+
6
20
  RED.nodes.registerType("unifi-network-presence", {
7
21
  category: "Unifi Ultimate",
8
22
  color: "#CFE8FB",
9
23
  defaults: {
10
24
  name: { value: "" },
11
25
  server: { value: "", type: "unifi-network-config", required: true },
12
- clientId: { value: "", required: true },
26
+ watchBy: { value: "presence", required: true },
27
+ clientId: {
28
+ value: "",
29
+ validate: function (v) {
30
+ const mode = currentWatchByValue(this);
31
+ return mode === "network" ? true : String(v || "").trim() !== "";
32
+ }
33
+ },
13
34
  deviceName: { value: "" },
14
35
  pollInterval: { value: 10, required: true, validate: RED.validators.number() },
15
36
  onlineHysteresis: { value: 15, required: true, validate: RED.validators.number() },
16
37
  offlineHysteresis: { value: 30, required: true, validate: RED.validators.number() },
17
- repeatInterval: { value: 0, required: false, validate: RED.validators.number() }
38
+ repeatInterval: { value: 0, required: false, validate: RED.validators.number() },
39
+ networkId: {
40
+ value: "",
41
+ validate: function (v) {
42
+ const mode = currentWatchByValue(this);
43
+ return mode === "network" ? String(v || "").trim() !== "" : true;
44
+ }
45
+ },
46
+ networkName: { value: "" },
47
+ emitInitial: { value: false },
48
+ joinConfirmPolls: { value: 1, validate: RED.validators.number() },
49
+ leaveConfirmPolls: { value: 3, validate: RED.validators.number() }
18
50
  },
19
51
  inputs: 0,
20
52
  outputs: 2,
21
53
  icon: "unifi-u-logo-light-network.svg",
22
54
  paletteLabel: "Presence Detection",
23
- outputLabels: ["presence", "error"],
55
+ outputLabels: ["result", "error"],
24
56
  label: function () {
25
- return this.name || "Presence Detection";
57
+ if (this.name) {
58
+ return this.name;
59
+ }
60
+ if (this.watchBy === "network" && this.networkName) {
61
+ return this.networkName;
62
+ }
63
+ return "Presence Detection";
64
+ },
65
+ oneditsave: function () {
66
+ const mode = String($("#node-input-watchBy").val() || "presence").trim();
67
+ // Only the network mode accepts an input trigger.
68
+ this.inputs = mode === "network" ? 1 : 0;
69
+ if (mode === "network") {
70
+ const $selected = $("#node-input-networkId option:selected");
71
+ this.networkName = String($selected.attr("data-network-name") || "").trim();
72
+ $("#node-input-networkName").val(this.networkName);
73
+ }
26
74
  },
27
75
  oneditprepare: function () {
28
76
  const node = this;
29
77
  const $name = $("#node-input-name");
30
78
  const $server = $("#node-input-server");
79
+ const $watchBy = $("#node-input-watchBy");
31
80
  const $clientId = $("#node-input-clientId");
32
81
  const $deviceName = $("#node-input-deviceName");
33
82
  const $refresh = $("#node-input-refreshClients");
34
83
  const $clientRow = $clientId.closest(".form-row");
35
84
  const $advancedRow = $("#node-row-advanced");
85
+ // Network-mode controls.
86
+ const $networkId = $("#node-input-networkId");
87
+ const $refreshNetworks = $("#node-input-refreshNetworks");
88
+ const $watchByRow = $("#node-row-watchBy");
89
+ const $networkRow = $("#node-row-networkId");
90
+ const $networkStatus = $("#unifi-presence-network-status");
36
91
  let suspendChangeHandling = false;
92
+ let loadedNetworksServerId = "";
93
+
94
+ $watchBy.val(this.watchBy || "presence");
95
+
96
+ function currentMode() {
97
+ return String($watchBy.val() || "presence").trim();
98
+ }
37
99
 
38
100
  function hasSelection($field) {
39
101
  const value = String($field.val() || "").trim();
@@ -42,10 +104,71 @@
42
104
 
43
105
  function syncProgressiveRows() {
44
106
  const hasServer = hasSelection($server);
45
- const hasClient = hasSelection($clientId);
107
+ const isNetwork = currentMode() === "network";
108
+ const hasTarget = isNetwork ? hasSelection($networkId) : hasSelection($clientId);
109
+
110
+ $watchByRow.toggle(hasServer);
111
+ $clientRow.toggle(hasServer && !isNetwork);
112
+ $networkRow.toggle(hasServer && isNetwork);
113
+ $advancedRow.toggle(hasServer && hasTarget);
114
+ // Tuning rows depend on the active mode.
115
+ $("#node-presence-tuning").toggle(!isNetwork);
116
+ $("#node-network-tuning").toggle(isNetwork);
117
+ }
118
+
119
+ function renderNetworks(items) {
120
+ const currentValue = String($networkId.val() || node.networkId || "").trim();
121
+ suspendChangeHandling = true;
122
+ try {
123
+ $networkId.empty();
124
+ $networkId.append($("<option></option>").val("").text("Choose a network"));
125
+ (items || []).forEach(function (item) {
126
+ const id = String(item.id || "").trim();
127
+ if (!id) {
128
+ return;
129
+ }
130
+ const name = String(item.name || id).trim();
131
+ const tags = [];
132
+ if (item.isGuest) { tags.push("guest"); }
133
+ if (item.vlan) { tags.push("VLAN " + item.vlan); }
134
+ if (item.enabled === false) { tags.push("disabled"); }
135
+ const suffix = tags.length > 0 ? " [" + tags.join(", ") + "]" : "";
136
+ $networkId.append(
137
+ $("<option></option>").val(id).text(name + suffix).attr("data-network-name", name)
138
+ );
139
+ });
140
+ $networkId.val(currentValue && $networkId.find("option[value='" + currentValue + "']").length > 0 ? currentValue : "");
141
+ } finally {
142
+ suspendChangeHandling = false;
143
+ }
144
+ syncProgressiveRows();
145
+ }
46
146
 
47
- $clientRow.toggle(hasServer);
48
- $advancedRow.toggle(hasServer && hasClient);
147
+ function loadNetworks(force) {
148
+ const serverId = String($server.val() || "").trim();
149
+ if (!serverId || serverId === "_ADD_") {
150
+ renderNetworks([]);
151
+ $networkStatus.text("");
152
+ return Promise.resolve();
153
+ }
154
+ if (!force && serverId === loadedNetworksServerId) {
155
+ return Promise.resolve();
156
+ }
157
+ $networkStatus.text("Loading networks...");
158
+ $refreshNetworks.find("i").addClass("fa-spin");
159
+ loadedNetworksServerId = serverId;
160
+ return requestJson("unifiNetwork/networks?serverId=" + encodeURIComponent(serverId))
161
+ .then(function (networks) {
162
+ renderNetworks(Array.isArray(networks) ? networks : []);
163
+ $networkStatus.text("");
164
+ })
165
+ .catch(function (xhr) {
166
+ renderNetworks([]);
167
+ $networkStatus.text(xhr && xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : "Unable to load networks.");
168
+ })
169
+ .then(function () {
170
+ $refreshNetworks.find("i").removeClass("fa-spin");
171
+ });
49
172
  }
50
173
 
51
174
  function requestJson(url) {
@@ -446,7 +569,11 @@
446
569
  if (suspendChangeHandling) {
447
570
  return;
448
571
  }
449
- loadClients();
572
+ if (currentMode() === "network") {
573
+ loadNetworks(false);
574
+ } else {
575
+ loadClients();
576
+ }
450
577
  });
451
578
 
452
579
  $clientId.on("change", function () {
@@ -467,11 +594,37 @@
467
594
  loadClients();
468
595
  });
469
596
 
597
+ $watchBy.on("change", function () {
598
+ syncProgressiveRows();
599
+ if (currentMode() === "network") {
600
+ loadNetworks(false);
601
+ } else {
602
+ loadClients();
603
+ }
604
+ });
605
+
606
+ $networkId.on("change", function () {
607
+ if (suspendChangeHandling) {
608
+ return;
609
+ }
610
+ syncProgressiveRows();
611
+ });
612
+
613
+ $refreshNetworks.on("click", function (event) {
614
+ event.preventDefault();
615
+ loadNetworks(true);
616
+ });
617
+
470
618
  ensureDefaultServerSelection();
471
619
  makeSelectSearchable($clientId, "Search clients");
472
620
  refreshSummary();
473
- $refresh.find("i").addClass("fa-spin");
474
- loadClients();
621
+ syncProgressiveRows();
622
+ if (currentMode() === "network") {
623
+ loadNetworks(false);
624
+ } else {
625
+ $refresh.find("i").addClass("fa-spin");
626
+ loadClients();
627
+ }
475
628
  }
476
629
  });
477
630
  </script>
@@ -490,61 +643,101 @@
490
643
  <label for="node-input-server"><i class="fa fa-cog"></i> Connection</label>
491
644
  <input type="text" id="node-input-server">
492
645
  </div>
493
- <div class="form-row">
646
+ <div class="form-row" id="node-row-watchBy" style="display:none;">
647
+ <label for="node-input-watchBy"><i class="fa fa-eye"></i> Watch by</label>
648
+ <select id="node-input-watchBy">
649
+ <option value="presence">Single client (presence)</option>
650
+ <option value="network">Network (join/leave)</option>
651
+ </select>
652
+ </div>
653
+ <div class="form-row" id="node-row-clientId">
494
654
  <label for="node-input-clientId"><i class="fa fa-wifi"></i> Client</label>
495
655
  <select id="node-input-clientId" style="width:62%;"></select>
496
656
  <a href="#" id="node-input-refreshClients" class="editor-button" style="margin-left:6px;" title="Refresh clients" aria-label="Refresh clients">
497
657
  <i class="fa fa-refresh"></i>
498
658
  </a>
499
659
  </div>
660
+ <div class="form-row" id="node-row-networkId" style="display:none;">
661
+ <label for="node-input-networkId"><i class="fa fa-sitemap"></i> Network</label>
662
+ <select id="node-input-networkId" style="width:62%;"></select>
663
+ <a href="#" id="node-input-refreshNetworks" class="editor-button" style="margin-left:6px;" title="Reload networks" aria-label="Reload networks">
664
+ <i class="fa fa-refresh"></i>
665
+ </a>
666
+ <div id="unifi-presence-network-status" class="unifi-presence-network-status"></div>
667
+ </div>
500
668
  <div id="node-row-advanced" class="unifi-ultimate-advanced">
501
669
  <div class="form-row">
502
670
  <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
503
671
  <input type="text" id="node-input-name" placeholder="Node name">
504
672
  </div>
505
- <div class="form-row">
506
- <label for="node-input-pollInterval"><i class="fa fa-repeat"></i> Poll (s)</label>
507
- <input type="text" id="node-input-pollInterval" placeholder="10">
508
- </div>
509
- <div class="form-row">
510
- <label for="node-input-onlineHysteresis"><i class="fa fa-hourglass-start"></i> Connect Hysteresis (s)</label>
511
- <input type="text" id="node-input-onlineHysteresis" placeholder="15">
512
- </div>
513
- <div class="form-row">
514
- <label for="node-input-offlineHysteresis"><i class="fa fa-hourglass-half"></i> Hysteresis (s)</label>
515
- <input type="text" id="node-input-offlineHysteresis" placeholder="30">
673
+ <div id="node-presence-tuning">
674
+ <div class="form-row">
675
+ <label for="node-input-pollInterval"><i class="fa fa-repeat"></i> Poll (s)</label>
676
+ <input type="text" id="node-input-pollInterval" placeholder="10">
677
+ </div>
678
+ <div class="form-row">
679
+ <label for="node-input-onlineHysteresis"><i class="fa fa-hourglass-start"></i> Connect Hysteresis (s)</label>
680
+ <input type="text" id="node-input-onlineHysteresis" placeholder="15">
681
+ </div>
682
+ <div class="form-row">
683
+ <label for="node-input-offlineHysteresis"><i class="fa fa-hourglass-half"></i> Hysteresis (s)</label>
684
+ <input type="text" id="node-input-offlineHysteresis" placeholder="30">
685
+ </div>
686
+ <div class="form-row">
687
+ <label for="node-input-repeatInterval"><i class="fa fa-clock-o"></i> Resend (s)</label>
688
+ <input type="text" id="node-input-repeatInterval" placeholder="0 = off">
689
+ </div>
516
690
  </div>
517
- <div class="form-row">
518
- <label for="node-input-repeatInterval"><i class="fa fa-clock-o"></i> Resend (s)</label>
519
- <input type="text" id="node-input-repeatInterval" placeholder="0 = off">
691
+ <div id="node-network-tuning" style="display:none;">
692
+ <div class="form-row">
693
+ <label for="node-input-emitInitial" style="width:auto;"><i class="fa fa-bullhorn"></i> Emit current clients on start</label>
694
+ <input type="checkbox" id="node-input-emitInitial" style="display:inline-block; width:auto; vertical-align:top;">
695
+ </div>
520
696
  </div>
521
697
  <input type="hidden" id="node-input-deviceName">
698
+ <input type="hidden" id="node-input-networkName">
699
+ <input type="hidden" id="node-input-joinConfirmPolls">
700
+ <input type="hidden" id="node-input-leaveConfirmPolls">
522
701
  </div>
523
702
  </script>
524
703
 
525
704
  <script type="text/html" data-help-name="unifi-network-presence">
526
705
  <p><a href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
527
706
 
528
- <p>Detects whether a selected UniFi Network client is currently connected.</p>
707
+ <p>Watches UniFi Network clients. In <b>Single client (presence)</b> mode it tells you whether one selected client is connected (a boolean). In <b>Network (join/leave)</b> mode it watches a whole network/VLAN (for example <code>Guest</code>) and emits an event whenever any client joins or leaves it.</p>
529
708
 
530
709
  <h3>Configuration</h3>
531
710
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
711
+ <p><b>Watch by</b> chooses the mode: <code>Single client (presence)</code> or <code>Network (join/leave)</code>.</p>
712
+
713
+ <h4>Single client (presence)</h4>
532
714
  <p><b>Client</b> selects the client to track. The selector is searchable and opens with the complete list before filtering. Each entry shows the user-defined client name (e.g. "iPhone di Massimo") when set, otherwise the device hostname. Known-but-offline clients are included too and marked with an <code>(offline)</code> label, so you can pick a target even while it is disconnected.</p>
533
- <p><b>Poll (s)</b> sets this node cadence for presence checks. Scheduling and fetch execution are handled by the shared Network config node.</p>
534
- <p><b>Connect Hysteresis (s)</b> delays the <code>true</code> output so brief reconnects do not flap.</p>
535
- <p><b>Hysteresis (s)</b> delays the <code>false</code> output to avoid flapping when the client disconnects briefly.</p>
536
- <p><b>Resend (s)</b> optionally re-emits the last saved presence value on a fixed cadence, even when it has not changed. Leave it at <code>0</code> to disable (default). Repeated messages carry <code>msg.eventName = "repeat"</code> so you can tell them apart from state changes.</p>
537
- <p>Request timeout is handled automatically by the node.</p>
538
- <p><b>Name</b> is the node name shown in the editor and is updated only when you manually select a different client from the list.</p>
715
+ <p><b>Connect Hysteresis (s)</b> delays the <code>true</code> output so brief reconnects do not flap. <b>Hysteresis (s)</b> delays the <code>false</code> output. <b>Resend (s)</b> optionally re-emits the last saved value on a fixed cadence (<code>0</code> = off); resent messages carry <code>msg.eventName = "repeat"</code>.</p>
716
+
717
+ <h4>Network (join/leave)</h4>
718
+ <p><b>Network</b> selects the L3 network / VLAN to watch. The list comes from the networks configured on your controller. This is the only required field — sensible defaults handle the rest.</p>
719
+ <p><b>Emit current clients on start</b>, when enabled, emits a <code>joined</code> event for every client already on the network at deploy. Disabled (default) only reports later changes.</p>
720
+ <p>The node automatically debounces events (a client must be seen for a couple of polls before <code>joined</code>/<code>left</code> fires) to absorb the transient flapping UniFi shows while it classifies a freshly connected client. Polling cadence and debounce use built-in defaults.</p>
721
+ <p><b>Note on timing:</b> a newly connected client can take up to about a minute to appear on its network in the UniFi data (especially guest networks), so a <code>joined</code> event may lag the physical connection. This is a controller-side limitation.</p>
722
+ <p><b>Note on duplicate events:</b> you may see repeated <code>joined</code>/<code>left</code> for the same device. This comes from the UniFi controller itself, not the node:</p>
723
+ <ul>
724
+ <li><b>UniFi client flapping</b> — a well-known controller behaviour where clients are shown repeatedly connecting/disconnecting (band steering, load balancing, fast roaming, weak signal). During a single reconnect the client can bounce in and out of its network for ~1 minute before settling.</li>
725
+ <li><b>Wi‑Fi MAC randomization (Private Address)</b> — phones/tablets present a different MAC over time, so the same physical device looks like a new client joining while the old MAC leaves. This is common on guest networks.</li>
726
+ </ul>
727
+ <p>The node reports the controller's data faithfully and applies a small built-in debounce, but it cannot fully remove this upstream noise. If duplicates are a problem, debounce in your flow — for example an <code>rbe</code> ("block unless value changes") node, or a <code>delay</code> node in rate-limit mode, keyed on <code>msg.deviceName</code>/<code>msg.payload.mac</code>.</p>
728
+
729
+ <p>In <b>presence</b> mode, <b>Poll (s)</b> sets the check cadence. <b>Name</b> is the node name shown in the editor. Request timeout is handled automatically.</p>
539
730
 
540
731
  <h3>Input</h3>
541
732
  <ul>
542
- <li>No input pin in this mode: checks run automatically at startup and then on the configured cadence through the shared config scheduler.</li>
733
+ <li><b>Presence mode:</b> no input pin; checks run automatically at startup and on the configured cadence.</li>
734
+ <li><b>Network mode:</b> any incoming message forces an immediate poll between intervals.</li>
543
735
  </ul>
544
736
 
545
737
  <h3>Outputs</h3>
738
+ <p><b>Network mode</b> emits one message per client on Output 1 with <code>msg.eventName</code> = <code>joined</code>/<code>left</code>, the client name in <code>msg.deviceName</code>, the watched network in <code>msg.network</code>, and details (<code>mac</code>, <code>isGuest</code>, <code>isWired</code>, <code>ipAddress</code>, …) in <code>msg.payload</code>. Route joins and leaves apart with a <code>switch</code> node on <code>msg.eventName</code>. The fields below describe <b>presence mode</b>.</p>
546
739
  <dl class="message-properties">
547
- <dt>Output 1 — presence</dt>
740
+ <dt>Output 1 — result</dt>
548
741
  <dd>Emitted when the debounced presence state changes.</dd>
549
742
  <dt class="optional">msg.payload</dt>
550
743
  <dd><code>true</code> when the client is present, <code>false</code> when absent.</dd>
@@ -592,4 +785,13 @@
592
785
  "payload": null,
593
786
  "error": { "message": "Presence polling failed" }
594
787
  }</code></pre>
595
- </script>
788
+ </script>
789
+
790
+ <style>
791
+ .unifi-presence-network-status {
792
+ margin-top: 4px;
793
+ margin-left: 102px;
794
+ font-size: 0.85em;
795
+ color: var(--red-ui-text-color-error, #b30000);
796
+ }
797
+ </style>
@@ -8,10 +8,23 @@ const {
8
8
  resolveDeviceName,
9
9
  extractDeviceNameFromPayload,
10
10
  attachDetails,
11
- buildErrorOutputMessage
11
+ buildErrorOutputMessage,
12
+ parseBoolean
12
13
  } = require("./utils/common-utils");
13
14
  const DEFAULT_REQUEST_TIMEOUT_MS = 8000;
14
15
 
16
+ function normalizeString(value) {
17
+ return String(value || "").trim();
18
+ }
19
+
20
+ function parseConfirmPolls(value, fallbackValue) {
21
+ const numeric = Number(value);
22
+ if (!Number.isFinite(numeric) || numeric < 1) {
23
+ return fallbackValue;
24
+ }
25
+ return Math.max(1, Math.trunc(numeric));
26
+ }
27
+
15
28
  function parsePositiveSeconds(value, fallbackValue) {
16
29
  const numeric = Number(value);
17
30
  if (!Number.isFinite(numeric) || numeric <= 0) {
@@ -34,6 +47,220 @@ function resolveClientId(configuredClientId) {
34
47
  return String(configuredClientId || "").trim();
35
48
  }
36
49
 
50
+ // "Network (join/leave)" mode. Polls the connected clients of a network and
51
+ // emits a message when one joins or leaves. A debounce (consecutive-poll
52
+ // confirmation) absorbs the transient flapping UniFi shows while it classifies
53
+ // a freshly connected client onto its network. Shares the same polling engine
54
+ // idea as the single-client presence mode above.
55
+ function setupNetworkClientWatch(node, config) {
56
+ node.networkId = normalizeString(config.networkId);
57
+ node.networkName = normalizeString(config.networkName);
58
+ node.pollIntervalSeconds = parsePositiveSeconds(config.pollInterval, 30);
59
+ node.emitInitial = parseBoolean(config.emitInitial);
60
+ node.joinConfirmPolls = parseConfirmPolls(config.joinConfirmPolls, 1);
61
+ node.leaveConfirmPolls = parseConfirmPolls(config.leaveConfirmPolls, 3);
62
+ node.timeout = DEFAULT_REQUEST_TIMEOUT_MS;
63
+
64
+ node.pollTimer = null;
65
+ node.pollInProgress = false;
66
+ node.confirmed = null; // null until the first successful poll baseline.
67
+ node.presentStreak = new Map(); // mac -> consecutive polls seen present (pending join).
68
+ node.absentStreak = new Map(); // mac -> consecutive polls seen absent (pending leave).
69
+
70
+ function setNodeStatus(status) {
71
+ if (!status || typeof status !== "object" || Array.isArray(status)) {
72
+ return;
73
+ }
74
+ node.status({
75
+ ...status,
76
+ text: appendStatusTimestamp(status.text)
77
+ });
78
+ }
79
+
80
+ function resolveNetworkLabel() {
81
+ return node.networkName || "network";
82
+ }
83
+
84
+ function emitClientEvent(eventName, client) {
85
+ const nodeName = resolveNodeName(node.name);
86
+ const deviceName = normalizeString(client && client.name) || normalizeString(client && client.mac) || "Client";
87
+ const networkName = normalizeString(client && client.networkName) || node.networkName;
88
+
89
+ const outputMsg = {
90
+ topic: nodeName,
91
+ eventName,
92
+ deviceName,
93
+ network: networkName || undefined,
94
+ payload: {
95
+ event: eventName,
96
+ deviceName,
97
+ mac: normalizeString(client && client.mac) || undefined,
98
+ network: networkName || undefined,
99
+ networkId: normalizeString(client && client.networkId) || node.networkId || undefined,
100
+ isGuest: client && client.isGuest === true,
101
+ isWired: client && client.isWired === true,
102
+ ipAddress: normalizeString(client && client.ipAddress) || undefined
103
+ }
104
+ };
105
+ attachDetails(outputMsg, { client });
106
+
107
+ node.send([outputMsg, null]);
108
+ }
109
+
110
+ function diffAndEmit(currentClients) {
111
+ const presentByMac = new Map();
112
+ currentClients.forEach((client) => {
113
+ const mac = normalizeString(client && client.mac).toLowerCase();
114
+ if (mac) {
115
+ presentByMac.set(mac, client);
116
+ }
117
+ });
118
+
119
+ // First successful poll only establishes the baseline so existing
120
+ // clients are not all reported as fresh joins (unless requested).
121
+ if (node.confirmed === null) {
122
+ node.confirmed = presentByMac;
123
+ node.presentStreak.clear();
124
+ node.absentStreak.clear();
125
+ if (node.emitInitial) {
126
+ presentByMac.forEach((client) => emitClientEvent("joined", client));
127
+ }
128
+ return;
129
+ }
130
+
131
+ // Candidate joins: present now. Confirm once seen for enough polls.
132
+ presentByMac.forEach((client, mac) => {
133
+ node.absentStreak.delete(mac);
134
+ if (node.confirmed.has(mac)) {
135
+ node.confirmed.set(mac, client); // keep latest client info
136
+ return;
137
+ }
138
+ const streak = (node.presentStreak.get(mac) || 0) + 1;
139
+ if (streak >= node.joinConfirmPolls) {
140
+ node.presentStreak.delete(mac);
141
+ node.confirmed.set(mac, client);
142
+ emitClientEvent("joined", client);
143
+ } else {
144
+ node.presentStreak.set(mac, streak);
145
+ }
146
+ });
147
+
148
+ // Candidate leaves: confirmed members now absent. Confirm after enough
149
+ // consecutive absences so a transient drop does not fire a false leave.
150
+ Array.from(node.confirmed.keys()).forEach((mac) => {
151
+ if (presentByMac.has(mac)) {
152
+ return;
153
+ }
154
+ const streak = (node.absentStreak.get(mac) || 0) + 1;
155
+ if (streak >= node.leaveConfirmPolls) {
156
+ const client = node.confirmed.get(mac);
157
+ node.absentStreak.delete(mac);
158
+ node.confirmed.delete(mac);
159
+ emitClientEvent("left", client);
160
+ } else {
161
+ node.absentStreak.set(mac, streak);
162
+ }
163
+ });
164
+
165
+ // Forget pending joins for clients that vanished before confirming.
166
+ Array.from(node.presentStreak.keys()).forEach((mac) => {
167
+ if (!presentByMac.has(mac)) {
168
+ node.presentStreak.delete(mac);
169
+ }
170
+ });
171
+ }
172
+
173
+ async function poll() {
174
+ if (node.pollInProgress) {
175
+ return;
176
+ }
177
+ if (!node.server || typeof node.server.fetchActiveClientsOnNetwork !== "function") {
178
+ throw new Error("Unifi Network configuration is missing or incompatible.");
179
+ }
180
+ if (!node.networkId) {
181
+ throw new Error("No network selected. Open the node and choose a network.");
182
+ }
183
+
184
+ node.pollInProgress = true;
185
+ try {
186
+ // Pass the known network name so the config helper can skip its
187
+ // per-poll networkconf lookup.
188
+ const clients = await node.server.fetchActiveClientsOnNetwork(node.networkId, node.networkName);
189
+ const list = Array.isArray(clients) ? clients : [];
190
+ diffAndEmit(list);
191
+ setNodeStatus({
192
+ fill: "green",
193
+ shape: "dot",
194
+ text: `${list.length} on ${resolveNetworkLabel()}`
195
+ });
196
+ } finally {
197
+ node.pollInProgress = false;
198
+ }
199
+ }
200
+
201
+ function runPoll() {
202
+ poll().catch((error) => {
203
+ setNodeStatus({ fill: "red", shape: "ring", text: "error" });
204
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
205
+ node.error(error);
206
+ });
207
+ }
208
+
209
+ function stopPolling() {
210
+ if (node.pollTimer) {
211
+ clearInterval(node.pollTimer);
212
+ node.pollTimer = null;
213
+ }
214
+ }
215
+
216
+ function startPolling() {
217
+ stopPolling();
218
+ // Re-baseline on (re)deploy so existing members are not re-announced.
219
+ node.confirmed = null;
220
+ node.presentStreak.clear();
221
+ node.absentStreak.clear();
222
+ setNodeStatus({ fill: "blue", shape: "ring", text: `watching ${resolveNetworkLabel()}` });
223
+ runPoll();
224
+ node.pollTimer = setInterval(runPoll, node.pollIntervalSeconds * 1000);
225
+ }
226
+
227
+ node.on("input", function(_msg, send, done) {
228
+ // A manual trigger forces an immediate poll between intervals.
229
+ poll().then(() => {
230
+ if (typeof done === "function") {
231
+ done();
232
+ }
233
+ }).catch((error) => {
234
+ setNodeStatus({ fill: "red", shape: "ring", text: "error" });
235
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
236
+ if (typeof done === "function") {
237
+ done(error);
238
+ } else {
239
+ node.error(error);
240
+ }
241
+ });
242
+ });
243
+
244
+ if (!node.server) {
245
+ setNodeStatus({ fill: "red", shape: "ring", text: "no config" });
246
+ } else if (!node.networkId) {
247
+ setNodeStatus({ fill: "grey", shape: "ring", text: "select network" });
248
+ } else {
249
+ startPolling();
250
+ }
251
+
252
+ node.on("close", function(done) {
253
+ try {
254
+ stopPolling();
255
+ } catch (error) {
256
+ } finally {
257
+ if (typeof done === "function") {
258
+ done();
259
+ }
260
+ }
261
+ });
262
+ }
263
+
37
264
  module.exports = function(RED) {
38
265
  function UnifiNetworkPresenceNode(config) {
39
266
  RED.nodes.createNode(this, config);
@@ -41,6 +268,14 @@ module.exports = function(RED) {
41
268
  const node = this;
42
269
  node.name = config.name;
43
270
  node.server = RED.nodes.getNode(config.server);
271
+ // "Watch by" selects the mode. "presence" (default) tracks a single
272
+ // client; "network" watches a network for clients joining/leaving.
273
+ node.watchBy = normalizeString(config.watchBy) || "presence";
274
+ if (node.watchBy === "network") {
275
+ setupNetworkClientWatch(node, config);
276
+ return;
277
+ }
278
+
44
279
  node.clientId = config.clientId || "";
45
280
  node.pollIntervalSeconds = parsePositiveSeconds(config.pollInterval, 10);
46
281
  node.onlineHysteresisSeconds = parseNonNegativeSeconds(config.onlineHysteresis, 15);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.0.9",
3
+ "version": "1.1.0",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",
@@ -36,14 +36,14 @@
36
36
  "version": ">=3.1.1",
37
37
  "nodes": {
38
38
  "unifi-access-config": "nodes/unifi-access-config.js",
39
- "unifi-access-device": "nodes/unifi-access-device.js",
40
- "unifi-network-control-poe": "nodes/unifi-network-control-poe.js",
39
+ "unifi-protect-config": "nodes/unifi-protect-config.js",
41
40
  "unifi-network-config": "nodes/unifi-network-config.js",
42
41
  "unifi-network-device": "nodes/unifi-network-device.js",
42
+ "unifi-protect-device": "nodes/unifi-protect-device.js",
43
+ "unifi-access-device": "nodes/unifi-access-device.js",
44
+ "unifi-network-control-poe": "nodes/unifi-network-control-poe.js",
43
45
  "unifi-network-presence": "nodes/unifi-network-presence.js",
44
- "unifi-network-restart": "nodes/unifi-network-restart.js",
45
- "unifi-protect-config": "nodes/unifi-protect-config.js",
46
- "unifi-protect-device": "nodes/unifi-protect-device.js"
46
+ "unifi-network-restart": "nodes/unifi-network-restart.js"
47
47
  }
48
48
  },
49
49
  "scripts": {