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

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/>
@@ -12,6 +12,7 @@ const {
12
12
  normalizeNetworkCollection
13
13
  } = require("./utils/unifi-network-utils");
14
14
  const {
15
+ decodeScopedDeviceId,
15
16
  encodeScopedDeviceId,
16
17
  getCapabilitiesForType,
17
18
  getCapabilityOptions,
@@ -2912,6 +2913,119 @@ module.exports = function(RED) {
2912
2913
  return attachedClients;
2913
2914
  };
2914
2915
 
2916
+ node.fetchNetworks = async () => {
2917
+ // List the L3 networks/VLANs configured on the controller so the
2918
+ // editor can offer them as watch targets. Uses the legacy
2919
+ // networkconf collection because it includes empty networks too.
2920
+ const sites = await node.fetchSites();
2921
+ const results = await Promise.all(sites.map(async (site) => {
2922
+ const siteId = normalizeString(site && site.id);
2923
+ if (!siteId) {
2924
+ return [];
2925
+ }
2926
+ const siteName = normalizeString(site.name || site.displayName || siteId);
2927
+ let networks = [];
2928
+ try {
2929
+ networks = await fetchLegacySiteCollection(siteId, "/rest/networkconf");
2930
+ } catch (error) {
2931
+ networks = [];
2932
+ }
2933
+
2934
+ return networks
2935
+ .filter((entry) => entry && typeof entry === "object" && !Array.isArray(entry))
2936
+ .map((entry) => {
2937
+ const networkId = normalizeString(entry._id || entry.id);
2938
+ const purpose = normalizeString(entry.purpose);
2939
+ return {
2940
+ id: encodeScopedDeviceId(siteId, networkId) || networkId,
2941
+ networkId,
2942
+ name: normalizeString(entry.name || networkId || "Network"),
2943
+ purpose,
2944
+ isGuest: purpose === "guest",
2945
+ vlan: entry.vlan_enabled ? Number(entry.vlan) : undefined,
2946
+ enabled: entry.enabled !== false,
2947
+ siteId,
2948
+ siteName
2949
+ };
2950
+ })
2951
+ .filter((entry) => entry.networkId);
2952
+ }));
2953
+
2954
+ const dedup = new Map();
2955
+ results.flat().forEach((entry) => {
2956
+ if (!dedup.has(entry.id)) {
2957
+ dedup.set(entry.id, entry);
2958
+ }
2959
+ });
2960
+
2961
+ return Array.from(dedup.values()).sort((a, b) => {
2962
+ return String(a.name).localeCompare(String(b.name));
2963
+ });
2964
+ };
2965
+
2966
+ node.fetchActiveClientsOnNetwork = async (scopedNetworkId, knownNetworkName) => {
2967
+ // Return the currently connected clients that belong to the given
2968
+ // network. Matching is done on the network id, with the network
2969
+ // name as a fallback when the controller omits the id.
2970
+ const scoped = decodeScopedDeviceId(scopedNetworkId);
2971
+ const siteId = normalizeString(scoped.siteId);
2972
+ const wantedNetworkId = normalizeString(scoped.resourceId);
2973
+ if (!siteId || !wantedNetworkId) {
2974
+ throw new Error("Network selection is invalid. Re-select the network from the editor.");
2975
+ }
2976
+
2977
+ // Resolve the watched network name (used by the name-based fallback
2978
+ // on controllers that omit the network id on stations). The caller
2979
+ // can pass it to skip this per-poll lookup.
2980
+ let wantedNetworkName = normalizeString(knownNetworkName);
2981
+ if (!wantedNetworkName) {
2982
+ try {
2983
+ const networks = await fetchLegacySiteCollection(siteId, "/rest/networkconf");
2984
+ const matched = networks.find((entry) => normalizeString(entry && (entry._id || entry.id)) === wantedNetworkId);
2985
+ wantedNetworkName = normalizeString(matched && matched.name);
2986
+ } catch (error) {
2987
+ wantedNetworkName = "";
2988
+ }
2989
+ }
2990
+
2991
+ const stations = await fetchLegacySiteCollection(siteId, "/stat/sta");
2992
+ const normalizedWantedName = wantedNetworkName.toLowerCase();
2993
+
2994
+ return stations
2995
+ .filter((station) => station && typeof station === "object" && !Array.isArray(station))
2996
+ .filter((station) => {
2997
+ const stationNetworkId = normalizeString(station.network_id || station.networkId);
2998
+ if (stationNetworkId) {
2999
+ return stationNetworkId === wantedNetworkId;
3000
+ }
3001
+ const stationNetworkName = normalizeString(station.network).toLowerCase();
3002
+ return normalizedWantedName !== "" && stationNetworkName === normalizedWantedName;
3003
+ })
3004
+ .map((station) => {
3005
+ const mac = normalizeString(station.mac || station.macAddress);
3006
+ const name = stripOfflineTag(firstNonEmptyString([
3007
+ station.name,
3008
+ station.hostname,
3009
+ station.display_name,
3010
+ mac
3011
+ ]));
3012
+ return {
3013
+ mac,
3014
+ clientId: normalizeString(station.user_id || station._id || mac),
3015
+ name: name || mac || "Client",
3016
+ network: normalizeString(station.network) || wantedNetworkName,
3017
+ networkId: normalizeString(station.network_id || station.networkId) || wantedNetworkId,
3018
+ networkName: wantedNetworkName || normalizeString(station.network),
3019
+ essid: normalizeString(station.essid),
3020
+ isGuest: station.is_guest === true,
3021
+ isWired: station.is_wired === true,
3022
+ ipAddress: firstNonEmptyString([station.ip, station.last_ip, station.fixed_ip]),
3023
+ siteId
3024
+ };
3025
+ })
3026
+ .filter((client) => client.mac);
3027
+ };
3028
+
2915
3029
  node.addClient = (client) => {
2916
3030
  if (!client) {
2917
3031
  return;
@@ -3154,6 +3268,26 @@ module.exports = function(RED) {
3154
3268
  }
3155
3269
  });
3156
3270
 
3271
+ RED.httpAdmin.get("/unifiNetwork/networks", RED.auth.needsPermission("unifi-network-config.read"), async (req, res) => {
3272
+ try {
3273
+ const serverId = String(req.query.serverId || "").trim();
3274
+ if (!serverId) {
3275
+ res.status(400).json({ error: "Missing serverId" });
3276
+ return;
3277
+ }
3278
+
3279
+ const server = RED.nodes.getNode(serverId);
3280
+ if (!server || typeof server.fetchNetworks !== "function") {
3281
+ res.status(404).json({ error: "Configuration node not found" });
3282
+ return;
3283
+ }
3284
+
3285
+ res.json(await server.fetchNetworks());
3286
+ } catch (error) {
3287
+ res.status(500).json({ error: error.message });
3288
+ }
3289
+ });
3290
+
3157
3291
  RED.httpAdmin.get("/unifiNetwork/observer-metrics", RED.auth.needsPermission("unifi-network-config.read"), async (req, res) => {
3158
3292
  try {
3159
3293
  const serverId = String(req.query.serverId || "").trim();
@@ -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,95 @@
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">
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>
512
690
  </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">
516
- </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. Leaves are detected quickly.</p>
722
+
723
+ <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
724
 
540
725
  <h3>Input</h3>
541
726
  <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>
727
+ <li><b>Presence mode:</b> no input pin; checks run automatically at startup and on the configured cadence.</li>
728
+ <li><b>Network mode:</b> any incoming message forces an immediate poll between intervals.</li>
543
729
  </ul>
544
730
 
545
731
  <h3>Outputs</h3>
732
+ <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
733
  <dl class="message-properties">
547
- <dt>Output 1 — presence</dt>
734
+ <dt>Output 1 — result</dt>
548
735
  <dd>Emitted when the debounced presence state changes.</dd>
549
736
  <dt class="optional">msg.payload</dt>
550
737
  <dd><code>true</code> when the client is present, <code>false</code> when absent.</dd>
@@ -592,4 +779,13 @@
592
779
  "payload": null,
593
780
  "error": { "message": "Presence polling failed" }
594
781
  }</code></pre>
595
- </script>
782
+ </script>
783
+
784
+ <style>
785
+ .unifi-presence-network-status {
786
+ margin-top: 4px;
787
+ margin-left: 102px;
788
+ font-size: 0.85em;
789
+ color: var(--red-ui-text-color-error, #b30000);
790
+ }
791
+ </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.0.11",
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": {