node-red-contrib-unifi-ultimate 1.1.23 → 1.1.25

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
@@ -19,6 +19,7 @@ UniFi Ultimate brings the full power of the Ubiquiti UniFi ecosystem to Node-RED
19
19
  [![NPM downloads total][npm-downloads-total-image]][npm-url]
20
20
  [![MIT License][license-image]][license-url]
21
21
  [![Youtube][youtube-image]][youtube-url]
22
+ [![Website](https://img.shields.io/badge/Website-maxsupervibe.com-0d4c70)](https://www.maxsupervibe.com)
22
23
 
23
24
  <p align="center">
24
25
  <img src="img/readmemain.png" alt="UniFi Ultimate for Node-RED — Max Supervibe" width="70%">
@@ -42,191 +43,15 @@ In Node-RED:
42
43
  3. Search for `node-red-contrib-unifi-ultimate`.
43
44
  4. Install the package.
44
45
 
45
- ## Quick Start
46
+ ## 📘 Documentation
46
47
 
47
- 1. Add a config node for your UniFi product: **Unifi Network Config**, **Unifi Protect Config**, or **Unifi Access Config**.
48
- 2. Enter your UniFi controller address and login credentials.
49
- 3. Add the matching node to your flow.
50
- 4. Select the device you want to control or monitor.
51
- 5. Select the action.
52
- 6. Click **Deploy**.
53
- 7. Send any message into the node to run the action.
48
+ The full documentation is on **[maxsupervibe.com](https://www.maxsupervibe.com/docs/unifi-ultimate/)**, together with the help of every other Max Supervibe node.
54
49
 
55
- > **Tip:** For most actions, the incoming message is just a trigger — the node uses the device and action you configured in the editor.
56
- > 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.
57
-
58
- > **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.
59
-
60
- > **Self-signed certificates:** Each config node has an **Allow self-signed certificate** option, enabled by default. UniFi controllers almost always present a self-signed certificate, so keep it checked for UniFi OS / UXG setups. Uncheck it only if your controller uses a certificate signed by a trusted certificate authority and you want strict verification.
61
-
62
- > **Optional local account:** Protect, Network, and Access config nodes include **Local User** and **Local Password**, stored in Node-RED's credential store. Protect uses this shared account for LPR text, recorded-event searches, and event images. Network Internet/WAN monitors use the local account when the controller rejects the API key on local endpoints. Access stores the fields but its actions, including door monitoring, use the API token. Leave both fields empty when they are not needed. The API key/token remains required. Protect history callers can still supply a complete per-request account to override the configured one.
63
-
64
- ### Guided setup and monitoring
65
-
66
- Every connection has a **Verify Connection** button. It tests the values in the editor from the Node-RED host and explains reachability, certificate, authentication and permission failures. It also checks complete local credentials where used. The editor keeps inline notes minimal; detailed requirements and output examples are in the HTML help.
67
-
68
- | Node / selection | New action or option | Result |
69
- | --- | --- | --- |
70
- | Protect / Camera | **Receive Events with Photo** | Detection in `msg.payload`, the exact event's recorded image in `msg.image`, MIME type in `msg.imageType`. |
71
- | Protect / Camera | **Read Recent Detections** | Inject-triggered event array, filter by detection type and time window (default 24 hours), up to 100 results. |
72
- | Protect / LPR, photos, history | **Known plates** | One `PLATE = friendly name` per line; LPR adds `msg.knownPlate` and optional `msg.plateName`, while photo/history rows include named `plates`. |
73
- | Access / Door | **Door Open Too Long** | `doorOpenTooLong` after the threshold (default 120 seconds), followed by `doorClosed`. Requires a physical DPS and token permission `view:space`. |
74
- | Network / UniFi Device | **Device Offline / Restored** | `deviceOffline` after a confirmed outage (default 60 seconds), then `deviceRestored`. |
75
- | Network / Site | **Monitor Internet and WAN** | `internetOffline` / `internetRestored`, plus native `wanFailover`, `wanActive`, `wanInactive` where supported. |
76
-
77
- All monitoring actions start on deploy, share polling on their connection (using the shortest interval for the same target) and emit one alert/recovery per transition. A controller error or unknown state goes to output 2 and resets the pending delay; it never becomes a fabricated device or Internet outage. Initial healthy state is silent. An initial open/offline state starts timing from observation, and monitoring restarts after redeploy. Polling adds up to one interval plus request time to detection. Plate names are ordinary flow settings and are included in exports; account credentials are kept in Node-RED's credential store.
78
-
79
- Protect event photos/history require the configured local account and retained recordings. Photos are retrieved by exact event ID, with brief retries for delayed availability. The node does not substitute a current camera snapshot. History metadata in `msg.details.history` includes `from`, `to`, `hasMore`, `nextOffset` and `stoppedReason`; a search scans at most 1,000 source rows and reports incomplete or repeated-page results. The time window is recalculated for each trigger, including when using **History offset**.
80
-
81
- Network Internet monitoring needs a UniFi gateway and local API support. It uses the controller's **WWW** health; one inactive WAN is not evidence of a total Internet outage. WAN transitions use native `EVT_GW_WANTransition` events for the selected site and identify the actual reported interface, without guessing which WAN is primary. The last 100 source events are checked per poll, so busy sites or long interruptions can leave gaps. Unsupported WAN event endpoints are reported separately while Internet health monitoring continues. These local APIs depend on controller version and permissions.
82
-
83
- Import [guided monitoring examples](examples/unifi-guided-monitoring.json), select your connections and devices, then deploy. Each action is wired to result/error Debug nodes. See the HTML help for example messages and the details of each option.
84
-
85
- <br/>
86
- <br/>
87
- <p align="left">
88
- <a href="https://ui.com/switching">
89
- <img src="nodes/readme-assets/UniFi%20Network/UniFi%20Network%20Black.svg" alt="UniFi Network logo" width="430">
90
- </a>
91
- </p>
92
-
93
- Use **Network** nodes to work with:
94
-
95
- - sites
96
- - UniFi devices such as switches and access points
97
- - connected clients such as phones, computers, and IoT devices
98
- - switch ports and PoE control
99
- - client presence detection
100
-
101
- Things you can do:
102
-
103
- - Check whether a device or phone is connected to your network.
104
- - Track presence either by the exact UniFi client ID or by client name; name matching tolerates private/rotating MAC addresses by resolving the active client again on every poll.
105
- - Re-send the current presence state at a fixed interval with the Presence node's **Resend** field (e.g. to keep a dashboard or home-automation system in sync).
106
- - Count how many clients are currently online.
107
- - List the site's configured networks, Wi-Fi broadcasts, and WAN interfaces.
108
- - List VPN servers and site-to-site VPN tunnels.
109
- - List existing guest Wi-Fi vouchers.
110
- - Create guest Wi-Fi vouchers.
111
- - Read CPU usage, memory, and uptime from a switch or access point.
112
- - Read the temperature of a switch (where supported).
113
- - Restart a UniFi device.
114
- - 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.
115
- - 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`.
116
- - Let **Clients Control** automatically find which switch port a client is connected to.
117
- - Restart a whole list of switches/APs at once, or power-cycle all their active PoE ports, with the **Restart** node.
118
- - 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)**.
119
-
120
- <br/>
121
- <br/>
122
- <p align="left">
123
- <a href="https://store.ui.com/us/en/products/uvc-g5-pro">
124
- <img src="nodes/readme-assets/UniFi%20Protect/UniFi%20Protect%20Black.svg" alt="UniFi Protect logo" width="430">
125
- </a>
50
+ <p align="left" style="font-size:2.25rem;font-weight:700;line-height:1.9;">
51
+ <a href="https://www.maxsupervibe.com/docs/unifi-ultimate/">📘 Go to the documentation</a>
126
52
  </p>
127
53
 
128
- Use **Protect** nodes to work with:
129
-
130
- - cameras
131
- - sensors (motion, contact, temperature, humidity, leak)
132
- - lights
133
- - chimes
134
- - viewers
135
- - bridges and Link Stations
136
- - alarm hubs and key fobs
137
- - sirens, relays, and speakers
138
- - NVR
139
-
140
- Things you can do:
141
-
142
- - Receive motion, ring, contact, tamper, leak, and low-battery alerts.
143
- - Read recognized license plates (LPR) from compatible cameras as text in `msg.payload`.
144
- - Read the current state of a camera or sensor.
145
- - Take a camera snapshot.
146
- - Control PTZ cameras (move to preset, start/stop patrol).
147
- - Display a custom message on a doorbell screen.
148
- - Switch a viewer to a different live feed.
149
- - Monitor bridges, Link Stations, alarm hubs, key fobs, sirens, relays, and speakers.
150
- - Play or stop a siren, control relay outputs, and test speaker or siren sound.
151
- - Read and select Protect Arm Profiles, then arm or disarm the local Alarm Manager from the NVR control.
152
- - Trigger Alarm Manager alarms by webhook ID from the NVR control.
153
- - Follow ONVIF camera digital inputs and Alarm Hub enclosure tamper.
154
- - Send point of sale transactions from `msg.payload` to overlay them on camera footage.
155
- - Poll Alarm Hub armed state or NVR local alarm status with **Read Alarm State**, or follow device updates with **Receive Events → Armed / Alarm status (local)**. These are separate alarm sources; the NVR arm commands require the local Alarm Manager. See [the polling example](examples/unifi-protect-alarm-state.json).
156
-
157
- ### Read license plates (LPR)
158
-
159
- 1. Enable license plate recognition on a compatible camera in UniFi Protect.
160
- 2. In the **PROTECT** node, select **Camera**, the camera, **Receive Events**, then **License Plate (LPR)**.
161
- 3. Open the shared **Protect connection** and enter its optional **Local User** and **Local Password** for a local UniFi OS account with permission to view that camera's recordings. Keep the API key configured there. The account is shared by every Protect node using that connection.
162
- 4. Deploy. Each recognized plate arrives as a string such as `"AB123CD"` in `msg.payload`, with `msg.eventName = "licensePlate"`.
163
-
164
- `msg.details.lpr` contains the plate text, event ID, timestamps, and OCR confidence (0–100) when available. The original event is preserved in `msg.details.raw.event`. The first available text is emitted immediately, even at low confidence. Multiple plates are emitted separately; corrected text or a confidence increase produces another message. Identical readings and lower confidence for previously emitted text are suppressed. Every reading carries the plate string in `msg.payload`, including higher-confidence readings of unchanged text. `msg.details.lpr.isUpdate` is true for subsequent readings of the same event; confidence stays in `msg.details.lpr.confidence`. A later event with the same plate produces a new message. Startup, unrelated detections, and events without plate text produce no result; lookup failures go to the error output.
165
-
166
- The [official Protect event schema](https://developer.ui.com/protect/v7.3.47/get-v1subscribeevents) exposes the `licensePlate` detection type but does not document the recognized text. The node therefore retrieves OCR metadata from the matching event through Protect's local, unofficial events API. An active LPR node prepares the configured account's session at deploy and reuses it until the controller requires renewal. OCR supplied in a live event bypasses pending lookups. The node starts looking for OCR at vehicle detection, before the live LPR classification arrives; vehicle detection alone never produces a plate. Up to five background follow-up reads, delayed by 150, 350, 750, 1500 and 3000 milliseconds between requests, retrieve missing text or refinements without holding the first reading. The first text still depends on when Protect exposes OCR, and later readings are not guaranteed accurate. This requires the local account above and may depend on the Protect version. Credentials use Node-RED's credential storage and are not included in messages or ordinary flow exports.
167
-
168
- Importable example: [Protect LPR](examples/unifi-protect-lpr.json).
169
-
170
- <br/>
171
- <br/>
172
- <p align="left">
173
- <a href="https://ui.com/door-access">
174
- <img src="nodes/readme-assets/UniFi%20Access/UniFi%20Access%20Black.svg" alt="UniFi Access logo" width="430">
175
- </a>
176
- </p>
177
-
178
- Use **Access** nodes to work with:
179
-
180
- - doors
181
- - Access devices (hubs, intercoms)
182
- - door events (unlock, ring, DPS, emergency)
183
- - lock rules and schedules
184
- - visitors, access policies, holiday groups, and door groups
185
- - recent system logs
186
- - doorbell actions
187
-
188
- Things you can do:
189
-
190
- - Unlock a door remotely.
191
- - Set a temporary unlock window with a custom duration.
192
- - Enable lockdown or evacuation mode.
193
- - Receive door events in real time.
194
- - Trigger or cancel an intercom doorbell.
195
- - Read visitors, access policies, schedules, holiday groups, and door groups.
196
- - Inspect recent Access system-log entries and the door-group topology.
197
-
198
- ## Outputs
199
-
200
- Every node has **two outputs**:
201
-
202
- | Output | When it fires |
203
- | -------------- | ---------------------------------------------------------------------------- |
204
- | **1 — result** | The action completed successfully. The result is available in `msg.payload`. |
205
- | **2 — error** | Something went wrong (connection problem, timeout, unsupported action). |
206
-
207
- 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.
208
-
209
- **Startup and missing readings** — Protect, Access and Network device nodes have an advanced **Emit startup states and undefined payloads** checkbox, disabled by default, including for existing flows. With it disabled, initial state snapshots and missing, null or `undefined` readings are suppressed. Valid `false` and `0` readings still pass through. Enable the checkbox to allow startup snapshots and missing payloads. Protect observables never replay an old value when a fresh reading is unavailable; LPR and event-photo actions continue to emit only actual readings or photos.
210
-
211
- **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.
212
-
213
- ## Example Flows
214
-
215
- Import from `examples/`:
216
-
217
- | Flow file | What it demonstrates |
218
- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
219
- | [examples/unifi-protect-info.json](examples/unifi-protect-info.json) | Read the state of a Protect camera |
220
- | [examples/unifi-protect-sensor-observe.json](examples/unifi-protect-sensor-observe.json) | Receive sensor events (motion, temperature, humidity, …) |
221
- | [examples/unifi-protect-camera-actions.json](examples/unifi-protect-camera-actions.json) | Take snapshots, move PTZ, show doorbell messages |
222
- | [examples/unifi-access-door-control.json](examples/unifi-access-door-control.json) | Door state, remote unlock, temporary lock rule |
223
- | [examples/unifi-access-intercom-doorbell.json](examples/unifi-access-intercom-doorbell.json) | Intercom — receive ring, trigger and cancel doorbell |
224
-
225
- ## Notes
226
-
227
- - You need valid login credentials for the UniFi application you want to use.
228
- - Some actions are only available on specific device models.
229
- - UniFi behavior can vary between application versions.
54
+ Release notes: [CHANGELOG.md](CHANGELOG.md)
230
55
 
231
56
  [npm-version-image]: https://img.shields.io/npm/v/node-red-contrib-unifi-ultimate.svg
232
57
  [npm-url]: https://www.npmjs.com/package/node-red-contrib-unifi-ultimate
@@ -5,6 +5,7 @@ const { actionGuidance } = require("./utils/unifi-action-guidance");
5
5
  const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
6
6
 
7
7
  const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
8
+ const { createUnifiAccessCerebrum } = require("./utils/unifiCerebrum");
8
9
 
9
10
  const {
10
11
  buildBaseUrlFromHost,
@@ -228,6 +229,10 @@ module.exports = function(RED) {
228
229
  };
229
230
 
230
231
  node.broadcastNotification = (payload) => {
232
+ try {
233
+ if (node.cerebrumIntegration) node.cerebrumIntegration.handleNotification(payload);
234
+ } catch (error) {
235
+ }
231
236
  // The config node centralizes one websocket stream and fans it out
232
237
  // to all Access runtime nodes interested in events.
233
238
  node.nodeClients.forEach((client) => {
@@ -789,7 +794,20 @@ module.exports = function(RED) {
789
794
  }
790
795
  };
791
796
 
797
+ // Read-only publication of doors and Access events to Cerebrum Ultimate (optional).
798
+ node.cerebrumIntegration = null;
799
+ try {
800
+ node.cerebrumIntegration = createUnifiAccessCerebrum({ configNode: node });
801
+ } catch (error) {
802
+ node.cerebrumIntegration = null;
803
+ }
804
+
792
805
  node.on("close", function(done) {
806
+ try {
807
+ if (node.cerebrumIntegration) node.cerebrumIntegration.dispose();
808
+ } catch (error) {
809
+ }
810
+ node.cerebrumIntegration = null;
793
811
  try {
794
812
  node.isClosing = true;
795
813
  node.stopSimpleMonitorScheduler();
@@ -4,6 +4,7 @@ const { registerConnectionCheck } = require("./utils/unifi-connection-check");
4
4
  const { actionGuidance } = require("./utils/unifi-action-guidance");
5
5
 
6
6
  const { installNetworkMonitorReads } = require("./utils/unifi-network-monitor");
7
+ const { createUnifiNetworkCerebrum } = require("./utils/unifiCerebrum");
7
8
  const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
8
9
  const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
9
10
 
@@ -3522,7 +3523,20 @@ module.exports = function(RED) {
3522
3523
  node.seedPortOverrideCache().catch(() => {});
3523
3524
  }, 0);
3524
3525
 
3526
+ // Read-only publication of network devices and clients to Cerebrum Ultimate (optional).
3527
+ node.cerebrumIntegration = null;
3528
+ try {
3529
+ node.cerebrumIntegration = createUnifiNetworkCerebrum({ configNode: node });
3530
+ } catch (error) {
3531
+ node.cerebrumIntegration = null;
3532
+ }
3533
+
3525
3534
  node.on("close", function(done) {
3535
+ try {
3536
+ if (node.cerebrumIntegration) node.cerebrumIntegration.dispose();
3537
+ } catch (error) {
3538
+ }
3539
+ node.cerebrumIntegration = null;
3526
3540
  try {
3527
3541
  node.isClosing = true;
3528
3542
  node.stopSimpleMonitorScheduler();
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { decodeScopedDeviceId } = require("./utils/unifi-network-device-registry");
4
4
  const { normalizePresenceMatchBy } = require("./utils/unifi-network-presence-utils");
5
+ const { createUnifiPresenceCerebrum } = require("./utils/unifiCerebrum");
5
6
  const {
6
7
  buildStatusTimestampText,
7
8
  appendStatusTimestamp,
@@ -107,6 +108,10 @@ function setupNetworkClientWatch(node, config) {
107
108
  attachDetails(outputMsg, { client });
108
109
 
109
110
  sendWithPayload(node.send.bind(node), [outputMsg, null]);
111
+ try {
112
+ if (node.cerebrumIntegration) node.cerebrumIntegration.client(eventName, client, networkName);
113
+ } catch (error) {
114
+ }
110
115
  }
111
116
 
112
117
  function diffAndEmit(currentClients) {
@@ -252,6 +257,11 @@ function setupNetworkClientWatch(node, config) {
252
257
  }
253
258
 
254
259
  node.on("close", function(done) {
260
+ try {
261
+ if (node.cerebrumIntegration) node.cerebrumIntegration.dispose();
262
+ } catch (error) {
263
+ }
264
+ node.cerebrumIntegration = null;
255
265
  try {
256
266
  stopPolling();
257
267
  } catch (error) {
@@ -270,6 +280,13 @@ module.exports = function(RED) {
270
280
  const node = this;
271
281
  node.name = config.name;
272
282
  node.server = RED.nodes.getNode(config.server);
283
+ // Read-only publication of this presence to Cerebrum Ultimate (optional).
284
+ node.cerebrumIntegration = null;
285
+ try {
286
+ node.cerebrumIntegration = createUnifiPresenceCerebrum({ node, deviceName: normalizeString(config.deviceName) });
287
+ } catch (error) {
288
+ node.cerebrumIntegration = null;
289
+ }
273
290
  // "Watch by" selects the mode. "presence" (default) tracks a single
274
291
  // client; "network" watches a network for clients joining/leaving.
275
292
  node.watchBy = normalizeString(config.watchBy) || "presence";
@@ -394,6 +411,10 @@ module.exports = function(RED) {
394
411
  } catch (error) {
395
412
  node.warn(`Presence output send failed: ${error && error.message ? error.message : error}`);
396
413
  }
414
+ try {
415
+ if (node.cerebrumIntegration) node.cerebrumIntegration.presence(present, resolvedDeviceName, reason);
416
+ } catch (error) {
417
+ }
397
418
  }
398
419
 
399
420
  function setPresent(clientId, source, raw) {
@@ -650,6 +671,11 @@ module.exports = function(RED) {
650
671
  }
651
672
 
652
673
  node.on("close", function(done) {
674
+ try {
675
+ if (node.cerebrumIntegration) node.cerebrumIntegration.dispose();
676
+ } catch (error) {
677
+ }
678
+ node.cerebrumIntegration = null;
653
679
  try {
654
680
  stopRepeatTimer();
655
681
  stopObservation();
@@ -27,6 +27,8 @@ const { LICENSE_PLATE_EVENT_TYPES, extractLicensePlates, isLicensePlateEvent } =
27
27
  const { readAlarmState, matchesDeviceUpdate, mergeDeviceUpdate, buildRequestError } = require("./utils/unifi-protect-alarm");
28
28
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
29
29
  const LPR_FOLLOW_UP_DELAYS_MS = [150, 350, 750, 1500, 3000];
30
+ const LPR_OPEN_EVENT_POLL_MS = 1000;
31
+ const LPR_OPEN_EVENT_MAX_MS = 60 * 1000;
30
32
 
31
33
  function resolveDeviceType(configuredDeviceType) {
32
34
  return String(configuredDeviceType || "").trim();
@@ -603,8 +605,17 @@ module.exports = function(RED) {
603
605
  }
604
606
 
605
607
  function scheduleLicensePlateFollowUp(state) {
606
- if (!isLicensePlateStateActive(state) || state.timer || state.followUpIndex >= LPR_FOLLOW_UP_DELAYS_MS.length) return;
607
- const delay = LPR_FOLLOW_UP_DELAYS_MS[state.followUpIndex++];
608
+ if (!isLicensePlateStateActive(state) || state.timer) return;
609
+ let delay;
610
+ if (state.followUpIndex < LPR_FOLLOW_UP_DELAYS_MS.length) {
611
+ delay = LPR_FOLLOW_UP_DELAYS_MS[state.followUpIndex++];
612
+ } else if (!state.emitted.size && !state.latestEvent.end && Date.now() < state.pollUntil) {
613
+ // Protect can read the plate well after the vehicle is detected.
614
+ // Keep looking while the event is open instead of waiting for its end.
615
+ delay = LPR_OPEN_EVENT_POLL_MS;
616
+ } else {
617
+ return;
618
+ }
608
619
  state.timer = setTimeout(() => {
609
620
  state.timer = null;
610
621
  if (!isLicensePlateStateActive(state)) return;
@@ -627,6 +638,7 @@ module.exports = function(RED) {
627
638
  // Do not keep retrying a credentials/permission failure.
628
639
  // A later real event can retry after configuration recovers.
629
640
  state.followUpIndex = LPR_FOLLOW_UP_DELAYS_MS.length;
641
+ state.pollUntil = 0;
630
642
  if (error.code === "UNIFI_PROTECT_HISTORY_CREDENTIALS_REQUIRED") {
631
643
  if (lprCredentialsWarningSent) continue;
632
644
  lprCredentialsWarningSent = true;
@@ -647,6 +659,7 @@ module.exports = function(RED) {
647
659
  }
648
660
  }).catch((error) => {
649
661
  state.followUpIndex = LPR_FOLLOW_UP_DELAYS_MS.length;
662
+ state.pollUntil = 0;
650
663
  if (isLicensePlateStateActive(state)) reportLicensePlateError(error);
651
664
  }).finally(() => {
652
665
  state.inFlight = null;
@@ -663,7 +676,8 @@ module.exports = function(RED) {
663
676
  // classification later. Output still requires actual OCR metadata.
664
677
  const vehicleCandidate = LICENSE_PLATE_EVENT_TYPES.includes(item.type)
665
678
  && Array.isArray(item.smartDetectTypes) && item.smartDetectTypes.includes("vehicle");
666
- if ((!isLicensePlateEvent(item) && !vehicleCandidate) || !item.id) return;
679
+ // Later updates of a tracked event may carry only the changed fields.
680
+ if (!item.id || (!isLicensePlateEvent(item) && !vehicleCandidate && !lprEventStates.has(item.id))) return;
667
681
  const now = Date.now();
668
682
  lprEventStates.forEach((state, id) => {
669
683
  if (now - state.lastSeen > 60 * 60 * 1000) forgetLicensePlateEvent(id);
@@ -672,7 +686,7 @@ module.exports = function(RED) {
672
686
  if (!state) {
673
687
  if (lprEventStates.size >= 256) forgetLicensePlateEvent(lprEventStates.keys().next().value);
674
688
  state = { emitted: new Map(), pending: null, inFlight: null, timer: null, lastSeen: now,
675
- liveVersion: 0, followUpIndex: 0, latestEvent: item };
689
+ liveVersion: 0, followUpIndex: 0, pollUntil: now + LPR_OPEN_EVENT_MAX_MS, latestEvent: item };
676
690
  lprEventStates.set(item.id, state);
677
691
  }
678
692
  state.lastSeen = now;
@@ -0,0 +1,198 @@
1
+ 'use strict'
2
+
3
+ // Cerebrum Ultimate integration helper.
4
+ // Canonical copy: node-red-contrib-cerebrum-ultimate/nodes/utils/cerebrumIntegration.js.
5
+ // Every Max Supervibe node package ships an identical copy: keep them in sync.
6
+ //
7
+ // Registers this package as a read-only provider in Cerebrum's in-process
8
+ // adapter registry. Cerebrum is optional: without it the registry is just an
9
+ // unused object. Cerebrum subscribes to the provider events (states, history,
10
+ // JavaScript routines) and publishes listEntities/getEntity to MCP clients.
11
+ //
12
+ // Event contract consumed by Cerebrum:
13
+ // { entityId, eventType: 'state_changed', state, previousState,
14
+ // resourceName, resourceType, area, kind, capability, unit, at, details }
15
+
16
+ const REGISTRY_KEY = Symbol.for('node-red.cerebrum-ultimate.adapters.v1')
17
+ const REGISTRY_VERSION = 1
18
+ const MAX_STATE_CHARS = 500
19
+
20
+ const isCompatibleRegistry = value => !!value &&
21
+ value.version === REGISTRY_VERSION &&
22
+ value.adapters instanceof Map &&
23
+ value.providers instanceof Map &&
24
+ value.listeners instanceof Set &&
25
+ typeof value.registerAdapter === 'function' &&
26
+ typeof value.registerProvider === 'function'
27
+
28
+ const notify = (listeners, event) => {
29
+ listeners.forEach(listener => {
30
+ try { listener(event) } catch { /* a consumer cannot break the registry */ }
31
+ })
32
+ }
33
+
34
+ // Same shape as Cerebrum's own registry, so whichever package loads first
35
+ // creates an instance the other accepts.
36
+ const getCerebrumRegistry = () => {
37
+ const existing = globalThis[REGISTRY_KEY]
38
+ if (isCompatibleRegistry(existing)) return existing
39
+ const registry = {
40
+ version: REGISTRY_VERSION,
41
+ adapters: new Map(),
42
+ providers: new Map(),
43
+ listeners: new Set(),
44
+ registerAdapter (adapter) {
45
+ if (!adapter || !adapter.id) throw new Error('Cerebrum adapter id is required')
46
+ const frozen = Object.freeze({ ...adapter, id: String(adapter.id) })
47
+ this.adapters.set(frozen.id, frozen)
48
+ notify(this.listeners, { type: 'adapter_registered', adapter: frozen })
49
+ return () => {
50
+ if (this.adapters.get(frozen.id) !== frozen) return false
51
+ this.adapters.delete(frozen.id)
52
+ notify(this.listeners, { type: 'adapter_unregistered', adapter: frozen })
53
+ return true
54
+ }
55
+ },
56
+ registerProvider (provider) {
57
+ if (!provider || !provider.id || !provider.adapterId) throw new Error('Cerebrum provider id and adapterId are required')
58
+ this.providers.set(String(provider.id), provider)
59
+ notify(this.listeners, { type: 'provider_registered', provider })
60
+ return () => this.unregisterProvider(provider.id, provider)
61
+ },
62
+ unregisterProvider (providerId, expectedProvider) {
63
+ const id = String(providerId || '')
64
+ const provider = this.providers.get(id)
65
+ if (!provider || (expectedProvider && provider !== expectedProvider)) return false
66
+ this.providers.delete(id)
67
+ notify(this.listeners, { type: 'provider_unregistered', provider })
68
+ return true
69
+ },
70
+ subscribe (listener) {
71
+ if (typeof listener !== 'function') return () => {}
72
+ this.listeners.add(listener)
73
+ return () => this.listeners.delete(listener)
74
+ }
75
+ }
76
+ globalThis[REGISTRY_KEY] = registry
77
+ return registry
78
+ }
79
+
80
+ const stateText = value => {
81
+ if (value === undefined || value === null) return ''
82
+ if (typeof value === 'object') {
83
+ try { return JSON.stringify(value).slice(0, MAX_STATE_CHARS) } catch { return '' }
84
+ }
85
+ return String(value).slice(0, MAX_STATE_CHARS)
86
+ }
87
+
88
+ // adapter: { id, title, packageName, kind, capabilities, operations }
89
+ // provider: { id, title, isReady(), listEntities(), getEntity(id), ... }
90
+ // options.minIntervalMs: per-entity minimum interval between two emitted
91
+ // changes of a numeric value (telemetry); state changes of non-numeric
92
+ // values are always emitted. Repeated identical values are never emitted.
93
+ const registerCerebrumIntegration = ({ adapter, provider, minIntervalMs = 0, now = () => Date.now() } = {}) => {
94
+ const listeners = new Set()
95
+ const lastByEntity = new Map()
96
+ const pendingByEntity = new Map()
97
+ let disposed = false
98
+ let unregisterProvider = () => {}
99
+ let unregisterAdapter = () => {}
100
+
101
+ const deliver = event => {
102
+ listeners.forEach(listener => {
103
+ try { listener(event) } catch { /* Cerebrum must never break the node */ }
104
+ })
105
+ }
106
+
107
+ const flushPending = entityId => {
108
+ const pending = pendingByEntity.get(entityId)
109
+ if (!pending) return
110
+ clearTimeout(pending.timer)
111
+ pendingByEntity.delete(entityId)
112
+ if (disposed) return
113
+ lastByEntity.set(entityId, { state: pending.event.state, at: now() })
114
+ deliver(pending.event)
115
+ }
116
+
117
+ const emit = (event = {}) => {
118
+ if (disposed || !listeners.size || !event.entityId) return false
119
+ const entityId = String(event.entityId)
120
+ const state = stateText(event.state)
121
+ const previous = lastByEntity.get(entityId)
122
+ if (previous && previous.state === state && (event.eventType || 'state_changed') === 'state_changed') return false
123
+ const normalized = {
124
+ ...event,
125
+ entityId,
126
+ eventType: event.eventType || 'state_changed',
127
+ state,
128
+ previousState: event.previousState !== undefined ? stateText(event.previousState) : (previous ? previous.state : ''),
129
+ adapterId: adapter.id,
130
+ providerId: provider.id,
131
+ source: adapter.id,
132
+ at: event.at || new Date(now()).toISOString()
133
+ }
134
+ const numeric = state !== '' && Number.isFinite(Number(state))
135
+ const elapsed = previous ? now() - previous.at : Infinity
136
+ if (minIntervalMs > 0 && numeric && normalized.eventType === 'state_changed' && elapsed < minIntervalMs) {
137
+ // Keep only the latest value and deliver it when the interval ends.
138
+ const pending = pendingByEntity.get(entityId)
139
+ if (pending) pending.event = normalized
140
+ else {
141
+ const timer = setTimeout(() => flushPending(entityId), minIntervalMs - elapsed)
142
+ if (timer && typeof timer.unref === 'function') timer.unref()
143
+ pendingByEntity.set(entityId, { event: normalized, timer })
144
+ }
145
+ return false
146
+ }
147
+ if (pendingByEntity.has(entityId)) {
148
+ clearTimeout(pendingByEntity.get(entityId).timer)
149
+ pendingByEntity.delete(entityId)
150
+ }
151
+ if (normalized.eventType === 'state_changed') lastByEntity.set(entityId, { state, at: now() })
152
+ deliver(normalized)
153
+ return true
154
+ }
155
+
156
+ const publishedProvider = {
157
+ ...provider,
158
+ adapterId: adapter.id,
159
+ subscribe (listener) {
160
+ if (typeof listener !== 'function') return () => {}
161
+ listeners.add(listener)
162
+ return () => listeners.delete(listener)
163
+ }
164
+ }
165
+
166
+ try {
167
+ const registry = getCerebrumRegistry()
168
+ unregisterAdapter = registry.registerAdapter(adapter) || (() => {})
169
+ unregisterProvider = registry.registerProvider(publishedProvider) || (() => registry.unregisterProvider(publishedProvider.id, publishedProvider))
170
+ } catch { /* Cerebrum integration is optional */ }
171
+
172
+ return {
173
+ provider: publishedProvider,
174
+ emit,
175
+ hasSubscribers: () => listeners.size > 0,
176
+ dispose () {
177
+ if (disposed) return
178
+ disposed = true
179
+ pendingByEntity.forEach(pending => clearTimeout(pending.timer))
180
+ pendingByEntity.clear()
181
+ listeners.clear()
182
+ try { unregisterProvider() } catch { /* ignore */ }
183
+ // The adapter manifest is shared by every config node of the package;
184
+ // remove it only when no provider of this adapter remains.
185
+ try {
186
+ const registry = getCerebrumRegistry()
187
+ const stillUsed = Array.from(registry.providers.values()).some(candidate => candidate && candidate.adapterId === adapter.id)
188
+ if (!stillUsed) unregisterAdapter()
189
+ } catch { /* ignore */ }
190
+ }
191
+ }
192
+ }
193
+
194
+ module.exports = {
195
+ CEREBRUM_REGISTRY_KEY: REGISTRY_KEY,
196
+ getCerebrumRegistry,
197
+ registerCerebrumIntegration
198
+ }
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+
3
+ // Publishes UniFi Network and UniFi Access to Cerebrum Ultimate, read-only.
4
+ // - Network config: network devices and clients, read on demand.
5
+ // - Network presence node: home/away of the watched device, or the clients
6
+ // joining and leaving the watched network.
7
+ // - Access config: door position and Access events (doorbell, unlocks...).
8
+ // Nothing can be commanded from Cerebrum. UniFi Protect cameras are already
9
+ // published through the Cerebrum camera registry.
10
+
11
+ const { registerCerebrumIntegration } = require("./cerebrumIntegration");
12
+
13
+ const text = (value) => (value === undefined || value === null ? "" : String(value).trim());
14
+ const first = (...values) => values.map(text).find(Boolean) || "";
15
+
16
+ const publishEntity = (integration, entity, eventType = "state_changed") => {
17
+ const details = { ...entity };
18
+ ["id", "name", "kind", "capability", "state"].forEach((key) => delete details[key]);
19
+ integration.emit({
20
+ entityId: entity.id,
21
+ eventType,
22
+ state: entity.state,
23
+ resourceName: entity.name,
24
+ resourceType: entity.kind,
25
+ kind: entity.kind,
26
+ capability: entity.capability,
27
+ details
28
+ });
29
+ };
30
+
31
+ const NETWORK_ADAPTER = Object.freeze({
32
+ id: "unifi-network",
33
+ title: "UniFi Network",
34
+ packageName: "node-red-contrib-unifi-ultimate",
35
+ kind: "network",
36
+ capabilities: ["network-devices", "network-clients", "presence"],
37
+ access: "observe",
38
+ operations: [
39
+ { id: "list-entities", description: "UniFi Network: access points, switches and gateways with their state (online/offline), model and IP; connected clients (phones, computers, IoT) with name, IP and connection type; presence of the watched devices (home/away). Filter with a query: the client list can be long. Read-only." },
40
+ { id: "read-entity", description: "Current state of one UniFi Network device, client or presence by its exact id." }
41
+ ]
42
+ });
43
+
44
+ function mapNetworkDevice(device) {
45
+ const state = first(device.state, device.status).toLowerCase();
46
+ return {
47
+ id: `device/${first(device.id, device.macAddress, device.mac)}`,
48
+ name: first(device.name, device.model, device.macAddress, device.mac),
49
+ kind: "network_device",
50
+ capability: "status",
51
+ state: state === "1" ? "online" : state === "0" ? "offline" : (state || "unknown"),
52
+ model: first(device.model),
53
+ ipAddress: first(device.ipAddress, device.ip),
54
+ site: first(device.siteName)
55
+ };
56
+ }
57
+
58
+ function mapNetworkClient(client) {
59
+ return {
60
+ id: `client/${first(client.id, client.macAddress, client.mac)}`,
61
+ name: first(client.name, client.hostname, client.macAddress, client.mac),
62
+ kind: "network_client",
63
+ capability: "presence",
64
+ state: "connected",
65
+ connection: first(client.type, client.isWired === true ? "WIRED" : ""),
66
+ ipAddress: first(client.ipAddress, client.ip),
67
+ connectedAt: first(client.connectedAt),
68
+ site: first(client.siteName)
69
+ };
70
+ }
71
+
72
+ function createUnifiNetworkCerebrum({ configNode }) {
73
+ const fetchList = async (type, mapper) => {
74
+ const items = await configNode.fetchDevices(type);
75
+ return (Array.isArray(items) ? items : []).map(mapper).filter((entity) => entity.id.split("/")[1]);
76
+ };
77
+ const integration = registerCerebrumIntegration({
78
+ adapter: NETWORK_ADAPTER,
79
+ provider: {
80
+ id: `unifi-network:${configNode.id}`,
81
+ title: `UniFi Network ${configNode.name || ""}`.trim(),
82
+ ownerNodeId: configNode.id,
83
+ isReady: () => Boolean(configNode.getApiKey && configNode.getApiKey()),
84
+ listEntities: async () => {
85
+ const [devices, clients] = await Promise.all([
86
+ fetchList("device", mapNetworkDevice),
87
+ fetchList("client", mapNetworkClient).catch(() => [])
88
+ ]);
89
+ return devices.concat(clients);
90
+ },
91
+ getEntity: async (id) => {
92
+ const wanted = text(id);
93
+ const list = wanted.startsWith("client/")
94
+ ? await fetchList("client", mapNetworkClient)
95
+ : await fetchList("device", mapNetworkDevice);
96
+ return list.find((entity) => entity.id === wanted) || null;
97
+ }
98
+ }
99
+ });
100
+ return { provider: integration.provider, dispose: integration.dispose };
101
+ }
102
+
103
+ // One provider per presence node: its own entities, updated by its events.
104
+ function createUnifiPresenceCerebrum({ node, deviceName: configuredName = "" }) {
105
+ const entitiesById = new Map();
106
+ const integration = registerCerebrumIntegration({
107
+ adapter: NETWORK_ADAPTER,
108
+ provider: {
109
+ id: `unifi-network-presence:${node.id}`,
110
+ title: `UniFi presence ${node.name || ""}`.trim(),
111
+ ownerNodeId: node.id,
112
+ ready: true,
113
+ listEntities: async () => Array.from(entitiesById.values()).map((entity) => ({ ...entity })),
114
+ getEntity: async (id) => {
115
+ const entity = entitiesById.get(text(id));
116
+ return entity ? { ...entity } : null;
117
+ }
118
+ }
119
+ });
120
+ const update = (entity) => {
121
+ entitiesById.set(entity.id, entity);
122
+ publishEntity(integration, entity);
123
+ };
124
+ return {
125
+ provider: integration.provider,
126
+ dispose: integration.dispose,
127
+ // Single watched device: home / away.
128
+ presence(present, deviceName, reason) {
129
+ update({
130
+ id: `${node.id}/presence`,
131
+ // The name given in the node (e.g. "Max's phone") beats the hostname.
132
+ name: first(configuredName, deviceName, node.clientName, node.name, "UniFi device"),
133
+ kind: "presence",
134
+ capability: "presence",
135
+ state: present ? "home" : "away",
136
+ reason: text(reason)
137
+ });
138
+ },
139
+ // Network watch: a client joined or left.
140
+ client(eventName, client, networkName) {
141
+ const mac = first(client && client.mac, client && client.macAddress);
142
+ if (!mac) return;
143
+ update({
144
+ id: `${node.id}/client/${mac}`,
145
+ name: first(client && client.name, mac),
146
+ kind: "network_client",
147
+ capability: "presence",
148
+ state: eventName === "joined" ? "connected" : "disconnected",
149
+ network: text(networkName),
150
+ ipAddress: first(client && client.ipAddress)
151
+ });
152
+ }
153
+ };
154
+ }
155
+
156
+ const ACCESS_ADAPTER = Object.freeze({
157
+ id: "unifi-access",
158
+ title: "UniFi Access",
159
+ packageName: "node-red-contrib-unifi-ultimate",
160
+ kind: "security",
161
+ capabilities: ["doors", "door-position", "doorbell", "access-events"],
162
+ access: "observe",
163
+ operations: [
164
+ { id: "list-entities", description: "UniFi Access doors: door position (open/close) and the last Access event of each door (doorbell ring, unlock, access granted or denied). Read-only." },
165
+ { id: "read-entity", description: "Current state of one UniFi Access door by its exact id." }
166
+ ]
167
+ });
168
+
169
+ function createUnifiAccessCerebrum({ configNode }) {
170
+ const entitiesById = new Map();
171
+ const integration = registerCerebrumIntegration({
172
+ adapter: ACCESS_ADAPTER,
173
+ provider: {
174
+ id: `unifi-access:${configNode.id}`,
175
+ title: `UniFi Access ${configNode.name || ""}`.trim(),
176
+ ownerNodeId: configNode.id,
177
+ ready: true,
178
+ listEntities: async () => Array.from(entitiesById.values()).map((entity) => ({ ...entity })),
179
+ getEntity: async (id) => {
180
+ const entity = entitiesById.get(text(id));
181
+ return entity ? { ...entity } : null;
182
+ }
183
+ }
184
+ });
185
+
186
+ // payload: one notification of the Access WebSocket.
187
+ function handleNotification(payload) {
188
+ if (!payload || typeof payload !== "object") return;
189
+ const eventName = text(payload.event);
190
+ if (!eventName) return;
191
+ const data = payload.data && typeof payload.data === "object" ? payload.data : {};
192
+ const location = data.location && typeof data.location === "object" ? data.location : {};
193
+ const doorId = first(location.id, data.device_id, data.deviceId) || "site";
194
+ const doorName = first(location.name, data.device_name, data.deviceName) || `Door ${doorId}`;
195
+ const position = eventName === "access.device.dps_status" ? first(data.object && data.object.status) : "";
196
+ const previous = entitiesById.get(`${configNode.id}/door/${doorId}`) || {};
197
+ const entity = {
198
+ id: `${configNode.id}/door/${doorId}`,
199
+ name: doorName,
200
+ kind: "door",
201
+ capability: "open_close",
202
+ state: position || previous.state || "unknown",
203
+ lastEvent: eventName,
204
+ at: new Date().toISOString()
205
+ };
206
+ entitiesById.set(entity.id, entity);
207
+ if (position) publishEntity(integration, entity);
208
+ else publishEntity(integration, { ...entity, state: eventName }, "access_event");
209
+ }
210
+
211
+ return { handleNotification, provider: integration.provider, dispose: integration.dispose };
212
+ }
213
+
214
+ module.exports = {
215
+ createUnifiAccessCerebrum,
216
+ createUnifiNetworkCerebrum,
217
+ createUnifiPresenceCerebrum,
218
+ mapNetworkClient,
219
+ mapNetworkDevice
220
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.23",
3
+ "version": "1.1.25",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",