node-red-contrib-unifi-ultimate 1.1.3 → 1.1.4

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
@@ -78,6 +78,7 @@ Use **Network** nodes to work with:
78
78
  Things you can do:
79
79
 
80
80
  - Check whether a device or phone is connected to your network.
81
+ - Track presence either by the exact UniFi client ID or by client name; name matching tolerates private/rotating MAC addresses by resolving the active client again on every poll.
81
82
  - Re-send the current presence state at a fixed interval with the Presence node's **Resend** field (e.g. to keep a dashboard or home-automation system in sync).
82
83
  - Count how many clients are currently online.
83
84
  - List the site's configured networks, Wi-Fi broadcasts, and WAN interfaces.
@@ -850,7 +850,20 @@
850
850
  );
851
851
  });
852
852
 
853
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
853
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
854
+ return String($(this).val() || "") === currentValue;
855
+ }).length > 0;
856
+ if (hasCurrentValue) {
857
+ $deviceId.val(currentValue);
858
+ } else if (currentValue) {
859
+ const savedName = String(node.deviceName || currentValue).trim();
860
+ $deviceId.append(
861
+ $("<option></option>")
862
+ .val(currentValue)
863
+ .text(savedName + " (saved; currently unavailable)")
864
+ .attr("data-device-name", savedName)
865
+ .attr("data-unavailable", "true")
866
+ );
854
867
  $deviceId.val(currentValue);
855
868
  } else {
856
869
  $deviceId.val("");
@@ -1069,6 +1082,7 @@
1069
1082
  });
1070
1083
 
1071
1084
  refreshSelectionSummary();
1085
+ renderDevices([]);
1072
1086
  ensureDefaultServerSelection();
1073
1087
  refreshEditor();
1074
1088
  }
@@ -1135,7 +1149,7 @@
1135
1149
 
1136
1150
  <h3>Configuration</h3>
1137
1151
  <p><b>Connection</b> selects the shared UniFi Access config node.</p>
1138
- <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering.</p>
1152
+ <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
1139
1153
  <p><b>Action</b> only shows actions supported by the selected item.</p>
1140
1154
  <p>Additional fields appear only when the selected action needs extra input, such as a temporary lock rule or a room name for doorbell actions.</p>
1141
1155
  <p>For <code>Set Temporary Lock Rule</code>, choose <code>Custom Duration</code> to reveal the minutes field. Legacy <code>ended_time</code> is still available only as fallback compatibility.</p>
@@ -24,6 +24,12 @@ const {
24
24
  resolveScopedIdentifiers,
25
25
  summarizeDevice
26
26
  } = require("./utils/unifi-network-device-registry");
27
+ const {
28
+ normalizePresenceMatchBy,
29
+ normalizeClientMatchName,
30
+ findActiveClientsByName,
31
+ resolveClientResourceId
32
+ } = require("./utils/unifi-network-presence-utils");
27
33
 
