node-red-contrib-unifi-ultimate 1.0.8 → 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
@@ -17,7 +17,7 @@ Control and monitor your **UniFi Network**, **UniFi Protect**, and **UniFi Acces
17
17
 
18
18
  [View Changelog](CHANGELOG.md)
19
19
 
20
- <a href="https://www.youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ">
20
+ <a href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv">
21
21
  <img src="resources/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" align="absmiddle">
22
22
  Watch news and tutorials on YouTube
23
23
  <br/>
@@ -50,7 +50,7 @@ In Node-RED:
50
50
  7. Send any message into the node to run the action.
51
51
 
52
52
  > **Tip:** For most actions, the incoming message is just a trigger — the node uses the device and action you configured in the editor.
53
- > The only exception is **Control POE** with the *POE controlled by incoming message* action: send `true` to turn PoE on and `false` to turn it off.
53
+ > The only exception is **Clients Control** with a _controlled by msg.payload_ action: send `true` to enable (PoE or the port) and `false` to disable it, on every target in its list.
54
54
 
55
55
  > **Custom port:** Each config node has an optional **Port** field. Leave it empty to use the default (`443` for Network/Protect, `12445` for Access). Set it when your controller listens on a custom port — for example a **UniFi OS server** that uses `11443`. A port written directly in the controller address (`host:port`) takes precedence over this field.
56
56
 
@@ -81,9 +81,11 @@ Things you can do:
81
81
  - Read CPU usage, memory, and uptime from a switch or access point.
82
82
  - Read the temperature of a switch (where supported).
83
83
  - Restart a UniFi device.
84
- - Power-cycle or turn on/off a PoE port.
85
- - Let the PoE node automatically find which port a client is connected to.
84
+ - Control a **list of clients/ports** at once with the **Clients Control** node: pick targets by switch+port or by client (its uplink switch/port is resolved automatically) and apply one action to all of them, getting a single summary message back.
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
+ - Let **Clients Control** automatically find which switch port a client is connected to.
86
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)**.
87
89
 
88
90
  <br/>
89
91
  <br/>
@@ -139,26 +141,26 @@ Things you can do:
139
141
 
140
142
  Every node has **two outputs**:
141
143
 
142
- | Output | When it fires |
143
- | ------ | ------------- |
144
+ | Output | When it fires |
145
+ | -------------- | ---------------------------------------------------------------------------- |
144
146
  | **1 — result** | The action completed successfully. The result is available in `msg.payload`. |
145
- | **2 — error** | Something went wrong (connection problem, timeout, unsupported action). |
147
+ | **2 — error** | Something went wrong (connection problem, timeout, unsupported action). |
146
148
 
147
149
  When an error occurs, the node status turns red and the error message comes out of the second output. Connect it to a **debug** node to see what happened, or wire it to any notification logic in your flow.
148
150
 
149
- **Repeat periodically** — for read actions, you can tick *Emit periodically* in the node editor to have the node send the result automatically at a fixed interval, without needing an Inject node. The **Presence Detection** node offers a similar **Resend (s)** field: set it above `0` to re-emit the last known presence value on that cadence (even when unchanged). Resent messages carry `msg.eventName = "repeat"` so you can tell them apart from real state changes; leave it at `0` to disable.
151
+ **Repeat periodically** — for read actions, you can tick _Emit periodically_ in the node editor to have the node send the result automatically at a fixed interval, without needing an Inject node. The **Presence Detection** node offers a similar **Resend (s)** field: set it above `0` to re-emit the last known presence value on that cadence (even when unchanged). Resent messages carry `msg.eventName = "repeat"` so you can tell them apart from real state changes; leave it at `0` to disable.
150
152
 
151
153
  ## Example Flows
152
154
 
153
155
  Import from `examples/`:
154
156
 
155
- | Flow file | What it demonstrates |
156
- | --------- | -------------------- |
157
- | [examples/unifi-protect-info.json](examples/unifi-protect-info.json) | Read the state of a Protect camera |
158
- | [examples/unifi-protect-sensor-observe.json](examples/unifi-protect-sensor-observe.json) | Receive sensor events (motion, temperature, humidity, …) |
159
- | [examples/unifi-protect-camera-actions.json](examples/unifi-protect-camera-actions.json) | Take snapshots, move PTZ, show doorbell messages |
160
- | [examples/unifi-access-door-control.json](examples/unifi-access-door-control.json) | Door state, remote unlock, temporary lock rule |
161
- | [examples/unifi-access-intercom-doorbell.json](examples/unifi-access-intercom-doorbell.json) | Intercom — receive ring, trigger and cancel doorbell |
157
+ | Flow file | What it demonstrates |
158
+ | -------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
159
+ | [examples/unifi-protect-info.json](examples/unifi-protect-info.json) | Read the state of a Protect camera |
160
+ | [examples/unifi-protect-sensor-observe.json](examples/unifi-protect-sensor-observe.json) | Receive sensor events (motion, temperature, humidity, …) |
161
+ | [examples/unifi-protect-camera-actions.json](examples/unifi-protect-camera-actions.json) | Take snapshots, move PTZ, show doorbell messages |
162
+ | [examples/unifi-access-door-control.json](examples/unifi-access-door-control.json) | Door state, remote unlock, temporary lock rule |
163
+ | [examples/unifi-access-intercom-doorbell.json](examples/unifi-access-intercom-doorbell.json) | Intercom — receive ring, trigger and cancel doorbell |
162
164
 