28
34
  module.exports = function(RED) {
29
35
  const API_KEY_HEADER = "X-API-Key";
@@ -1433,7 +1439,7 @@ module.exports = function(RED) {
1433
1439
  return node.legacySiteNameById.get(normalizedSiteId) || "";
1434
1440
  }
1435
1441
 
1436
- async function fetchLegacySiteCollection(siteId, collectionPath) {
1442
+ async function fetchLegacySiteCollection(siteId, collectionPath, timeout) {
1437
1443
  const legacySiteName = await fetchLegacySiteName(siteId);
1438
1444
  if (!legacySiteName) {
1439
1445
  return [];
@@ -1441,7 +1447,8 @@ module.exports = function(RED) {
1441
1447
 
1442
1448
  const response = await node.legacyApiRequest({
1443
1449
  path: `/api/s/${encodeURIComponent(legacySiteName)}${collectionPath}`,
1444
- method: "GET"
1450
+ method: "GET",
1451
+ timeout: Number(timeout) > 0 ? Number(timeout) : 15000
1445
1452
  });
1446
1453
 
1447
1454
  if (response.statusCode < 200 || response.statusCode >= 300) {
@@ -1451,8 +1458,8 @@ module.exports = function(RED) {
1451
1458
  return normalizeNetworkCollection(response.payload);
1452
1459
  }
1453
1460
 
1454
- async function fetchLegacyClients(siteId) {
1455
- const clients = await fetchLegacySiteCollection(siteId, "/stat/sta");
1461
+ async function fetchLegacyClients(siteId, timeout) {
1462
+ const clients = await fetchLegacySiteCollection(siteId, "/stat/sta", timeout);
1456
1463
  return clients.map((client) => ({
1457
1464
  ...client,
1458
1465
  __unifiUltimateOnline: true,
@@ -2503,11 +2510,126 @@ module.exports = function(RED) {
2503
2510
  };
2504
2511
  };
2505
2512
 
2513
+ node.fetchActivePresenceClients = async (siteId, timeout) => {
2514
+ const normalizedSiteId = normalizeString(siteId);
2515
+ if (!normalizedSiteId) {
2516
+ throw new Error("Client selection is invalid. Re-select the client from the editor.");
2517
+ }
2518
+
2519
+ // Name matching needs the currently connected population, not the
2520
+ // historical known-client list. Query both sources so aliases and
2521
+ // hostnames remain available across controller/API versions.
2522
+ const results = await Promise.allSettled([
2523
+ node.fetchPagedCollection({
2524
+ path: `/v1/sites/${encodeURIComponent(normalizedSiteId)}/clients`,
2525
+ timeout: Number(timeout) > 0 ? Number(timeout) : 8000
2526
+ }),
2527
+ fetchLegacyClients(normalizedSiteId, Number(timeout) > 0 ? Number(timeout) : 8000)
2528
+ ]);
2529
+ const successful = results.filter((result) => result.status === "fulfilled");
2530
+ if (successful.length === 0) {
2531
+ const firstFailure = results.find((result) => result.status === "rejected");
2532
+ throw (firstFailure && firstFailure.reason) || new Error("Unable to load active clients.");
2533
+ }
2534
+
2535
+ const officialClients = results[0].status === "fulfilled" && Array.isArray(results[0].value)
2536
+ ? results[0].value
2537
+ : [];
2538
+ const legacyClients = results[1].status === "fulfilled" && Array.isArray(results[1].value)
2539
+ ? results[1].value
2540
+ : [];
2541
+
2542
+ return officialClients
2543
+ .map((client) => ({
2544
+ ...client,
2545
+ siteId: client && (client.siteId || client.site_id) || normalizedSiteId,
2546
+ isOnline: true,
2547
+ online: true,
2548
+ offline: false
2549
+ }))
2550
+ .concat(legacyClients.map((client) => ({
2551
+ ...client,
2552
+ siteId: client && (client.siteId || client.site_id) || normalizedSiteId,
2553
+ isOnline: true,
2554
+ online: true,
2555
+ offline: false
2556
+ })));
2557
+ };
2558
+
2559
+ node.fetchPresenceObservationSnapshotByName = async (clientId, clientName, timeout, activeClients) => {
2560
+ const scoped = resolveScopedIdentifiers("client", clientId);
2561
+ const normalizedClientName = normalizeString(clientName);
2562
+ if (!scoped.siteId || !normalizedClientName) {
2563
+ throw new Error("Client name selection is invalid. Re-select the client from the editor.");
2564
+ }
2565
+
2566
+ const clients = Array.isArray(activeClients)
2567
+ ? activeClients
2568
+ : await node.fetchActivePresenceClients(scoped.siteId, timeout);
2569
+ const matches = findActiveClientsByName(clients, normalizedClientName);
2570
+ if (matches.length === 0) {
2571
+ return {
2572
+ found: false,
2573
+ connected: false,
2574
+ statusCode: 404,
2575
+ client: null,
2576
+ matchBy: "name",
2577
+ clientName: normalizedClientName,
2578
+ matchCount: 0
2579
+ };
2580
+ }
2581
+
2582
+ // The official and legacy collections can describe the same active
2583
+ // client. Count unique identities so metadata is not inflated.
2584
+ const uniqueMatches = new Map();
2585
+ matches.forEach((client, index) => {
2586
+ const key = normalizeIdentifierKey(client && (client.macAddress || client.mac_address || client.mac))
2587
+ || normalizeIdentifierKey(resolveClientResourceId(client))
2588
+ || String(index);
2589
+ if (!uniqueMatches.has(key)) {
2590
+ uniqueMatches.set(key, client);
2591
+ }
2592
+ });
2593
+ const matchedClient = uniqueMatches.values().next().value;
2594
+ const matchedResourceId = resolveClientResourceId(matchedClient);
2595
+ const matchedClientId = encodeScopedDeviceId(scoped.siteId, matchedResourceId) || matchedResourceId;
2596
+
2597
+ return {
2598
+ found: true,
2599
+ connected: true,
2600
+ statusCode: 200,
2601
+ client: {
2602
+ ...matchedClient,
2603
+ siteId: matchedClient && (matchedClient.siteId || matchedClient.site_id) || scoped.siteId
2604
+ },
2605
+ matchBy: "name",
2606
+ clientName: normalizedClientName,
2607
+ matchCount: uniqueMatches.size,
2608
+ matchedClientId: matchedClientId || undefined
2609
+ };
2610
+ };
2611
+
2612
+ node.fetchPresenceObservationSnapshotForDescriptor = async (descriptor, activeClients) => {
2613
+ const matchBy = normalizePresenceMatchBy(descriptor && descriptor.matchBy);
2614
+ if (matchBy === "name") {
2615
+ return node.fetchPresenceObservationSnapshotByName(
2616
+ descriptor && descriptor.clientId,
2617
+ descriptor && descriptor.clientName,
2618
+ descriptor && descriptor.timeout,
2619
+ activeClients
2620
+ );
2621
+ }
2622
+ return node.fetchPresenceObservationSnapshot(
2623
+ descriptor && descriptor.clientId,
2624
+ descriptor && descriptor.timeout
2625
+ );
2626
+ };
2627
+
2506
2628
  node.requestPresenceObservationNow = async (descriptor) => {
2507
2629
  if (!descriptor || typeof descriptor !== "object") {
2508
2630
  throw new Error("Invalid presence descriptor.");
2509
2631
  }
2510
- const snapshot = await node.fetchPresenceObservationSnapshot(descriptor.clientId, descriptor.timeout);
2632
+ const snapshot = await node.fetchPresenceObservationSnapshotForDescriptor(descriptor);
2511
2633
  return {
2512
2634
  source: normalizeString(descriptor.source) || "manual-input",
2513
2635
  ...snapshot,
@@ -2542,9 +2664,14 @@ module.exports = function(RED) {
2542
2664
  }
2543
2665
 
2544
2666
  const clientId = normalizeString(descriptor.clientId);
2667
+ const matchBy = normalizePresenceMatchBy(descriptor.matchBy);
2668
+ const clientName = normalizeString(descriptor.clientName);
2545
2669
  const pollIntervalSeconds = Number(descriptor.pollIntervalSeconds);
2546
2670
  const timeout = Number(descriptor.timeout);
2547
- if (!clientId || !Number.isFinite(pollIntervalSeconds) || pollIntervalSeconds <= 0) {
2671
+ if (!clientId
2672
+ || (matchBy === "name" && !clientName)
2673
+ || !Number.isFinite(pollIntervalSeconds)
2674
+ || pollIntervalSeconds <= 0) {
2548
2675
  return null;
2549
2676
  }
2550
2677
 
@@ -2552,6 +2679,8 @@ module.exports = function(RED) {
2552
2679
  client,
2553
2680
  descriptor: {
2554
2681
  clientId,
2682
+ matchBy,
2683
+ clientName,
2555
2684
  pollIntervalMs: Math.max(1000, Math.trunc(pollIntervalSeconds * 1000)),
2556
2685
  timeout: Number.isFinite(timeout) && timeout > 0 ? Math.trunc(timeout) : 8000
2557
2686
  }
@@ -2634,9 +2763,14 @@ module.exports = function(RED) {
2634
2763
  }
2635
2764
 
2636
2765
  state.nextRunAt = now + entry.descriptor.pollIntervalMs;
2637
- const key = entry.descriptor.clientId;
2766
+ const scoped = resolveScopedIdentifiers("client", entry.descriptor.clientId);
2767
+ const key = entry.descriptor.matchBy === "name"
2768
+ ? `name::${scoped.siteId}::${normalizeClientMatchName(entry.descriptor.clientName)}`
2769
+ : `id::${entry.descriptor.clientId}`;
2638
2770
  const group = dueGroups.get(key) || {
2639
2771
  clientId: entry.descriptor.clientId,
2772
+ matchBy: entry.descriptor.matchBy,
2773
+ clientName: entry.descriptor.clientName,
2640
2774
  timeout: entry.descriptor.timeout,
2641
2775
  entries: []
2642
2776
  };
@@ -2645,10 +2779,22 @@ module.exports = function(RED) {
2645
2779
  dueGroups.set(key, group);
2646
2780
  });
2647
2781
 
2782
+ const activeClientsBySite = new Map();
2648
2783
  for (const group of dueGroups.values()) {
2649
2784
  let snapshot;
2650
2785
  try {
2651
- snapshot = await node.fetchPresenceObservationSnapshot(group.clientId, group.timeout);
2786
+ let activeClients;
2787
+ if (group.matchBy === "name") {
2788
+ const scoped = resolveScopedIdentifiers("client", group.clientId);
2789
+ if (!activeClientsBySite.has(scoped.siteId)) {
2790
+ activeClientsBySite.set(
2791
+ scoped.siteId,
2792
+ node.fetchActivePresenceClients(scoped.siteId, group.timeout)
2793
+ );
2794
+ }
2795
+ activeClients = await activeClientsBySite.get(scoped.siteId);
2796
+ }
2797
+ snapshot = await node.fetchPresenceObservationSnapshotForDescriptor(group, activeClients);
2652
2798
  } catch (error) {
2653
2799
  snapshot = {
2654
2800
  found: false,
@@ -2663,6 +2809,8 @@ module.exports = function(RED) {
2663
2809
  node.notifyPresenceObserverClient(entry.client, {
2664
2810
  source: "poll",
2665
2811
  clientId: group.clientId,
2812
+ matchBy: group.matchBy,
2813
+ clientName: group.clientName,
2666
2814
  ...snapshot
2667
2815
  });
2668
2816
  });
@@ -941,7 +941,20 @@
941
941
  $deviceId.append($option);
942
942
  });
943
943
 
944
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
944
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
945
+ return String($(this).val() || "") === currentValue;
946
+ }).length > 0;
947
+ if (hasCurrentValue) {
948
+ $deviceId.val(currentValue);
949
+ } else if (currentValue) {
950
+ const savedName = String(node.deviceName || currentValue).trim();
951
+ $deviceId.append(
952
+ $("<option></option>")
953
+ .val(currentValue)
954
+ .text(savedName + " (saved; currently unavailable)")
955
+ .attr("data-device-name", savedName)
956
+ .attr("data-unavailable", "true")
957
+ );
945
958
  $deviceId.val(currentValue);
946
959
  } else {
947
960
  $deviceId.val("");
@@ -955,16 +968,28 @@
955
968
  }
956
969
 
957
970
  function renderDevicesLoading(label) {
971
+ const savedValue = getCurrentOrNodeValue($deviceId, node.deviceId, "");
972
+ const savedName = String(node.deviceName || savedValue).trim();
958
973
  clientTargetsLoading = isClientResourceSelected();
959
974
  clientTargetsPopulated = false;
960
975
  withSuppressedChanges(function () {
961
976
  $deviceId.empty();
962
- $deviceId.append(
963
- $("<option></option>")
964
- .val("")
965
- .text(label)
966
- );
967
- $deviceId.val("");
977
+ if (savedValue) {
978
+ $deviceId.append(
979
+ $("<option></option>")
980
+ .val(savedValue)
981
+ .text(savedName + " (loading...)")
982
+ .attr("data-device-name", savedName)
983
+ );
984
+ $deviceId.val(savedValue);
985
+ } else {
986
+ $deviceId.append(
987
+ $("<option></option>")
988
+ .val("")
989
+ .text(label)
990
+ );
991
+ $deviceId.val("");
992
+ }
968
993
  });
969
994
 
970
995
  makeSelectSearchable($deviceId, label);
@@ -1197,6 +1222,7 @@
1197
1222
  });
1198
1223
 
1199
1224
  refreshSelectionSummary();
1225
+ renderDevicesLoading("Loading items, please wait...");
1200
1226
  ensureDefaultServerSelection();
1201
1227
  $refresh.find("i").addClass("fa-spin");
1202
1228
  refreshEditor();
@@ -1265,7 +1291,7 @@
1265
1291
  <h3>Configuration</h3>
1266
1292
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
1267
1293
  <p><b>Resource</b> chooses what you want to work with: Site, UniFi Device, or Client.</p>
1268
- <p><b>Item</b> chooses the specific site, device, or client. Device and client selectors are searchable and open with the complete list before filtering.</p>
1294
+ <p><b>Item</b> chooses the specific site, device, or client. Device and client selectors are searchable and open with the complete list before filtering. A saved selection that is offline or temporarily unavailable is preserved instead of being cleared.</p>
1269
1295
  <p><b>Action</b> only shows actions supported by the selected resource. Additional fields appear only when the selected action needs extra input.</p>
1270
1296
  <p>Action highlights include <code>Count Online Clients</code>, <code>List Networks</code>, <code>List Wi-Fi Broadcasts</code>, <code>List WAN Interfaces</code>, <code>List VPN Servers</code>, <code>List Site-to-Site VPN Tunnels</code>, <code>List Guest Vouchers</code>, <code>Create Guest Voucher</code>, <code>Read CPU</code>, <code>Read Memory</code>, <code>Read Uptime</code>, <code>Read Temperatures</code>, <code>Is Client Online</code>, <code>Restart Device</code>, and <code>Power Cycle Port</code>.</p>
1271
1297
  <p><code>Read Application Info</code> is available on the <code>Site</code> resource type and returns Network application metadata.</p>
@@ -17,6 +17,18 @@
17
17
  return (self && self.watchBy) ? String(self.watchBy).trim() : "presence";
18
18
  }
19
19
 
20
+ function currentPresenceMatchByValue(self) {
21
+ try {
22
+ const live = $("#node-input-matchBy").val();
23
+ if (live) {
24
+ return String(live).trim();
25
+ }
26
+ } catch (error) {
27
+ // jQuery/DOM not available in this context.
28
+ }
29
+ return (self && self.matchBy) ? String(self.matchBy).trim() : "id";
30
+ }
31
+
20
32
  RED.nodes.registerType("unifi-network-presence", {
21
33
  category: "Unifi Ultimate",
22
34
  color: "#CFE8FB",
@@ -24,6 +36,7 @@
24
36
  name: { value: "" },
25
37
  server: { value: "", type: "unifi-network-config", required: true },
26
38
  watchBy: { value: "presence", required: true },
39
+ matchBy: { value: "id", required: true },
27
40
  clientId: {
28
41
  value: "",
29
42
  validate: function (v) {
@@ -31,6 +44,16 @@
31
44
  return mode === "network" ? true : String(v || "").trim() !== "";
32
45
  }
33
46
  },
47
+ clientName: {
48
+ value: "",
49
+ validate: function (v) {
50
+ const mode = currentWatchByValue(this);
51
+ const matchBy = currentPresenceMatchByValue(this);
52
+ return mode !== "presence" || matchBy !== "name"
53
+ ? true
54
+ : String(v || this.deviceName || "").trim() !== "";
55
+ }
56
+ },
34
57
  deviceName: { value: "" },
35
58
  pollInterval: { value: 10, required: true, validate: RED.validators.number() },
36
59
  onlineHysteresis: { value: 15, required: true, validate: RED.validators.number() },
@@ -54,12 +77,12 @@
54
77
  paletteLabel: "Presence Detection",
55
78
  outputLabels: ["result", "error"],
56
79
  label: function () {
57
- if (this.name) {
58
- return this.name;
59
- }
60
80
  if (this.watchBy === "network" && this.networkName) {
61
81
  return this.networkName;
62
82
  }
83
+ if (this.watchBy !== "network" && (this.clientName || this.deviceName)) {
84
+ return this.clientName || this.deviceName;
85
+ }
63
86
  return "Presence Detection";
64
87
  },
65
88
  oneditsave: function () {
@@ -70,28 +93,42 @@
70
93
  const $selected = $("#node-input-networkId option:selected");
71
94
  this.networkName = String($selected.attr("data-network-name") || "").trim();
72
95
  $("#node-input-networkName").val(this.networkName);
96
+ } else {
97
+ const selectedClientName = String($("#node-input-clientId option:selected").attr("data-client-name") || "").trim();
98
+ const configuredClientName = String($("#node-input-clientName").val() || "").trim();
99
+ if (selectedClientName) {
100
+ this.deviceName = selectedClientName;
101
+ $("#node-input-deviceName").val(selectedClientName);
102
+ }
103
+ this.clientName = configuredClientName || selectedClientName;
104
+ $("#node-input-clientName").val(this.clientName);
73
105
  }
74
106
  },
75
107
  oneditprepare: function () {
76
108
  const node = this;
77
- const $name = $("#node-input-name");
78
109
  const $server = $("#node-input-server");
79
110
  const $watchBy = $("#node-input-watchBy");
111
+ const $matchBy = $("#node-input-matchBy");
80
112
  const $clientId = $("#node-input-clientId");
113
+ const $clientName = $("#node-input-clientName");
81
114
  const $deviceName = $("#node-input-deviceName");
82
115
  const $refresh = $("#node-input-refreshClients");
83
116
  const $clientRow = $clientId.closest(".form-row");
117
+ const $clientNameRow = $("#node-row-clientName");
84
118
  const $advancedRow = $("#node-row-advanced");
85
119
  // Network-mode controls.
86
120
  const $networkId = $("#node-input-networkId");
87
121
  const $refreshNetworks = $("#node-input-refreshNetworks");
88
122
  const $watchByRow = $("#node-row-watchBy");
123
+ const $matchByRow = $("#node-row-matchBy");
89
124
  const $networkRow = $("#node-row-networkId");
90
125
  const $networkStatus = $("#unifi-presence-network-status");
91
126
  let suspendChangeHandling = false;
92
127
  let loadedNetworksServerId = "";
93
128
 
94
129
  $watchBy.val(this.watchBy || "presence");
130
+ $matchBy.val(this.matchBy || "id");
131
+ $clientName.val(this.clientName || this.deviceName || "");
95
132
 
96
133
  function currentMode() {
97
134
  return String($watchBy.val() || "presence").trim();
@@ -108,7 +145,9 @@
108
145
  const hasTarget = isNetwork ? hasSelection($networkId) : hasSelection($clientId);
109
146
 
110
147
  $watchByRow.toggle(hasServer);
148
+ $matchByRow.toggle(hasServer && !isNetwork);
111
149
  $clientRow.toggle(hasServer && !isNetwork);
150
+ $clientNameRow.toggle(hasServer && !isNetwork && hasSelection($clientId));
112
151
  $networkRow.toggle(hasServer && isNetwork);
113
152
  $advancedRow.toggle(hasServer && hasTarget);
114
153
  // Tuning rows depend on the active mode.
@@ -137,7 +176,48 @@
137
176
  $("<option></option>").val(id).text(name + suffix).attr("data-network-name", name)
138
177
  );
139
178
  });
140
- $networkId.val(currentValue && $networkId.find("option[value='" + currentValue + "']").length > 0 ? currentValue : "");
179
+ const hasCurrentValue = currentValue && $networkId.find("option").filter(function () {
180
+ return String($(this).val() || "") === currentValue;
181
+ }).length > 0;
182
+ if (hasCurrentValue) {
183
+ $networkId.val(currentValue);
184
+ } else if (currentValue) {
185
+ const savedName = String(node.networkName || currentValue).trim();
186
+ $networkId.append(
187
+ $("<option></option>")
188
+ .val(currentValue)
189
+ .text(savedName + " (saved; currently unavailable)")
190
+ .attr("data-network-name", savedName)
191
+ .attr("data-unavailable", "true")
192
+ );
193
+ $networkId.val(currentValue);
194
+ } else {
195
+ $networkId.val("");
196
+ }
197
+ } finally {
198
+ suspendChangeHandling = false;
199
+ }
200
+ syncProgressiveRows();
201
+ }
202
+
203
+ function renderNetworksLoading() {
204
+ const savedValue = String($networkId.val() || node.networkId || "").trim();
205
+ const savedName = String(node.networkName || savedValue).trim();
206
+ suspendChangeHandling = true;
207
+ try {
208
+ $networkId.empty();
209
+ if (savedValue) {
210
+ $networkId.append(
211
+ $("<option></option>")
212
+ .val(savedValue)
213
+ .text(savedName + " (loading...)")
214
+ .attr("data-network-name", savedName)
215
+ );
216
+ $networkId.val(savedValue);
217
+ } else {
218
+ $networkId.append($('<option></option>').val("").text("Loading networks..."));
219
+ $networkId.val("");
220
+ }
141
221
  } finally {
142
222
  suspendChangeHandling = false;
143
223
  }
@@ -156,6 +236,7 @@
156
236
  }
157
237
  $networkStatus.text("Loading networks...");
158
238
  $refreshNetworks.find("i").addClass("fa-spin");
239
+ renderNetworksLoading();
159
240
  loadedNetworksServerId = serverId;
160
241
  return requestJson("unifiNetwork/networks?serverId=" + encodeURIComponent(serverId))
161
242
  .then(function (networks) {
@@ -446,7 +527,9 @@
446
527
 
447
528
  if (serverId && serverId !== "_ADD_") {
448
529
  summary = "Choose the client to monitor.";
449
- detail = "Presence checks are scheduled by the shared Network config node using UniFi Network data.";
530
+ detail = $matchBy.val() === "name"
531
+ ? "The active client is matched by alias or hostname on every poll."
532
+ : "The selected UniFi client ID is checked on every poll.";
450
533
  }
451
534
 
452
535
  if (clientName) {
@@ -456,22 +539,16 @@
456
539
  syncProgressiveRows();
457
540
  }
458
541
 
459
- function syncNameFromSelection() {
460
- const clientName = getSelectedClientName();
461
- if (!clientName) {
462
- return;
463
- }
464
-
465
- $name.val(clientName);
466
- }
467
-
468
- function rememberSelectedClientName() {
542
+ function rememberSelectedClientName(forceTargetName) {
469
543
  const clientName = getSelectedClientName();
470
544
  if (!clientName) {
471
545
  return;
472
546
  }
473
547
 
474
548
  $deviceName.val(clientName);
549
+ if (forceTargetName || !String($clientName.val() || "").trim()) {
550
+ $clientName.val(clientName);
551
+ }
475
552
  }
476
553
 
477
554
  function renderClients(items) {
@@ -500,7 +577,28 @@
500
577
  $clientId.append($option);
501
578
  });
502
579
 
503
- if (currentValue && $clientId.find("option[value='" + currentValue + "']").length > 0) {
580
+ const hasCurrentValue = currentValue && $clientId.find("option").filter(function () {
581
+ return String($(this).val() || "") === currentValue;
582
+ }).length > 0;
583
+ if (hasCurrentValue) {
584
+ $clientId.val(currentValue);
585
+ const loadedClientName = getSelectedClientName();
586
+ if (loadedClientName) {
587
+ $clientName.val(loadedClientName);
588
+ $deviceName.val(loadedClientName);
589
+ }
590
+ } else if (currentValue) {
591
+ // Never discard a saved target just because the controller
592
+ // omitted it from this refresh. Keeping a synthetic option
593
+ // prevents opening/saving the editor from erasing clientId.
594
+ const savedName = String($clientName.val() || node.clientName || node.deviceName || currentValue).trim();
595
+ $clientId.append(
596
+ $("<option></option>")
597
+ .val(currentValue)
598
+ .text(savedName + " (saved; currently unavailable)")
599
+ .attr("data-client-name", savedName)
600
+ .attr("data-unavailable", "true")
601
+ );
504
602
  $clientId.val(currentValue);
505
603
  } else {
506
604
  $clientId.val("");
@@ -510,20 +608,32 @@
510
608
  }
511
609
 
512
610
  makeSelectSearchable($clientId, "Search clients");
513
- rememberSelectedClientName();
611
+ rememberSelectedClientName(false);
514
612
  refreshSummary();
515
613
  }
516
614
 
517
615
  function renderClientsLoading() {
616
+ const savedValue = String($clientId.val() || node.clientId || "").trim();
617
+ const savedName = String($clientName.val() || node.clientName || node.deviceName || savedValue).trim();
518
618
  suspendChangeHandling = true;
519
619
  try {
520
620
  $clientId.empty();
521
- $clientId.append(
522
- $("<option></option>")
523
- .val("")
524
- .text("Loading clients, please wait...")
525
- );
526
- $clientId.val("");
621
+ if (savedValue) {
622
+ $clientId.append(
623
+ $("<option></option>")
624
+ .val(savedValue)
625
+ .text(savedName + " (loading...)")
626
+ .attr("data-client-name", savedName)
627
+ );
628
+ $clientId.val(savedValue);
629
+ } else {
630
+ $clientId.append(
631
+ $("<option></option>")
632
+ .val("")
633
+ .text("Loading clients, please wait...")
634
+ );
635
+ $clientId.val("");
636
+ }
527
637
  } finally {
528
638
  suspendChangeHandling = false;
529
639
  }
@@ -580,12 +690,8 @@
580
690
  if (suspendChangeHandling) {
581
691
  return;
582
692
  }
583
- rememberSelectedClientName();
584
- const isUserSelection = $clientId.data("unifi-user-selection") === true;
693
+ rememberSelectedClientName(true);
585
694
  $clientId.removeData("unifi-user-selection");
586
- if (isUserSelection) {
587
- syncNameFromSelection();
588
- }
589
695
  refreshSummary();
590
696
  });
591
697
 
@@ -603,6 +709,14 @@
603
709
  }
604
710
  });
605
711
 
712
+ $matchBy.on("change", function () {
713
+ refreshSummary();
714
+ });
715
+
716
+ $clientName.on("input change", function () {
717
+ refreshSummary();
718
+ });
719
+
606
720
  $networkId.on("change", function () {
607
721
  if (suspendChangeHandling) {
608
722
  return;
@@ -650,6 +764,13 @@
650
764
  <option value="network">Network (join/leave)</option>
651
765
  </select>
652
766
  </div>
767
+ <div class="form-row" id="node-row-matchBy" style="display:none;">
768
+ <label for="node-input-matchBy"><i class="fa fa-id-card-o"></i> Identify by</label>
769
+ <select id="node-input-matchBy">
770
+ <option value="id">Client ID</option>
771
+ <option value="name">Client name</option>
772
+ </select>
773
+ </div>
653
774
  <div class="form-row" id="node-row-clientId">
654
775
  <label for="node-input-clientId"><i class="fa fa-wifi"></i> Client</label>
655
776
  <select id="node-input-clientId" style="width:62%;"></select>
@@ -666,9 +787,10 @@
666
787
  <div id="unifi-presence-network-status" class="unifi-presence-network-status"></div>
667
788
  </div>
668
789
  <div id="node-row-advanced" class="unifi-ultimate-advanced">
669
- <div class="form-row">
670
- <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
671
- <input type="text" id="node-input-name" placeholder="Node name">
790
+ <div class="form-row" id="node-row-clientName" style="display:none;">
791
+ <label for="node-input-clientName"><i class="fa fa-font"></i> Match name</label>
792
+ <input type="text" id="node-input-clientName" readonly>
793
+ <div class="form-tips">Read-only value copied from the selected client. It is used when Identify by is set to Client name.</div>
672
794
  </div>
673
795
  <div id="node-presence-tuning">
674
796
  <div class="form-row">
@@ -694,6 +816,7 @@
694
816
  <input type="checkbox" id="node-input-emitInitial" style="display:inline-block; width:auto; vertical-align:top;">
695
817
  </div>
696
818
  </div>
819
+ <input type="hidden" id="node-input-name">
697
820
  <input type="hidden" id="node-input-deviceName">
698
821
  <input type="hidden" id="node-input-networkName">
699
822
  <input type="hidden" id="node-input-joinConfirmPolls">
@@ -712,6 +835,8 @@
712
835
 
713
836
  <h4>Single client (presence)</h4>
714
837
  <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>
838
+ <p><b>Identify by</b> controls how the selected client is found. <b>Client ID</b> (default) tracks the exact UniFi record and is the safest choice for most devices. <b>Client name</b> searches the currently connected clients by alias, display name, or hostname on every poll, so presence continues to work when a privacy-enabled device rotates its MAC address and UniFi assigns it a new client ID. The read-only <b>Match name</b> value is copied from the client selected above. Name matching is exact but case-insensitive; give devices unique names because any online client with the same name counts as present.</p>
839
+ <p>If a saved client is temporarily missing from the controller response, the editor keeps it as <code>saved; currently unavailable</code> instead of clearing the configuration.</p>
715
840
  <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
841
 
717
842
  <h4>Network (join/leave)</h4>
@@ -726,7 +851,7 @@
726
851
  </ul>
727
852
  <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
853
 
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>
854
+ <p>In <b>presence</b> mode, <b>Poll (s)</b> sets the check cadence. Request timeout is handled automatically.</p>
730
855
 
731
856
  <h3>Input</h3>
732
857
  <ul>
@@ -794,4 +919,4 @@
794
919
  font-size: 0.85em;
795
920
  color: var(--red-ui-text-color-error, #b30000);
796
921
  }
797
- </style>
922
+ </style>
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const { decodeScopedDeviceId } = require("./utils/unifi-network-device-registry");
4
+ const { normalizePresenceMatchBy } = require("./utils/unifi-network-presence-utils");
4
5
  const {
5
6
  buildStatusTimestampText,
6
7
  appendStatusTimestamp,
@@ -277,6 +278,11 @@ module.exports = function(RED) {
277
278
  }
278
279
 
279
280
  node.clientId = config.clientId || "";
281
+ // Existing flows keep the historical ID-based behavior. Name matching
282
+ // deliberately resolves the active client again on every poll, allowing
283
+ // privacy-addressed devices to rotate their MAC/resource id.
284
+ node.matchBy = normalizePresenceMatchBy(config.matchBy);
285
+ node.clientName = normalizeString(config.clientName || config.deviceName);
280
286
  node.pollIntervalSeconds = parsePositiveSeconds(config.pollInterval, 10);
281
287
  node.onlineHysteresisSeconds = parseNonNegativeSeconds(config.onlineHysteresis, 15);
282
288
  node.offlineHysteresisSeconds = parseNonNegativeSeconds(config.offlineHysteresis, 30);
@@ -293,6 +299,8 @@ module.exports = function(RED) {
293
299
  node.firstOnlineDetectedAt = 0;
294
300
  node.firstOfflineDetectedAt = 0;
295
301
  node.lastKnownClient = null;
302
+ node.lastMatchedClientId = "";
303
+ node.lastMatchCount = 0;
296
304
 
297
305
  function setNodeStatus(status) {
298
306
  if (!status || typeof status !== "object" || Array.isArray(status)) {
@@ -341,6 +349,10 @@ module.exports = function(RED) {
341
349
  name: nodeName || undefined,
342
350
  deviceName: resolvedDeviceName || undefined,
343
351
  clientId,
352
+ matchBy: node.matchBy,
353
+ clientName: node.matchBy === "name" ? node.clientName || undefined : undefined,
354
+ matchedClientId: node.lastMatchedClientId || undefined,
355
+ matchCount: node.matchBy === "name" ? node.lastMatchCount : undefined,
344
356
  siteId: scoped.siteId || undefined,
345
357
  resourceId: scoped.resourceId || undefined,
346
358
  source,
@@ -469,6 +481,14 @@ module.exports = function(RED) {
469
481
  const client = snapshot && snapshot.client && typeof snapshot.client === "object" && !Array.isArray(snapshot.client)
470
482
  ? snapshot.client
471
483
  : null;
484
+ if (node.matchBy === "name") {
485
+ node.lastMatchCount = Number.isFinite(Number(snapshot && snapshot.matchCount))
486
+ ? Math.max(0, Math.trunc(Number(snapshot.matchCount)))
487
+ : 0;
488
+ if (normalizeString(snapshot && snapshot.matchedClientId)) {
489
+ node.lastMatchedClientId = normalizeString(snapshot.matchedClientId);
490
+ }
491
+ }
472
492
  if (client) {
473
493
  node.lastKnownClient = client;
474
494
  }
@@ -507,6 +527,8 @@ module.exports = function(RED) {
507
527
  }
508
528
  return node.server.requestPresenceObservationNow({
509
529
  clientId,
530
+ matchBy: node.matchBy,
531
+ clientName: node.clientName,
510
532
  timeout: node.timeout,
511
533
  source: source || "manual-input"
512
534
  });
@@ -587,6 +609,8 @@ module.exports = function(RED) {
587
609
  }
588
610
  return {
589
611
  clientId,
612
+ matchBy: node.matchBy,
613
+ clientName: node.clientName,
590
614
  pollIntervalSeconds: node.pollIntervalSeconds,
591
615
  timeout: node.timeout
592
616
  };
@@ -606,6 +630,8 @@ module.exports = function(RED) {
606
630
  setNodeStatus({ fill: "red", shape: "ring", text: "no config" });
607
631
  } else if (!node.clientId) {
608
632
  setNodeStatus({ fill: "grey", shape: "ring", text: "set client" });
633
+ } else if (node.matchBy === "name" && !node.clientName) {
634
+ setNodeStatus({ fill: "grey", shape: "ring", text: "set client name" });
609
635
  } else {
610
636
  if (node.server && typeof node.server.addClient === "function") {
611
637
  node.server.addClient(node);
@@ -58,6 +58,15 @@
58
58
  }
59
59
  }
60
60
 
61
+ function parseStoredNames() {
62
+ try {
63
+ const parsed = JSON.parse(String(node.deviceNames || "{}"));
64
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
65
+ } catch (error) {
66
+ return {};
67
+ }
68
+ }
69
+
61
70
  function hasSelection($field) {
62
71
  return String($field.val() || "").trim() !== "";
63
72
  }
@@ -101,16 +110,12 @@
101
110
  const hasStoredSelection = storedIds.length > 0;
102
111
  const storedSet = {};
103
112
  storedIds.forEach(function (id) { storedSet[id] = true; });
113
+ const storedNames = parseStoredNames();
114
+ const renderedSet = {};
104
115
 
105
116
  $list.empty();
106
117
 
107
- if (!Array.isArray(items) || items.length === 0) {
108
- $list.append($("<div class='unifi-restart-empty'></div>").text("No UniFi Network devices found."));
109
- updateSelectedCount();
110
- return;
111
- }
112
-
113
- items
118
+ (Array.isArray(items) ? items : [])
114
119
  .slice()
115
120
  .sort(function (a, b) {
116
121
  return String(a.name || a.id).localeCompare(String(b.name || b.id));
@@ -120,6 +125,7 @@
120
125
  if (!id) {
121
126
  return;
122
127
  }
128
+ renderedSet[id] = true;
123
129
  const name = String(item.name || id).trim();
124
130
  const model = String(item.state || "").trim();
125
131
  const checked = hasStoredSelection ? Boolean(storedSet[id]) : !isGatewayLike(item);
@@ -139,6 +145,30 @@
139
145
  $list.append($row);
140
146
  });
141
147
 
148
+ // Keep configured devices that are missing from this controller
149
+ // response. Otherwise opening and saving the editor would silently
150
+ // delete an offline or temporarily unavailable target.
151
+ storedIds.forEach(function (id) {
152
+ if (renderedSet[id]) {
153
+ return;
154
+ }
155
+ const name = String(storedNames[id] || id).trim();
156
+ const $row = $("<label class='unifi-restart-device-row unifi-restart-device-unavailable'></label>");
157
+ const $checkbox = $("<input type='checkbox'>")
158
+ .attr("data-id", id)
159
+ .attr("data-name", name)
160
+ .prop("checked", true);
161
+ $checkbox.on("change", updateSelectedCount);
162
+ $row.append($checkbox);
163
+ $row.append($("<span class='unifi-restart-device-name'></span>").text(name));
164
+ $row.append($("<span class='unifi-restart-device-model'></span>").text("saved; currently unavailable"));
165
+ $list.append($row);
166
+ });
167
+
168
+ if ($list.find("input[type='checkbox']").length === 0) {
169
+ $list.append($("<div class='unifi-restart-empty'></div>").text("No UniFi Network devices found."));
170
+ }
171
+
142
172
  applyFilter();
143
173
  updateSelectedCount();
144
174
  }
@@ -158,9 +188,8 @@
158
188
  function loadDevices(force) {
159
189
  const serverId = String($server.val() || "").trim();
160
190
  if (!serverId || serverId === "_ADD_") {
161
- $list.empty();
191
+ renderDevices([]);
162
192
  $status.text("");
163
- updateSelectedCount();
164
193
  return Promise.resolve();
165
194
  }
166
195
 
@@ -169,6 +198,9 @@
169
198
  }
170
199
 
171
200
  $status.text("Loading devices...");
201
+ if ($list.find("input[type='checkbox']").length === 0) {
202
+ renderDevices([]);
203
+ }
172
204
  loadedServerId = serverId;
173
205
  loadingPromise = requestJson("unifiNetwork/devices?serverId=" + encodeURIComponent(serverId) + "&deviceType=device")
174
206
  .then(function (devices) {
@@ -176,7 +208,7 @@
176
208
  $status.text("");
177
209
  })
178
210
  .catch(function (xhr) {
179
- $list.empty();
211
+ renderDevices([]);
180
212
  const message = xhr && xhr.responseJSON && xhr.responseJSON.error
181
213
  ? xhr.responseJSON.error
182
214
  : "Unable to load devices.";
@@ -278,7 +310,7 @@
278
310
  <li><code>Restart devices</code> — reboots each selected device (UniFi <code>RESTART</code> action).</li>
279
311
  <li><code>Power cycle PoE ports</code> — power-cycles every port currently delivering PoE on each selected device (UniFi <code>POWER_CYCLE</code> action). Devices with no active PoE ports are skipped.</li>
280
312
  </ul>
281
- <p><b>Devices</b> lists every adopted UniFi Network device. By default switches and access points are pre-selected; gateways, consoles and cloud keys are listed but unchecked. Add or remove devices freely — the selection is saved with the node. Use <code>All</code>/<code>None</code> and the filter box to manage long lists.</p>
313
+ <p><b>Devices</b> lists every adopted UniFi Network device. By default switches and access points are pre-selected; gateways, consoles and cloud keys are listed but unchecked. Add or remove devices freely — the selection is saved with the node. A configured device missing from the current controller response remains checked and is marked as <code>saved; currently unavailable</code>. Use <code>All</code>/<code>None</code> and the filter box to manage long lists.</p>
282
314
 
283
315
  <h3>Input</h3>
284
316
  <ul>
@@ -861,7 +861,20 @@
861
861
  );
862
862
  });
863
863
 
864
- if (currentValue && $deviceId.find("option[value='" + currentValue + "']").length > 0) {
864
+ const hasCurrentValue = currentValue && $deviceId.find("option").filter(function () {
865
+ return String($(this).val() || "") === currentValue;
866
+ }).length > 0;
867
+ if (hasCurrentValue) {
868
+ $deviceId.val(currentValue);
869
+ } else if (currentValue) {
870
+ const savedName = String(node.deviceName || currentValue).trim();
871
+ $deviceId.append(
872
+ $("<option></option>")
873
+ .val(currentValue)
874
+ .text(savedName + " (saved; currently unavailable)")
875
+ .attr("data-device-name", savedName)
876
+ .attr("data-unavailable", "true")
877
+ );
865
878
  $deviceId.val(currentValue);
866
879
  } else {
867
880
  $deviceId.val("");
@@ -1080,6 +1093,7 @@
1080
1093
  });
1081
1094
 
1082
1095
  refreshSelectionSummary();
1096
+ renderDevices([]);
1083
1097
  ensureDefaultServerSelection();
1084
1098
  refreshEditor();
1085
1099
  }
@@ -1146,7 +1160,7 @@
1146
1160
 
1147
1161
  <h3>Configuration</h3>
1148
1162
  <p><b>Connection</b> selects the shared UniFi Protect config node.</p>
1149
- <p><b>Control</b> chooses the Protect device category. <b>Device</b> chooses the specific item. Device selectors are searchable and open with the complete list before filtering.</p>
1163
+ <p><b>Control</b> chooses the Protect device category. <b>Device</b> chooses the specific item. Device selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
1150
1164
  <p><b>Action</b> only shows actions supported by the selected device.</p>
1151
1165
  <p>Additional fields appear only when the selected action needs extra input. For example, events, PTZ presets, live views, or discovered properties.</p>
1152
1166
  <p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and <code>Read Application Info</code> on <code>NVR</code>.</p>
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ function normalizeString(value) {
4
+ return String(value || "").trim();
5
+ }
6
+
7
+ function stripOfflineTag(value) {
8
+ return normalizeString(value)
9
+ .replace(/\s*\(\s*offline\s*\)\s*/ig, " ")
10
+ .replace(/\s+/g, " ")
11
+ .trim();
12
+ }
13
+
14
+ function normalizePresenceMatchBy(value) {
15
+ return normalizeString(value).toLowerCase() === "name" ? "name" : "id";
16
+ }
17
+
18
+ function normalizeClientMatchName(value) {
19
+ const cleaned = stripOfflineTag(value);
20
+ try {
21
+ return cleaned.normalize("NFKC").toLowerCase();
22
+ } catch (error) {
23
+ return cleaned.toLowerCase();
24
+ }
25
+ }
26
+
27
+ function getClientNameCandidates(client) {
28
+ const item = client && typeof client === "object" && !Array.isArray(client)
29
+ ? client
30
+ : {};
31
+ const raw = item.raw && typeof item.raw === "object" && !Array.isArray(item.raw)
32
+ ? item.raw
33
+ : {};
34
+ const values = [
35
+ item.name,
36
+ item.displayName,
37
+ item.display_name,
38
+ item.deviceName,
39
+ item.hostname,
40
+ item.host_name,
41
+ item.last_hostname,
42
+ raw.name,
43
+ raw.displayName,
44
+ raw.display_name,
45
+ raw.deviceName,
46
+ raw.hostname,
47
+ raw.host_name,
48
+ raw.last_hostname
49
+ ];
50
+ const candidates = [];
51
+ const seen = new Set();
52
+
53
+ values.forEach((value) => {
54
+ const cleaned = stripOfflineTag(value);
55
+ const normalized = normalizeClientMatchName(cleaned);
56
+ if (!cleaned || !normalized || seen.has(normalized)) {
57
+ return;
58
+ }
59
+ seen.add(normalized);
60
+ candidates.push(cleaned);
61
+ });
62
+
63
+ return candidates;
64
+ }
65
+
66
+ function isExplicitlyOffline(client) {
67
+ const item = client && typeof client === "object" && !Array.isArray(client)
68
+ ? client
69
+ : {};
70
+ return item.offline === true
71
+ || item.isOnline === false
72
+ || item.online === false
73
+ || item.connected === false
74
+ || item.isConnected === false
75
+ || normalizeString(item.connectionState).toLowerCase() === "disconnected"
76
+ || normalizeString(item.status).toLowerCase() === "offline"
77
+ || normalizeString(item.state).toLowerCase() === "offline";
78
+ }
79
+
80
+ function findActiveClientsByName(clients, targetName) {
81
+ const wanted = normalizeClientMatchName(targetName);
82
+ if (!wanted) {
83
+ return [];
84
+ }
85
+
86
+ return (Array.isArray(clients) ? clients : []).filter((client) => {
87
+ if (!client || typeof client !== "object" || Array.isArray(client) || isExplicitlyOffline(client)) {
88
+ return false;
89
+ }
90
+ return getClientNameCandidates(client)
91
+ .some((candidate) => normalizeClientMatchName(candidate) === wanted);
92
+ });
93
+ }
94
+
95
+ function resolveClientResourceId(client) {
96
+ const item = client && typeof client === "object" && !Array.isArray(client)
97
+ ? client
98
+ : {};
99
+ return [
100
+ item.id,
101
+ item.clientId,
102
+ item.client_id,
103
+ item.user_id,
104
+ item._id,
105
+ item.macAddress,
106
+ item.mac_address,
107
+ item.mac
108
+ ].map(normalizeString).find(Boolean) || "";
109
+ }
110
+
111
+ module.exports = {
112
+ normalizePresenceMatchBy,
113
+ normalizeClientMatchName,
114
+ getClientNameCandidates,
115
+ findActiveClientsByName,
116
+ resolveClientResourceId
117
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",
@@ -66,7 +66,7 @@
66
66
  }
67
67
  },
68
68
  "scripts": {
69
- "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
69
+ "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
70
70
  "registry:discover:network": "node scripts/discover-unifi-network-registry.js",
71
71
  "registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
72
72
  "registry:discover:access": "node scripts/discover-unifi-access-registry.js"