163
165
  ## Notes
164
166
 
@@ -178,4 +180,4 @@ Import from `examples/`:
178
180
  [license-image]: https://img.shields.io/badge/license-MIT-green.svg
179
181
  [license-url]: https://opensource.org/licenses/MIT
180
182
  [youtube-image]: https://img.shields.io/badge/YouTube-Subscribe-red?logo=youtube&logoColor=white
181
- [youtube-url]: https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ
183
+ [youtube-url]: https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
  <script type="text/javascript">
4
5
  RED.nodes.registerType("unifi-access-config", {
@@ -74,7 +75,7 @@
74
75
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-access-black.svg" alt="UniFi Access logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
75
76
  </div>
76
77
  <div class="form-row unifi-ultimate-hero">
77
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
78
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
78
79
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
79
80
  <span>Youtube Tutorials</span>
80
81
  </a>
@@ -105,7 +106,7 @@
105
106
  </script>
106
107
 
107
108
  <script type="text/html" data-help-name="unifi-access-config">
108
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
109
+ <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>
109
110
 
110
111
  <p>Shared connection for UniFi Access nodes.</p>
111
112
 
@@ -119,4 +120,4 @@
119
120
  <h3>Usage</h3>
120
121
  <p>This config node is used by UniFi Access Device nodes for API requests and live notification events.</p>
121
122
  <p>All Access API calls and notification channels are managed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive fan-out updates.</p>
122
- </script>
123
+ </script>
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
5
  <script type="text/javascript">
@@ -1079,7 +1080,7 @@
1079
1080
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-access-black.svg" alt="UniFi Access logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
1080
1081
  </div>
1081
1082
  <div class="form-row unifi-ultimate-hero">
1082
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
1083
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
1083
1084
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
1084
1085
  <span>Youtube Tutorials</span>
1085
1086
  </a>
@@ -1128,7 +1129,7 @@
1128
1129
  </script>
1129
1130
 
1130
1131
  <script type="text/html" data-help-name="unifi-access-device">
1131
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
1132
+ <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>
1132
1133
 
1133
1134
  <p>Use this node to execute a configured UniFi Access action or listen for live Access events.</p>
1134
1135
 
@@ -1201,4 +1202,4 @@
1201
1202
  "payload": null,
1202
1203
  "error": { "message": "Request timed out" }
1203
1204
  }</code></pre>
1204
- </script>
1205
+ </script>
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
5
  <script type="text/javascript">
@@ -87,7 +88,7 @@
87
88
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
88
89
  </div>
89
90
  <div class="form-row unifi-ultimate-hero">
90
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
91
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
91
92
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
92
93
  <span>Youtube Tutorials</span>
93
94
  </a>
@@ -122,7 +123,7 @@
122
123
  </script>
123
124
 
124
125
  <script type="text/html" data-help-name="unifi-network-config">
125
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
126
+ <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>
126
127
 
127
128
  <p>Shared connection for UniFi Network nodes.</p>
128
129
 
@@ -139,4 +140,4 @@
139
140
  <p>All UniFi Network requests are executed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive updates/events from here.</p>
140
141
  <p>Event streams and observation timers are centralized here (shared scheduler per config node), so runtime nodes do not open their own websocket channels or polling timers.</p>
141
142
  <p>The node uses the official Network integration API where available and falls back automatically to local legacy endpoints when the official <code>/v1</code> routes are not exposed (for example on older local releases). For switch port/client mapping and PoE enable/disable, legacy endpoints are also used where needed.</p>
142
- </script>
143
+ </script>
@@ -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();
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
5
  <script type="text/javascript">
@@ -1178,7 +1179,7 @@
1178
1179
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
1179
1180
  </div>
1180
1181
  <div class="form-row unifi-ultimate-hero">
1181
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
1182
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
1182
1183
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
1183
1184
  <span>Youtube Tutorials</span>
1184
1185
  </a>
@@ -1278,6 +1279,7 @@
1278
1279
  padding: 10px 12px 2px;
1279
1280
  margin-bottom: 14px;
1280
1281
  }
1282
+
1281
1283
  .unifi-poe-picker-title {
1282
1284
  font-size: 0.78em;
1283
1285
  text-transform: uppercase;
@@ -1285,11 +1287,13 @@
1285
1287
  opacity: 0.65;
1286
1288
  margin-bottom: 8px;
1287
1289
  }
1290
+
1288
1291
  .unifi-poe-targets-panel {
1289
1292
  display: inline-block;
1290
1293
  width: 70%;
1291
1294
  vertical-align: top;
1292
1295
  }
1296
+
1293
1297
  .unifi-poe-target-list {
1294
1298
  max-height: 160px;
1295
1299
  overflow-y: auto;
@@ -1298,32 +1302,38 @@
1298
1302
  padding: 4px 6px;
1299
1303
  background: var(--red-ui-form-input-background, #fff);
1300
1304
  }
1305
+
1301
1306
  #unifi-poe-target-list .unifi-poe-target-row {
1302
1307
  display: flex;
1303
1308
  align-items: center;
1304
1309
  gap: 8px;
1305
1310
  padding: 3px 2px;
1306
1311
  }
1312
+
1307
1313
  #unifi-poe-target-list .unifi-poe-target-name {
1308
1314
  flex: 1 1 auto;
1309
1315
  overflow: hidden;
1310
1316
  text-overflow: ellipsis;
1311
1317
  white-space: nowrap;
1312
1318
  }
1319
+
1313
1320
  #unifi-poe-target-list .unifi-poe-target-meta {
1314
1321
  flex: 0 0 auto;
1315
1322
  opacity: 0.6;
1316
1323
  font-size: 0.85em;
1317
1324
  }
1325
+
1318
1326
  #unifi-poe-target-list .unifi-poe-target-remove {
1319
1327
  flex: 0 0 auto;
1320
1328
  color: var(--red-ui-text-color-error, #b30000);
1321
1329
  text-decoration: none;
1322
1330
  }
1331
+
1323
1332
  .unifi-poe-target-empty {
1324
1333
  opacity: 0.6;
1325
1334
  padding: 6px 2px;
1326
1335
  }
1336
+
1327
1337
  .unifi-poe-target-footer {
1328
1338
  display: flex;
1329
1339
  justify-content: flex-end;
@@ -1334,9 +1344,9 @@
1334
1344
  </style>
1335
1345
 
1336
1346
  <script type="text/html" data-help-name="unifi-network-control-poe">
1337
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
1347
+ <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>
1338
1348
 
1339
- <p>Controls PoE on a list of UniFi switch ports. Build the list by picking a target (a switch port, or a client whose uplink switch/port is resolved automatically) and clicking <b>Add to list</b>. When triggered, the configured action runs on every target in the list and a single summary message is emitted.</p>
1349
+ <p>Controls PoE, or enables/disables the whole switch port, on a list of UniFi switch ports. Build the list by picking a target (a switch port, or a client whose uplink switch/port is resolved automatically) and clicking <b>Add to list</b>. When triggered, the configured action runs on every target in the list and a single summary message is emitted.</p>
1340
1350
 
1341
1351
  <h3>Configuration</h3>
1342
1352
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
@@ -1455,8 +1465,8 @@
1455
1465
  }</code></pre>
1456
1466
  <p>Example output (pin 2 — error):</p>
1457
1467
  <pre><code>{
1458
- "topic": "POE Soffitta Port 2",
1468
+ "topic": "Clients Control",
1459
1469
  "payload": null,
1460
- "error": { "message": "Missing switch device id." }
1470
+ "error": { "message": "No client targets configured." }
1461
1471
  }</code></pre>
1462
- </script>
1472
+ </script>
@@ -1209,7 +1209,7 @@
1209
1209
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
1210
1210
  </div>
1211
1211
  <div class="form-row unifi-ultimate-hero">
1212
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
1212
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
1213
1213
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
1214
1214
  <span>Youtube Tutorials</span>
1215
1215
  </a>
@@ -1258,7 +1258,7 @@
1258
1258
  </script>
1259
1259
 
1260
1260
  <script type="text/html" data-help-name="unifi-network-device">
1261
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
1261
+ <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>
1262
1262
 
1263
1263
  <p>Use this node to execute a configured UniFi Network action on a selected site, UniFi device, or client.</p>
1264
1264
 
@@ -1338,4 +1338,4 @@
1338
1338
  "payload": null,
1339
1339
  "error": { "message": "Request timed out" }
1340
1340
  }</code></pre>
1341
- </script>
1341
+ </script>
@@ -1,38 +1,101 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
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
+
5
20
  RED.nodes.registerType("unifi-network-presence", {
6
21
  category: "Unifi Ultimate",
7
22
  color: "#CFE8FB",
8
23
  defaults: {
9
24
  name: { value: "" },
10
25
  server: { value: "", type: "unifi-network-config", required: true },
11
- 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
+ },
12
34
  deviceName: { value: "" },
13
35
  pollInterval: { value: 10, required: true, validate: RED.validators.number() },
14
36
  onlineHysteresis: { value: 15, required: true, validate: RED.validators.number() },
15
37
  offlineHysteresis: { value: 30, required: true, validate: RED.validators.number() },
16
- 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() }
17
50
  },
18
51
  inputs: 0,
19
52
  outputs: 2,
20
53
  icon: "unifi-u-logo-light-network.svg",
21
54
  paletteLabel: "Presence Detection",
22
- outputLabels: ["presence", "error"],
55
+ outputLabels: ["result", "error"],
23
56
  label: function () {
24
- 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
+ }
25
74
  },
26
75
  oneditprepare: function () {
27
76
  const node = this;
28
77
  const $name = $("#node-input-name");
29
78
  const $server = $("#node-input-server");
79
+ const $watchBy = $("#node-input-watchBy");
30
80
  const $clientId = $("#node-input-clientId");
31
81
  const $deviceName = $("#node-input-deviceName");
32
82
  const $refresh = $("#node-input-refreshClients");
33
83
  const $clientRow = $clientId.closest(".form-row");
34
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");
35
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
+ }
36
99
 
37
100
  function hasSelection($field) {
38
101
  const value = String($field.val() || "").trim();
@@ -41,10 +104,71 @@
41
104
 
42
105
  function syncProgressiveRows() {
43
106
  const hasServer = hasSelection($server);
44
- 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
+ }
45
118
 
46
- $clientRow.toggle(hasServer);
47
- $advancedRow.toggle(hasServer && hasClient);
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
+ }
146
+
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
+ });
48
172
  }
49
173
 
50
174
  function requestJson(url) {
@@ -445,7 +569,11 @@
445
569
  if (suspendChangeHandling) {
446
570
  return;
447
571
  }
448
- loadClients();
572
+ if (currentMode() === "network") {
573
+ loadNetworks(false);
574
+ } else {
575
+ loadClients();
576
+ }
449
577
  });
450
578
 
451
579
  $clientId.on("change", function () {
@@ -466,11 +594,37 @@
466
594
  loadClients();
467
595
  });
468
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
+
469
618
  ensureDefaultServerSelection();
470
619
  makeSelectSearchable($clientId, "Search clients");
471
620
  refreshSummary();
472
- $refresh.find("i").addClass("fa-spin");
473
- loadClients();
621
+ syncProgressiveRows();
622
+ if (currentMode() === "network") {
623
+ loadNetworks(false);
624
+ } else {
625
+ $refresh.find("i").addClass("fa-spin");
626
+ loadClients();
627
+ }
474
628
  }
475
629
  });
476
630
  </script>
@@ -480,7 +634,7 @@
480
634
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
481
635
  </div>
482
636
  <div class="form-row unifi-ultimate-hero">
483
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
637
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
484
638
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
485
639
  <span>Youtube Tutorials</span>
486
640
  </a>
@@ -489,61 +643,95 @@
489
643
  <label for="node-input-server"><i class="fa fa-cog"></i> Connection</label>
490
644
  <input type="text" id="node-input-server">
491
645
  </div>
492
- <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">
493
654
  <label for="node-input-clientId"><i class="fa fa-wifi"></i> Client</label>
494
655
  <select id="node-input-clientId" style="width:62%;"></select>
495
656
  <a href="#" id="node-input-refreshClients" class="editor-button" style="margin-left:6px;" title="Refresh clients" aria-label="Refresh clients">
496
657
  <i class="fa fa-refresh"></i>
497
658
  </a>
498
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>
499
668
  <div id="node-row-advanced" class="unifi-ultimate-advanced">
500
669
  <div class="form-row">
501
670
  <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
502
671
  <input type="text" id="node-input-name" placeholder="Node name">
503
672
  </div>
504
- <div class="form-row">
505
- <label for="node-input-pollInterval"><i class="fa fa-repeat"></i> Poll (s)</label>
506
- <input type="text" id="node-input-pollInterval" placeholder="10">
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>
507
690
  </div>
508
- <div class="form-row">
509
- <label for="node-input-onlineHysteresis"><i class="fa fa-hourglass-start"></i> Connect Hysteresis (s)</label>
510
- <input type="text" id="node-input-onlineHysteresis" placeholder="15">
511
- </div>
512
- <div class="form-row">
513
- <label for="node-input-offlineHysteresis"><i class="fa fa-hourglass-half"></i> Hysteresis (s)</label>
514
- <input type="text" id="node-input-offlineHysteresis" placeholder="30">
515
- </div>
516
- <div class="form-row">
517
- <label for="node-input-repeatInterval"><i class="fa fa-clock-o"></i> Resend (s)</label>
518
- <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>
519
696
  </div>
520
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">
521
701
  </div>
522
702
  </script>
523
703
 
524
704
  <script type="text/html" data-help-name="unifi-network-presence">
525
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
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>
526
706
 
527
- <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>
528
708
 
529
709
  <h3>Configuration</h3>
530
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>
531
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>
532
- <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>
533
- <p><b>Connect Hysteresis (s)</b> delays the <code>true</code> output so brief reconnects do not flap.</p>
534
- <p><b>Hysteresis (s)</b> delays the <code>false</code> output to avoid flapping when the client disconnects briefly.</p>
535
- <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>
536
- <p>Request timeout is handled automatically by the node.</p>
537
- <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>
538
724
 
539
725
  <h3>Input</h3>
540
726
  <ul>
541
- <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>
542
729
  </ul>
543
730
 
544
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>
545
733
  <dl class="message-properties">
546
- <dt>Output 1 — presence</dt>
734
+ <dt>Output 1 — result</dt>
547
735
  <dd>Emitted when the debounced presence state changes.</dd>
548
736
  <dt class="optional">msg.payload</dt>
549
737
  <dd><code>true</code> when the client is present, <code>false</code> when absent.</dd>
@@ -592,3 +780,12 @@
592
780
  "error": { "message": "Presence polling failed" }
593
781
  }</code></pre>
594
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);
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
5
  <script type="text/javascript">
@@ -77,7 +78,7 @@
77
78
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-protect-black.svg" alt="UniFi Protect logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
78
79
  </div>
79
80
  <div class="form-row unifi-ultimate-hero">
80
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
81
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
81
82
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
82
83
  <span>Youtube Tutorials</span>
83
84
  </a>
@@ -112,7 +113,7 @@
112
113
  </script>
113
114
 
114
115
  <script type="text/html" data-help-name="unifi-protect-config">
115
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
116
+ <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>
116
117
 
117
118
  <p>Shared connection for UniFi Protect nodes.</p>
118
119
 
@@ -127,4 +128,4 @@
127
128
  <h3>Usage</h3>
128
129
  <p>This config node is used by UniFi Protect Device nodes for API requests and live device/event updates.</p>
129
130
  <p>All Protect API calls and websocket streams are managed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive broadcast updates.</p>
130
- </script>
131
+ </script>
@@ -1,4 +1,5 @@
1
- <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
1
+ <link rel="stylesheet" type="text/css"
2
+ href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
3
 
3
4
 
4
5
  <script type="text/javascript">
@@ -1090,7 +1091,7 @@
1090
1091
  <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-protect-black.svg" alt="UniFi Protect logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
1091
1092
  </div>
1092
1093
  <div class="form-row unifi-ultimate-hero">
1093
- <a class="unifi-ultimate-youtube-link" href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" target="_blank" rel="noopener noreferrer">
1094
+ <a class="unifi-ultimate-youtube-link" href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer">
1094
1095
  <img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18">
1095
1096
  <span>Youtube Tutorials</span>
1096
1097
  </a>
@@ -1139,7 +1140,7 @@
1139
1140
  </script>
1140
1141
 
1141
1142
  <script type="text/html" data-help-name="unifi-protect-device">
1142
- <p><a href="https://www.youtube.com/watch?v=ZOq7M5mgUBk&list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ" 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>
1143
+ <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>
1143
1144
 
1144
1145
  <p>Use this node to execute a configured UniFi Protect action or listen for live Protect events.</p>
1145
1146
 
@@ -1216,4 +1217,4 @@
1216
1217
  "payload": null,
1217
1218
  "error": { "message": "Request timed out" }
1218
1219
  }</code></pre>
1219
- </script>
1220
+ </script>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.0.8",
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": {
@@ -63,4 +63,4 @@
63
63
  "bugs": {
64
64
  "url": "https://github.com/Supergiovane/node-red-contrib-unifi-ultimate/issues"
65
65
  }
66
- }
66
+ }