node-red-contrib-unifi-ultimate 1.1.17 → 1.1.19
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 +1 -0
- package/examples/unifi-protect-alarm-state.json +84 -0
- package/nodes/unifi-access-config.js +19 -7
- package/nodes/unifi-network-config.js +145 -37
- package/nodes/unifi-network-device.html +2 -1
- package/nodes/unifi-network-device.js +2 -0
- package/nodes/unifi-protect-config.js +13 -4
- package/nodes/unifi-protect-device.html +8 -2
- package/nodes/unifi-protect-device.js +38 -8
- package/nodes/utils/unifi-protect-alarm.js +59 -0
- package/nodes/utils/unifi-protect-device-registry.js +10 -1
- package/nodes/utils/unifi-protect-field-metadata.js +12 -0
- package/nodes/utils/unifi-websocket-resilience.js +94 -0
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -149,6 +149,7 @@ Things you can do:
|
|
|
149
149
|
- Monitor bridges, Link Stations, alarm hubs, key fobs, sirens, relays, and speakers.
|
|
150
150
|
- Play or stop a siren, control relay outputs, and test speaker or siren sound.
|
|
151
151
|
- Read and select Protect Arm Profiles, then arm or disarm the local Alarm Manager from the NVR control.
|
|
152
|
+
- 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).
|
|
152
153
|
|
|
153
154
|
### Read license plates (LPR)
|
|
154
155
|
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "flow-protect-alarm-poll",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "Protect Alarm State",
|
|
6
|
+
"disabled": false,
|
|
7
|
+
"info": "Select your Protect connection and Alarm Hub in Read Alarm State. Polls every 60 seconds and after deployment. Hub payload is boolean; NVR payload is the local armMode.status string. Requires a version with Read Alarm State support."
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"id": "inject-protect-alarm-poll",
|
|
11
|
+
"type": "inject",
|
|
12
|
+
"z": "flow-protect-alarm-poll",
|
|
13
|
+
"name": "Poll every 60 seconds",
|
|
14
|
+
"props": [],
|
|
15
|
+
"repeat": "60",
|
|
16
|
+
"crontab": "",
|
|
17
|
+
"once": true,
|
|
18
|
+
"onceDelay": 5,
|
|
19
|
+
"topic": "",
|
|
20
|
+
"x": 170,
|
|
21
|
+
"y": 120,
|
|
22
|
+
"wires": [
|
|
23
|
+
[
|
|
24
|
+
"read-protect-alarm-state"
|
|
25
|
+
]
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"id": "read-protect-alarm-state",
|
|
30
|
+
"type": "unifi-protect-device",
|
|
31
|
+
"z": "flow-protect-alarm-poll",
|
|
32
|
+
"name": "Read Alarm State (Hub)",
|
|
33
|
+
"server": "",
|
|
34
|
+
"deviceType": "alarmHub",
|
|
35
|
+
"deviceId": "",
|
|
36
|
+
"deviceName": "",
|
|
37
|
+
"inputs": 1,
|
|
38
|
+
"capability": "getAlarmState",
|
|
39
|
+
"capabilityConfig": "{}",
|
|
40
|
+
"emitStartupAndUndefined": false,
|
|
41
|
+
"autoEmit": false,
|
|
42
|
+
"autoEmitInterval": 60,
|
|
43
|
+
"x": 440,
|
|
44
|
+
"y": 120,
|
|
45
|
+
"wires": [
|
|
46
|
+
[
|
|
47
|
+
"debug-protect-alarm-status"
|
|
48
|
+
],
|
|
49
|
+
[
|
|
50
|
+
"debug-protect-alarm-error"
|
|
51
|
+
]
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"id": "debug-protect-alarm-status",
|
|
56
|
+
"type": "debug",
|
|
57
|
+
"z": "flow-protect-alarm-poll",
|
|
58
|
+
"name": "Current alarm status",
|
|
59
|
+
"active": true,
|
|
60
|
+
"tosidebar": true,
|
|
61
|
+
"console": false,
|
|
62
|
+
"tostatus": false,
|
|
63
|
+
"complete": "payload",
|
|
64
|
+
"targetType": "msg",
|
|
65
|
+
"x": 990,
|
|
66
|
+
"y": 100,
|
|
67
|
+
"wires": []
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"id": "debug-protect-alarm-error",
|
|
71
|
+
"type": "debug",
|
|
72
|
+
"z": "flow-protect-alarm-poll",
|
|
73
|
+
"name": "Error / missing alarm state",
|
|
74
|
+
"active": true,
|
|
75
|
+
"tosidebar": true,
|
|
76
|
+
"console": false,
|
|
77
|
+
"tostatus": false,
|
|
78
|
+
"complete": "true",
|
|
79
|
+
"targetType": "full",
|
|
80
|
+
"x": 730,
|
|
81
|
+
"y": 200,
|
|
82
|
+
"wires": []
|
|
83
|
+
}
|
|
84
|
+
]
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { registerConnectionCheck } = require("./utils/unifi-connection-check");
|
|
4
4
|
const { actionGuidance } = require("./utils/unifi-action-guidance");
|
|
5
|
+
const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
|
|
5
6
|
|
|
6
7
|
const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
|
|
7
8
|
|
|
@@ -82,6 +83,7 @@ module.exports = function(RED) {
|
|
|
82
83
|
node.nodeClients = [];
|
|
83
84
|
node.wsNotifications = null;
|
|
84
85
|
node.reconnectTimer = null;
|
|
86
|
+
node.reconnectBackoff = createReconnectBackoff();
|
|
85
87
|
node.isClosing = false;
|
|
86
88
|
node.activeDoorbells = new Map();
|
|
87
89
|
node.activeDoorbellRequests = new Map();
|
|
@@ -652,8 +654,8 @@ module.exports = function(RED) {
|
|
|
652
654
|
return;
|
|
653
655
|
}
|
|
654
656
|
|
|
655
|
-
//
|
|
656
|
-
//
|
|
657
|
+
// Back off exponentially to avoid a busy loop while the controller
|
|
658
|
+
// is restarting or upgrading.
|
|
657
659
|
node.reconnectTimer = setTimeout(() => {
|
|
658
660
|
node.reconnectTimer = null;
|
|
659
661
|
try {
|
|
@@ -661,7 +663,7 @@ module.exports = function(RED) {
|
|
|
661
663
|
} catch (error) {
|
|
662
664
|
node.warn(`Access websocket reconnect failed: ${error && error.message ? error.message : error}`);
|
|
663
665
|
}
|
|
664
|
-
},
|
|
666
|
+
}, node.reconnectBackoff.nextDelay());
|
|
665
667
|
};
|
|
666
668
|
|
|
667
669
|
node.ensureWebSocket = () => {
|
|
@@ -698,6 +700,11 @@ module.exports = function(RED) {
|
|
|
698
700
|
return;
|
|
699
701
|
}
|
|
700
702
|
|
|
703
|
+
ws.on("open", () => {
|
|
704
|
+
node.reconnectBackoff.reset();
|
|
705
|
+
});
|
|
706
|
+
attachHeartbeat(ws);
|
|
707
|
+
|
|
701
708
|
ws.on("message", (rawData) => {
|
|
702
709
|
try {
|
|
703
710
|
// Ignore malformed websocket frames rather than killing the
|
|
@@ -712,10 +719,12 @@ module.exports = function(RED) {
|
|
|
712
719
|
|
|
713
720
|
ws.on("close", () => {
|
|
714
721
|
try {
|
|
722
|
+
// A socket closed on purpose has already been detached and
|
|
723
|
+
// must not schedule a reconnect.
|
|
715
724
|
if (node.wsNotifications === ws) {
|
|
716
725
|
node.wsNotifications = null;
|
|
726
|
+
node.scheduleReconnect();
|
|
717
727
|
}
|
|
718
|
-
node.scheduleReconnect();
|
|
719
728
|
} catch (error) {
|
|
720
729
|
}
|
|
721
730
|
});
|
|
@@ -736,12 +745,15 @@ module.exports = function(RED) {
|
|
|
736
745
|
node.reconnectTimer = null;
|
|
737
746
|
}
|
|
738
747
|
|
|
739
|
-
|
|
748
|
+
const socket = node.wsNotifications;
|
|
749
|
+
if (socket) {
|
|
750
|
+
// Detach first so the close callback does not reconnect.
|
|
751
|
+
node.wsNotifications = null;
|
|
752
|
+
stopHeartbeat(socket);
|
|
740
753
|
try {
|
|
741
|
-
|
|
754
|
+
socket.close();
|
|
742
755
|
} catch (error) {
|
|
743
756
|
}
|
|
744
|
-
node.wsNotifications = null;
|
|
745
757
|
}
|
|
746
758
|
};
|
|
747
759
|
|
|
@@ -5,6 +5,7 @@ const { actionGuidance } = require("./utils/unifi-action-guidance");
|
|
|
5
5
|
|
|
6
6
|
const { installNetworkMonitorReads } = require("./utils/unifi-network-monitor");
|
|
7
7
|
const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
|
|
8
|
+
const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
|
|
8
9
|
|
|
9
10
|
const fs = require("fs");
|
|
10
11
|
const os = require("os");
|
|
@@ -44,6 +45,9 @@ module.exports = function(RED) {
|
|
|
44
45
|
const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
|
|
45
46
|
const PORT_OVERRIDE_CACHE_VERSION = 1;
|
|
46
47
|
const PORT_OVERRIDE_CACHE_SAVE_DEBOUNCE_MS = 1000;
|
|
48
|
+
// Short name of the site used by the legacy event stream when a subscriber
|
|
49
|
+
// has no resolvable site.
|
|
50
|
+
const UNOFFICIAL_NETWORK_DEFAULT_SITE = "default";
|
|
47
51
|
// Sentinel stored for a port that was enabled but had no override at all, so
|
|
48
52
|
// re-enabling knows to remove the override we added (instead of restoring one).
|
|
49
53
|
const PORT_OVERRIDE_NONE = { __noOverride: true };
|
|
@@ -122,8 +126,12 @@ module.exports = function(RED) {
|
|
|
122
126
|
node.rejectUnauthorized = config.rejectUnauthorized === true || config.rejectUnauthorized === "true";
|
|
123
127
|
node.powerObservationIntervalSeconds = normalizePowerObserverIntervalSeconds(config.powerObservationIntervalSeconds);
|
|
124
128
|
node.nodeClients = [];
|
|
125
|
-
|
|
129
|
+
// Legacy site name -> socket; the unofficial stream is scoped per site.
|
|
130
|
+
node.wsNetworkEvents = new Map();
|
|
131
|
+
node.unofficialNetworkSiteNames = new Map();
|
|
132
|
+
node.unofficialNetworkSync = Promise.resolve();
|
|
126
133
|
node.reconnectTimer = null;
|
|
134
|
+
node.reconnectBackoff = createReconnectBackoff();
|
|
127
135
|
node.isClosing = false;
|
|
128
136
|
node.powerObserverNodeState = new Map();
|
|
129
137
|
node.powerObserverTimer = null;
|
|
@@ -838,7 +846,7 @@ module.exports = function(RED) {
|
|
|
838
846
|
return getCapabilitiesForType(deviceType, selectedDevice);
|
|
839
847
|
};
|
|
840
848
|
|
|
841
|
-
node.buildUnofficialNetworkWebSocketUrl = () => {
|
|
849
|
+
node.buildUnofficialNetworkWebSocketUrl = (siteName = UNOFFICIAL_NETWORK_DEFAULT_SITE) => {
|
|
842
850
|
const normalizedHost = applyPortToHost(
|
|
843
851
|
String(node.host || "")
|
|
844
852
|
.trim()
|
|
@@ -850,30 +858,58 @@ module.exports = function(RED) {
|
|
|
850
858
|
throw new Error("The configured host is empty or invalid.");
|
|
851
859
|
}
|
|
852
860
|
|
|
853
|
-
const
|
|
861
|
+
const normalizedSiteName = normalizeString(siteName) || UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
862
|
+
const url = new URL(`https://${normalizedHost}/proxy/network/wss/s/${encodeURIComponent(normalizedSiteName)}/events`);
|
|
854
863
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
855
864
|
return url.toString();
|
|
856
865
|
};
|
|
857
866
|
|
|
858
|
-
|
|
867
|
+
const isUnofficialNetworkStreamSubscriber = (client) => {
|
|
859
868
|
try {
|
|
860
|
-
return client && typeof client.shouldReceiveUnofficialNetworkEvents === "function" && client.shouldReceiveUnofficialNetworkEvents();
|
|
869
|
+
return Boolean(client && typeof client.shouldReceiveUnofficialNetworkEvents === "function" && client.shouldReceiveUnofficialNetworkEvents());
|
|
861
870
|
} catch (error) {
|
|
862
871
|
return false;
|
|
863
872
|
}
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
873
|
+
};
|
|
874
|
+
|
|
875
|
+
const getUnofficialNetworkSubscriberSiteId = (client) => {
|
|
876
|
+
try {
|
|
877
|
+
return client && typeof client.getUnofficialNetworkSiteId === "function"
|
|
878
|
+
? normalizeString(client.getUnofficialNetworkSiteId())
|
|
879
|
+
: "";
|
|
880
|
+
} catch (error) {
|
|
881
|
+
return "";
|
|
882
|
+
}
|
|
883
|
+
};
|
|
870
884
|
|
|
871
|
-
|
|
885
|
+
// The legacy event stream is scoped to one site by its short name, so
|
|
886
|
+
// a subscriber without a known site falls back to the default site.
|
|
887
|
+
const getUnofficialNetworkSubscriberSiteName = (client) => {
|
|
888
|
+
const siteId = getUnofficialNetworkSubscriberSiteId(client);
|
|
889
|
+
if (!siteId) {
|
|
890
|
+
return UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
891
|
+
}
|
|
892
|
+
return node.unofficialNetworkSiteNames.get(siteId) || UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
node.hasUnofficialNetworkStreamSubscribers = () => node.nodeClients.some(isUnofficialNetworkStreamSubscriber);
|
|
896
|
+
node.isUnofficialNetworkWebSocketConnected = () => node.wsNetworkEvents.size > 0
|
|
897
|
+
&& Array.from(node.wsNetworkEvents.values()).every((socket) => (
|
|
898
|
+
socket
|
|
899
|
+
&& typeof socket.readyState === "number"
|
|
900
|
+
&& socket.readyState === 1
|
|
901
|
+
));
|
|
902
|
+
|
|
903
|
+
node.broadcastUnofficialNetworkEvent = (eventPayload, siteName) => {
|
|
872
904
|
node.nodeClients.forEach((client) => {
|
|
873
905
|
try {
|
|
874
|
-
if (client
|
|
875
|
-
|
|
906
|
+
if (!client || typeof client.handleNetworkEventUpdate !== "function") {
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
if (siteName && getUnofficialNetworkSubscriberSiteName(client) !== siteName) {
|
|
910
|
+
return;
|
|
876
911
|
}
|
|
912
|
+
client.handleNetworkEventUpdate(eventPayload);
|
|
877
913
|
} catch (error) {
|
|
878
914
|
}
|
|
879
915
|
});
|
|
@@ -886,19 +922,36 @@ module.exports = function(RED) {
|
|
|
886
922
|
|
|
887
923
|
node.reconnectTimer = setTimeout(() => {
|
|
888
924
|
node.reconnectTimer = null;
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
} catch (error) {
|
|
892
|
-
node.warn(`Network websocket reconnect failed: ${error && error.message ? error.message : error}`);
|
|
893
|
-
}
|
|
894
|
-
}, 5000);
|
|
925
|
+
node.ensureUnofficialNetworkWebSocket();
|
|
926
|
+
}, node.reconnectBackoff.nextDelay());
|
|
895
927
|
};
|
|
896
928
|
|
|
897
|
-
|
|
898
|
-
if (
|
|
899
|
-
return;
|
|
929
|
+
async function resolveUnofficialNetworkSiteName(siteId) {
|
|
930
|
+
if (!siteId) {
|
|
931
|
+
return UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
932
|
+
}
|
|
933
|
+
if (node.unofficialNetworkSiteNames.has(siteId)) {
|
|
934
|
+
return node.unofficialNetworkSiteNames.get(siteId);
|
|
900
935
|
}
|
|
901
936
|
|
|
937
|
+
let siteName = "";
|
|
938
|
+
try {
|
|
939
|
+
siteName = await fetchLegacySiteName(siteId);
|
|
940
|
+
} catch (error) {
|
|
941
|
+
// Not cached, so the next reconnect or subscriber retries.
|
|
942
|
+
node.warn(`Unable to resolve UniFi Network site '${siteId}' for the event stream, using '${UNOFFICIAL_NETWORK_DEFAULT_SITE}': ${error && error.message ? error.message : error}`);
|
|
943
|
+
return UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
if (!siteName) {
|
|
947
|
+
node.warn(`UniFi Network site '${siteId}' was not found for the event stream, using '${UNOFFICIAL_NETWORK_DEFAULT_SITE}'.`);
|
|
948
|
+
siteName = UNOFFICIAL_NETWORK_DEFAULT_SITE;
|
|
949
|
+
}
|
|
950
|
+
node.unofficialNetworkSiteNames.set(siteId, siteName);
|
|
951
|
+
return siteName;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function openUnofficialNetworkSiteSocket(siteName) {
|
|
902
955
|
let WebSocket;
|
|
903
956
|
const apiKey = String(node.getApiKey() || "").trim();
|
|
904
957
|
if (!apiKey) {
|
|
@@ -914,7 +967,7 @@ module.exports = function(RED) {
|
|
|
914
967
|
|
|
915
968
|
let ws;
|
|
916
969
|
try {
|
|
917
|
-
ws = new WebSocket(node.buildUnofficialNetworkWebSocketUrl(), {
|
|
970
|
+
ws = new WebSocket(node.buildUnofficialNetworkWebSocketUrl(siteName), {
|
|
918
971
|
headers: buildRequestHeaders(apiKey),
|
|
919
972
|
rejectUnauthorized: node.rejectUnauthorized
|
|
920
973
|
});
|
|
@@ -924,6 +977,11 @@ module.exports = function(RED) {
|
|
|
924
977
|
return;
|
|
925
978
|
}
|
|
926
979
|
|
|
980
|
+
ws.on("open", () => {
|
|
981
|
+
node.reconnectBackoff.reset();
|
|
982
|
+
});
|
|
983
|
+
attachHeartbeat(ws);
|
|
984
|
+
|
|
927
985
|
ws.on("message", (rawData) => {
|
|
928
986
|
try {
|
|
929
987
|
const text = Buffer.isBuffer(rawData) ? rawData.toString("utf8") : String(rawData);
|
|
@@ -931,9 +989,9 @@ module.exports = function(RED) {
|
|
|
931
989
|
return;
|
|
932
990
|
}
|
|
933
991
|
try {
|
|
934
|
-
node.broadcastUnofficialNetworkEvent(JSON.parse(text));
|
|
992
|
+
node.broadcastUnofficialNetworkEvent(JSON.parse(text), siteName);
|
|
935
993
|
} catch (error) {
|
|
936
|
-
node.broadcastUnofficialNetworkEvent({ raw: text });
|
|
994
|
+
node.broadcastUnofficialNetworkEvent({ raw: text }, siteName);
|
|
937
995
|
}
|
|
938
996
|
} catch (error) {
|
|
939
997
|
}
|
|
@@ -941,10 +999,12 @@ module.exports = function(RED) {
|
|
|
941
999
|
|
|
942
1000
|
ws.on("close", () => {
|
|
943
1001
|
try {
|
|
944
|
-
|
|
945
|
-
|
|
1002
|
+
// A socket closed on purpose has already been detached and
|
|
1003
|
+
// must not schedule a reconnect.
|
|
1004
|
+
if (node.wsNetworkEvents.get(siteName) === ws) {
|
|
1005
|
+
node.wsNetworkEvents.delete(siteName);
|
|
1006
|
+
node.scheduleNetworkReconnect();
|
|
946
1007
|
}
|
|
947
|
-
node.scheduleNetworkReconnect();
|
|
948
1008
|
} catch (error) {
|
|
949
1009
|
}
|
|
950
1010
|
});
|
|
@@ -956,7 +1016,58 @@ module.exports = function(RED) {
|
|
|
956
1016
|
}
|
|
957
1017
|
});
|
|
958
1018
|
|
|
959
|
-
node.wsNetworkEvents
|
|
1019
|
+
node.wsNetworkEvents.set(siteName, ws);
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
function closeUnofficialNetworkSiteSocket(siteName) {
|
|
1023
|
+
const socket = node.wsNetworkEvents.get(siteName);
|
|
1024
|
+
if (!socket) {
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
node.wsNetworkEvents.delete(siteName);
|
|
1028
|
+
stopHeartbeat(socket);
|
|
1029
|
+
try {
|
|
1030
|
+
socket.close();
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
async function syncUnofficialNetworkWebSockets() {
|
|
1036
|
+
if (node.isClosing) {
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const siteIds = new Set(node.nodeClients
|
|
1041
|
+
.filter(isUnofficialNetworkStreamSubscriber)
|
|
1042
|
+
.map(getUnofficialNetworkSubscriberSiteId));
|
|
1043
|
+
const wantedSiteNames = new Set();
|
|
1044
|
+
for (const siteId of siteIds) {
|
|
1045
|
+
wantedSiteNames.add(await resolveUnofficialNetworkSiteName(siteId));
|
|
1046
|
+
}
|
|
1047
|
+
if (node.isClosing) {
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
Array.from(node.wsNetworkEvents.keys())
|
|
1052
|
+
.filter((siteName) => !wantedSiteNames.has(siteName))
|
|
1053
|
+
.forEach(closeUnofficialNetworkSiteSocket);
|
|
1054
|
+
wantedSiteNames.forEach((siteName) => {
|
|
1055
|
+
if (!node.wsNetworkEvents.has(siteName)) {
|
|
1056
|
+
openUnofficialNetworkSiteSocket(siteName);
|
|
1057
|
+
}
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// Opens one stream per subscribed site and closes streams no longer
|
|
1062
|
+
// needed. Calls are serialized so overlapping requests cannot open
|
|
1063
|
+
// duplicate sockets while a site name is being resolved.
|
|
1064
|
+
node.ensureUnofficialNetworkWebSocket = () => {
|
|
1065
|
+
node.unofficialNetworkSync = node.unofficialNetworkSync
|
|
1066
|
+
.then(syncUnofficialNetworkWebSockets)
|
|
1067
|
+
.catch((error) => {
|
|
1068
|
+
node.warn(`Unable to initialize Network websocket: ${error && error.message ? error.message : error}`);
|
|
1069
|
+
});
|
|
1070
|
+
return node.unofficialNetworkSync;
|
|
960
1071
|
};
|
|
961
1072
|
|
|
962
1073
|
node.closeUnofficialNetworkWebSocket = () => {
|
|
@@ -965,13 +1076,7 @@ module.exports = function(RED) {
|
|
|
965
1076
|
node.reconnectTimer = null;
|
|
966
1077
|
}
|
|
967
1078
|
|
|
968
|
-
|
|
969
|
-
try {
|
|
970
|
-
node.wsNetworkEvents.close();
|
|
971
|
-
} catch (error) {
|
|
972
|
-
}
|
|
973
|
-
node.wsNetworkEvents = null;
|
|
974
|
-
}
|
|
1079
|
+
Array.from(node.wsNetworkEvents.keys()).forEach(closeUnofficialNetworkSiteSocket);
|
|
975
1080
|
};
|
|
976
1081
|
|
|
977
1082
|
function parsePowerNumber(value) {
|
|
@@ -3397,6 +3502,9 @@ module.exports = function(RED) {
|
|
|
3397
3502
|
}
|
|
3398
3503
|
if (!node.hasUnofficialNetworkStreamSubscribers()) {
|
|
3399
3504
|
node.closeUnofficialNetworkWebSocket();
|
|
3505
|
+
} else {
|
|
3506
|
+
// Close the stream of a site that no longer has subscribers.
|
|
3507
|
+
node.ensureUnofficialNetworkWebSocket();
|
|
3400
3508
|
}
|
|
3401
3509
|
node.refreshPowerObservationScheduler();
|
|
3402
3510
|
node.refreshPresenceObservationScheduler();
|
|
@@ -1237,6 +1237,7 @@
|
|
|
1237
1237
|
refreshEditor();
|
|
1238
1238
|
}
|
|
1239
1239
|
});
|
|
1240
|
+
|
|
1240
1241
|
</script>
|
|
1241
1242
|
|
|
1242
1243
|
<script type="text/html" data-template-name="unifi-network-device">
|
|
@@ -1401,4 +1402,4 @@ msg.payload = { state: "failover", interface: "eth9", at: "2026-09-12T12:00:00.0
|
|
|
1401
1402
|
"payload": null,
|
|
1402
1403
|
"error": { "message": "Request timed out" }
|
|
1403
1404
|
}</code></pre>
|
|
1404
|
-
</script>
|
|
1405
|
+
</script>
|
|
@@ -1008,6 +1008,8 @@ module.exports = function(RED) {
|
|
|
1008
1008
|
}
|
|
1009
1009
|
|
|
1010
1010
|
node.shouldReceiveUnofficialNetworkEvents = () => Boolean(node.isObserving && isUnofficialNetworkStreamCapabilitySelected());
|
|
1011
|
+
// The config node opens the event stream of the site this node belongs to.
|
|
1012
|
+
node.getUnofficialNetworkSiteId = () => resolveScopedIdentifiers(node.deviceType, node.deviceId, node.currentDevice).siteId;
|
|
1011
1013
|
|
|
1012
1014
|
function shouldAutoReceiveConfiguredDevice() {
|
|
1013
1015
|
return node.server
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
const { registerConnectionCheck } = require("./utils/unifi-connection-check");
|
|
4
4
|
const { actionGuidance } = require("./utils/unifi-action-guidance");
|
|
5
|
+
const { buildRequestError } = require("./utils/unifi-protect-alarm");
|
|
6
|
+
const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
|
|
5
7
|
|
|
6
8
|
const {
|
|
7
9
|
buildBaseUrlFromHost,
|
|
@@ -203,6 +205,7 @@ module.exports = function(RED) {
|
|
|
203
205
|
node.wsDevices = null;
|
|
204
206
|
node.wsEvents = null;
|
|
205
207
|
node.reconnectTimer = null;
|
|
208
|
+
node.reconnectBackoff = createReconnectBackoff();
|
|
206
209
|
node.isClosing = false;
|
|
207
210
|
node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
208
211
|
node.knxAiCameraRefresh = null;
|
|
@@ -411,7 +414,7 @@ module.exports = function(RED) {
|
|
|
411
414
|
method: "GET"
|
|
412
415
|
});
|
|
413
416
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
414
|
-
throw
|
|
417
|
+
throw buildRequestError(response, "GET", path, [...Object.values(node.credentials || {}), node.getApiKey()]);
|
|
415
418
|
}
|
|
416
419
|
return response.payload;
|
|
417
420
|
};
|
|
@@ -874,8 +877,8 @@ module.exports = function(RED) {
|
|
|
874
877
|
return;
|
|
875
878
|
}
|
|
876
879
|
|
|
877
|
-
// Back off
|
|
878
|
-
//
|
|
880
|
+
// Back off exponentially so temporary controller restarts do not
|
|
881
|
+
// cause a tight reconnect loop.
|
|
879
882
|
node.reconnectTimer = setTimeout(() => {
|
|
880
883
|
node.reconnectTimer = null;
|
|
881
884
|
try {
|
|
@@ -883,7 +886,7 @@ module.exports = function(RED) {
|
|
|
883
886
|
} catch (error) {
|
|
884
887
|
node.warn(`Protect websocket reconnect failed: ${error && error.message ? error.message : error}`);
|
|
885
888
|
}
|
|
886
|
-
},
|
|
889
|
+
}, node.reconnectBackoff.nextDelay());
|
|
887
890
|
};
|
|
888
891
|
|
|
889
892
|
node.attachSocket = (kind, path, handler) => {
|
|
@@ -917,6 +920,11 @@ module.exports = function(RED) {
|
|
|
917
920
|
return;
|
|
918
921
|
}
|
|
919
922
|
|
|
923
|
+
ws.on("open", () => {
|
|
924
|
+
node.reconnectBackoff.reset();
|
|
925
|
+
});
|
|
926
|
+
attachHeartbeat(ws);
|
|
927
|
+
|
|
920
928
|
ws.on("message", (rawData) => {
|
|
921
929
|
try {
|
|
922
930
|
// Protect streams send JSON messages; malformed frames are
|
|
@@ -971,6 +979,7 @@ module.exports = function(RED) {
|
|
|
971
979
|
// Clear ownership before close so the close callback knows this was
|
|
972
980
|
// intentional and does not schedule an unnecessary reconnect.
|
|
973
981
|
node[propertyName] = null;
|
|
982
|
+
stopHeartbeat(socket);
|
|
974
983
|
try {
|
|
975
984
|
socket.close();
|
|
976
985
|
} catch (error) {
|
|
@@ -1190,6 +1190,9 @@
|
|
|
1190
1190
|
<span style="margin-left:8px;">seconds</span>
|
|
1191
1191
|
</div>
|
|
1192
1192
|
</div>
|
|
1193
|
+
<br/>
|
|
1194
|
+
<br/>
|
|
1195
|
+
<br/>
|
|
1193
1196
|
</script>
|
|
1194
1197
|
|
|
1195
1198
|
<script type="text/html" data-help-name="unifi-protect-device">
|
|
@@ -1206,7 +1209,10 @@
|
|
|
1206
1209
|
<p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and application/alarm actions on <code>NVR</code>.</p>
|
|
1207
1210
|
<p>Protect resources include cameras, sensors, lights, chimes, viewers, live views, NVRs, bridges, Link Stations, alarm hubs, key fobs, relays, sirens, and speakers. The newer device families expose read state and events without the generic raw-update action.</p>
|
|
1208
1211
|
<p><code>Play Siren</code> uses a duration in seconds. <code>Control Relay Output</code> requires an explicit output and on/off state; auto-off applies only when turning an output on. <code>Trigger Alarm Hub Output</code> can toggle an output or set it on/off, with an optional delay and duration. Sound-test actions use a configured volume and never read control values from the incoming message.</p>
|
|
1209
|
-
<p>
|
|
1212
|
+
<p>The <code>NVR</code> arm profile commands control Protect's local Alarm Manager; they do not necessarily control the alarm managed by an Alarm Hub or a global Alarm Manager. Use <code>Read Arm Profiles</code>, <code>Select Arm Profile</code>, <code>Arm Alarm</code>, and <code>Disarm Alarm</code>. These endpoints require Protect's local Alarm Manager.</p>
|
|
1213
|
+
<p><code>Read Alarm State</code> is available on <code>Alarm Hub</code> and <code>NVR</code>. On an Alarm Hub it reads <code>alarmHub.armed</code> and emits <code>true</code> for <code>on</code> or <code>false</code> for <code>off</code>. On an NVR it emits the local Alarm Manager's <code>armMode.status</code> string without converting transitional or unknown statuses to a boolean. The full device remains in <code>msg.details.device</code>. Missing or unsupported state goes to output 2; it never means disarmed. Trigger this action with an Inject node or enable periodic reads for recovery after missed updates or controller restarts.</p>
|
|
1214
|
+
<p>For live state, choose <code>Receive Events → Armed</code> on an Alarm Hub, or <code>Receive Events → Alarm status (local)</code> on an NVR. These values follow device updates, rather than assuming a dedicated arm/disarm event exists. Enable startup emission if you need an initial value after deploy. Delivery depends on Protect publishing device updates; use periodic <code>Read Alarm State</code> for recovery. NVR state and Hub state are separate sources and can differ.</p>
|
|
1215
|
+
<p>Arm/Disarm commands use the configured Protect API key and its account permissions. The optional local username/password used for recorded events does not grant permissions to these commands. HTTP 401 suggests checking the key; 403 suggests checking permissions. HTTP 400 alone does not establish a permission problem: check the selected profile and whether the local Alarm Manager is in use. Request failures include HTTP status, method, path and a bounded, redacted API message when available in <code>msg.details.response</code>. No automatic fallback to raw updates, relay outputs or undocumented alarm controls is performed.</p>
|
|
1210
1216
|
<p><code>Receive Events</code> performs an initial fetch and then subscribes to streams managed by the shared Protect config node. The config node keeps websocket channels and forwards matching updates to runtime nodes. In this mode, the input pin is hidden and listening starts automatically after deploy/restart.</p>
|
|
1211
1217
|
<p>For <code>Sensor</code>, <code>Camera</code>, <code>Light</code>, <code>Key Fob</code>, <code>Relay</code>, and <code>Alarm Hub</code> observables, <code>All</code> emits every event for the selected device. Choosing a specific observable normalizes the main output to a derived value and keeps the original context in <code>msg.details.raw</code>. Event observables emit <code>true/false</code>; sensor metrics such as <code>Temperature</code>, <code>Humidity</code>, <code>Light Level</code>, and <code>Battery Level</code> emit numeric values. <code>License Plate (LPR)</code> emits recognized plate text.</p>
|
|
1212
1218
|
<p>For <code>Key Fob</code>, the event list includes <code>Arm (1)</code>, <code>Night (2)</code>, <code>Disarm (3)</code>, <code>Panic (4)</code>, <code>Left</code>, and <code>Right</code>. The two side buttons have no printed number. Selecting one emits <code>true</code> only for that button; the original <code>sensorButtonPressed</code> event remains available in <code>msg.details.raw</code>.</p>
|
|
@@ -1312,4 +1318,4 @@ XY456ZT = Delivery van</code></pre>
|
|
|
1312
1318
|
"payload": null,
|
|
1313
1319
|
"error": { "message": "Request timed out" }
|
|
1314
1320
|
}</code></pre>
|
|
1315
|
-
</script>
|
|
1321
|
+
</script>
|
|
@@ -24,6 +24,7 @@ const {
|
|
|
24
24
|
} = require("./utils/common-utils");
|
|
25
25
|
const { parseKnownPlates, namePlate, matchesDetection, describeDetection } = require("./utils/unifi-protect-detections");
|
|
26
26
|
const { LICENSE_PLATE_EVENT_TYPES, extractLicensePlates, isLicensePlateEvent } = require("./utils/unifi-protect-lpr");
|
|
27
|
+
const { readAlarmState, matchesDeviceUpdate, mergeDeviceUpdate, buildRequestError } = require("./utils/unifi-protect-alarm");
|
|
27
28
|
const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
|
|
28
29
|
const LPR_FOLLOW_UP_DELAYS_MS = [150, 350, 750, 1500, 3000];
|
|
29
30
|
|
|
@@ -143,6 +144,12 @@ module.exports = function(RED) {
|
|
|
143
144
|
});
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
function protectErrorOutput(error) {
|
|
148
|
+
const message = buildErrorOutputMessage(error, node.name);
|
|
149
|
+
if (error.protectResponse) attachDetails(message, { response: error.protectResponse });
|
|
150
|
+
return message;
|
|
151
|
+
}
|
|
152
|
+
|
|
146
153
|
function resolveOutputDeviceName(payload) {
|
|
147
154
|
const extracted = extractDeviceNameFromPayload(payload);
|
|
148
155
|
if (extracted) {
|
|
@@ -324,7 +331,9 @@ module.exports = function(RED) {
|
|
|
324
331
|
|
|
325
332
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
326
333
|
setNodeStatus({ fill: "yellow", shape: "ring", text: `${response.statusCode}` });
|
|
327
|
-
|
|
334
|
+
const secrets = Object.values(node.server.credentials || {});
|
|
335
|
+
if (typeof node.server.getApiKey === "function") secrets.push(node.server.getApiKey());
|
|
336
|
+
throw buildRequestError(response, request.method, request.path, secrets);
|
|
328
337
|
}
|
|
329
338
|
|
|
330
339
|
if (response.payload && typeof response.payload === "object" && !Array.isArray(response.payload)) {
|
|
@@ -335,6 +344,13 @@ module.exports = function(RED) {
|
|
|
335
344
|
payload: response.payload
|
|
336
345
|
};
|
|
337
346
|
decorateOutputMessage(stateMsg, response.payload, `request:${capabilityId}`);
|
|
347
|
+
if (capabilityId === "getAlarmState") {
|
|
348
|
+
const alarmState = readAlarmState(deviceType, response.payload);
|
|
349
|
+
if (alarmState === undefined) {
|
|
350
|
+
throw new Error(`The ${deviceType} response has no supported alarm state. Check the Protect version and alarm mode; missing state does not mean disarmed.`);
|
|
351
|
+
}
|
|
352
|
+
stateMsg.payload = alarmState;
|
|
353
|
+
}
|
|
338
354
|
attachDetails(stateMsg, {
|
|
339
355
|
response: {
|
|
340
356
|
statusCode: response.statusCode,
|
|
@@ -410,9 +426,10 @@ module.exports = function(RED) {
|
|
|
410
426
|
}
|
|
411
427
|
|
|
412
428
|
fetchDeviceState(node.deviceType, node.deviceId, parseCapabilityConfig(node.capabilityConfig), node.send.bind(node), "startup").catch((error) => {
|
|
413
|
-
if (node.isObserving && (isPhotoObservation() || isLicensePlateObservation())) {
|
|
429
|
+
if (node.isObserving && (isPhotoObservation() || isLicensePlateObservation() || node.deviceType === "alarmHub" || node.deviceType === "nvr")) {
|
|
414
430
|
setNodeStatus({ fill: "red", shape: "ring", text: "check camera configuration" });
|
|
415
|
-
node.
|
|
431
|
+
if (node.deviceType === "alarmHub" || node.deviceType === "nvr") setNodeStatus({ fill: "red", shape: "ring", text: "alarm state unavailable" });
|
|
432
|
+
node.send([null, protectErrorOutput(error)]);
|
|
416
433
|
}
|
|
417
434
|
});
|
|
418
435
|
}
|
|
@@ -444,7 +461,7 @@ module.exports = function(RED) {
|
|
|
444
461
|
invokeCapability(node.send.bind(node), "interval")
|
|
445
462
|
.catch((error) => {
|
|
446
463
|
setNodeStatus({ fill: "red", shape: "ring", text: "auto error" });
|
|
447
|
-
node.send([null,
|
|
464
|
+
node.send([null, protectErrorOutput(error)]);
|
|
448
465
|
node.error(error);
|
|
449
466
|
})
|
|
450
467
|
.finally(() => {
|
|
@@ -474,7 +491,7 @@ module.exports = function(RED) {
|
|
|
474
491
|
}
|
|
475
492
|
} catch (error) {
|
|
476
493
|
setNodeStatus({ fill: "red", shape: "ring", text: "error" });
|
|
477
|
-
node.send([null,
|
|
494
|
+
node.send([null, protectErrorOutput(error)]);
|
|
478
495
|
if (typeof done === "function") {
|
|
479
496
|
done(error);
|
|
480
497
|
} else {
|
|
@@ -493,19 +510,32 @@ module.exports = function(RED) {
|
|
|
493
510
|
// Only react to device updates that match both the selected
|
|
494
511
|
// model family and the exact configured device id.
|
|
495
512
|
const deviceDefinition = getDeviceTypeDefinition(node.deviceType);
|
|
496
|
-
|
|
513
|
+
const alarmDevice = node.deviceType === "alarmHub" || node.deviceType === "nvr";
|
|
514
|
+
if (!deviceDefinition || (alarmDevice
|
|
515
|
+
? !matchesDeviceUpdate(node.deviceType, node.deviceId, item, deviceDefinition.modelKey)
|
|
516
|
+
: item.modelKey !== deviceDefinition.modelKey || item.id !== node.deviceId)) {
|
|
497
517
|
return;
|
|
498
518
|
}
|
|
499
519
|
|
|
500
|
-
|
|
520
|
+
if (alarmDevice && ["remove", "delete"].includes(update.type)) {
|
|
521
|
+
node.currentDevice = null;
|
|
522
|
+
node.currentObservableValue = undefined;
|
|
523
|
+
setNodeStatus({ fill: "yellow", shape: "ring", text: "device removed" });
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
node.currentDevice = alarmDevice ? mergeDeviceUpdate(node.currentDevice, item) : item;
|
|
501
527
|
if (isLicensePlateObservation() || isPhotoObservation()) return;
|
|
502
528
|
const capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
|
|
529
|
+
const observable = resolveConfiguredObservable(capabilityConfig);
|
|
530
|
+
// An unrelated partial update must not replay an old alarm value.
|
|
531
|
+
if ((node.deviceType === "alarmHub" && observable === "armed" && !(item.alarmHub && Object.prototype.hasOwnProperty.call(item.alarmHub, "armed")))
|
|
532
|
+
|| (node.deviceType === "nvr" && observable === "armStatus" && !(item.armMode && Object.prototype.hasOwnProperty.call(item.armMode, "status")))) return;
|
|
503
533
|
setNodeStatus({ fill: "green", shape: "dot", text: buildNodeStatus(node.deviceType, item) });
|
|
504
534
|
sendOutputs(node.send.bind(node), buildObservedStateMessage(
|
|
505
535
|
node.deviceType,
|
|
506
536
|
node.deviceId,
|
|
507
537
|
capabilityConfig,
|
|
508
|
-
|
|
538
|
+
node.currentDevice,
|
|
509
539
|
"devices",
|
|
510
540
|
{ updateType: update.type || "" },
|
|
511
541
|
update.type || "devices"
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
function readAlarmState(deviceType, device) {
|
|
4
|
+
if (deviceType === "alarmHub") {
|
|
5
|
+
const value = device && device.alarmHub && device.alarmHub.armed;
|
|
6
|
+
if (value === true || value === "on") return true;
|
|
7
|
+
if (value === false || value === "off") return false;
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
const status = device && device.armMode && device.armMode.status;
|
|
11
|
+
return deviceType === "nvr" && typeof status === "string" && status.trim()
|
|
12
|
+
? status : undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function matchesDeviceUpdate(deviceType, deviceId, item, modelKey) {
|
|
16
|
+
if (!item || item.id !== deviceId) return false;
|
|
17
|
+
// Partial updates may omit the model key. IDs still scope them to the
|
|
18
|
+
// configured device. Protect also represents Alarm Hubs as Link Stations.
|
|
19
|
+
return !item.modelKey || item.modelKey === modelKey
|
|
20
|
+
|| (deviceType === "alarmHub" && item.modelKey === "linkStation")
|
|
21
|
+
|| (deviceType === "alarmHub" && item.modelKey === "linkstation");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function mergeDeviceUpdate(previous, update) {
|
|
25
|
+
const result = { ...(previous || {}) };
|
|
26
|
+
for (const [key, value] of Object.entries(update)) {
|
|
27
|
+
if (["__proto__", "constructor", "prototype"].includes(key)) continue;
|
|
28
|
+
result[key] = value && typeof value === "object" && !Array.isArray(value)
|
|
29
|
+
? mergeDeviceUpdate(result[key] && typeof result[key] === "object" ? result[key] : null, value)
|
|
30
|
+
: value;
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function buildRequestError(response, method, path, secrets) {
|
|
36
|
+
const statusCode = Number(response.statusCode);
|
|
37
|
+
const body = response.payload;
|
|
38
|
+
const detail = body && typeof body === "object"
|
|
39
|
+
? (body.message || (body.error && body.error.message) || (typeof body.error === "string" ? body.error : ""))
|
|
40
|
+
: typeof body === "string" ? body : "";
|
|
41
|
+
let apiMessage = typeof detail === "string" ? detail : "";
|
|
42
|
+
for (const secret of secrets || []) {
|
|
43
|
+
if (typeof secret === "string" && secret) apiMessage = apiMessage.split(secret).join("[redacted]");
|
|
44
|
+
}
|
|
45
|
+
apiMessage = apiMessage.replace(/(bearer\s+)\S+/gi, "$1[redacted]")
|
|
46
|
+
.replace(/((?:password|token|api[-_ ]?key|authorization|cookie)\s*[=:]\s*)[^\s,;]+/gi, "$1[redacted]")
|
|
47
|
+
.replace(/[\r\n\t]+/g, " ").slice(0, 500);
|
|
48
|
+
let hint = "";
|
|
49
|
+
if (statusCode === 401) hint = " Check the Protect API key and its validity.";
|
|
50
|
+
if (statusCode === 403) hint = " Check the Protect permissions of the account associated with the API key.";
|
|
51
|
+
if (statusCode === 400 && path.startsWith("/v1/arm-profiles")) {
|
|
52
|
+
hint = " Arm profile commands require Protect's local Alarm Manager; check the alarm mode and selected profile. A 400 response alone does not identify a permission failure.";
|
|
53
|
+
}
|
|
54
|
+
const error = new Error(`UniFi Protect request failed with status ${statusCode}.${hint}${apiMessage ? ` API: ${apiMessage}` : ""}`);
|
|
55
|
+
error.protectResponse = { statusCode, method, path, ...(apiMessage ? { apiMessage } : {}) };
|
|
56
|
+
return error;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
module.exports = { readAlarmState, matchesDeviceUpdate, mergeDeviceUpdate, buildRequestError };
|
|
@@ -9,6 +9,7 @@ const {
|
|
|
9
9
|
} = require("./unifi-protect-field-metadata");
|
|
10
10
|
const { DETECTION_FIELD, KNOWN_PLATES_FIELD } = require("./unifi-protect-detections");
|
|
11
11
|
const { LICENSE_PLATE_EVENT_TYPES, extractLicensePlates } = require("./unifi-protect-lpr");
|
|
12
|
+
const { readAlarmState } = require("./unifi-protect-alarm");
|
|
12
13
|
|
|
13
14
|
// Central Protect registry used by:
|
|
14
15
|
// - the editor for device/capability discovery
|
|
@@ -360,6 +361,7 @@ const RELAY_OBSERVABLE_DEFINITIONS = [
|
|
|
360
361
|
];
|
|
361
362
|
|
|
362
363
|
const ALARM_HUB_OBSERVABLE_DEFINITIONS = [
|
|
364
|
+
{ id: "armed", label: "Armed", eventTypes: [] },
|
|
363
365
|
{
|
|
364
366
|
id: "motion",
|
|
365
367
|
label: "Motion input",
|
|
@@ -724,6 +726,7 @@ const TYPE_CAPABILITIES = {
|
|
|
724
726
|
createSetPropertyCapability()
|
|
725
727
|
],
|
|
726
728
|
nvr: [
|
|
729
|
+
{ id: "getAlarmState", label: "Read Alarm State", description: "Read the local Alarm Manager status from the NVR.", method: "GET", pathKind: "detail", mode: "request" },
|
|
727
730
|
{
|
|
728
731
|
id: "getApplicationInfo",
|
|
729
732
|
label: "Read Application Info",
|
|
@@ -792,6 +795,7 @@ const TYPE_CAPABILITIES = {
|
|
|
792
795
|
bridge: [],
|
|
793
796
|
linkStation: [],
|
|
794
797
|
alarmHub: [
|
|
798
|
+
{ id: "getAlarmState", label: "Read Alarm State", description: "Read the selected Alarm Hub's armed state.", method: "GET", pathKind: "detail", mode: "request" },
|
|
795
799
|
{
|
|
796
800
|
id: "triggerAlarmHubOutput",
|
|
797
801
|
label: "Trigger Alarm Hub Output",
|
|
@@ -1923,7 +1927,8 @@ function getObservableDefinitions(deviceType) {
|
|
|
1923
1927
|
light: LIGHT_OBSERVABLE_DEFINITIONS,
|
|
1924
1928
|
fob: FOB_OBSERVABLE_DEFINITIONS,
|
|
1925
1929
|
relay: RELAY_OBSERVABLE_DEFINITIONS,
|
|
1926
|
-
alarmHub: ALARM_HUB_OBSERVABLE_DEFINITIONS
|
|
1930
|
+
alarmHub: ALARM_HUB_OBSERVABLE_DEFINITIONS,
|
|
1931
|
+
nvr: [{ id: "armStatus", label: "Alarm status (local)", eventTypes: [] }]
|
|
1927
1932
|
};
|
|
1928
1933
|
|
|
1929
1934
|
return definitionsByDeviceType[String(deviceType || "").trim()] || [];
|
|
@@ -1952,6 +1957,10 @@ function resolveSelectedObservable(options, configuredObservable) {
|
|
|
1952
1957
|
}
|
|
1953
1958
|
|
|
1954
1959
|
function resolveObservableState(deviceType, device, observable, fallbackValue) {
|
|
1960
|
+
if ((deviceType === "alarmHub" && observable === "armed") || (deviceType === "nvr" && observable === "armStatus")) {
|
|
1961
|
+
const value = readAlarmState(deviceType, device);
|
|
1962
|
+
return value === undefined ? fallbackValue : value;
|
|
1963
|
+
}
|
|
1955
1964
|
if (deviceType === "sensor") {
|
|
1956
1965
|
return resolveSensorObservableState(device, observable, fallbackValue);
|
|
1957
1966
|
}
|
|
@@ -28,6 +28,13 @@ const COMMON_FIELD_METADATA = {
|
|
|
28
28
|
|
|
29
29
|
// Device-family-specific metadata overrides or extends the common dictionary.
|
|
30
30
|
const TYPE_FIELD_METADATA = {
|
|
31
|
+
nvr: {
|
|
32
|
+
armStatus: {
|
|
33
|
+
label: "Alarm Status (Local)",
|
|
34
|
+
description: "Local Alarm Manager status from armMode.status. Kept as a string, including transitional states; it may differ from an Alarm Hub's armed state.",
|
|
35
|
+
source: "official"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
31
38
|
camera: {
|
|
32
39
|
isMicEnabled: {
|
|
33
40
|
label: "Microphone Enabled",
|
|
@@ -366,6 +373,11 @@ const OBSERVABLE_METADATA = {
|
|
|
366
373
|
}
|
|
367
374
|
},
|
|
368
375
|
alarmHub: {
|
|
376
|
+
armed: {
|
|
377
|
+
label: "Armed",
|
|
378
|
+
description: "Current Alarm Hub armed state: on becomes true and off becomes false. Updated by device state messages, not a dedicated arm/disarm event.",
|
|
379
|
+
source: "official"
|
|
380
|
+
},
|
|
369
381
|
motion: {
|
|
370
382
|
label: "Motion Input",
|
|
371
383
|
description: "True while an Alarm Hub motion input is active.",
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Shared resilience for UniFi WebSocket streams. A ping/pong heartbeat detects
|
|
4
|
+
// half-open connections that never emit "close", and an exponential backoff
|
|
5
|
+
// spaces out reconnects while a controller restarts or upgrades.
|
|
6
|
+
|
|
7
|
+
const HEARTBEAT_INTERVAL_MS = 30000;
|
|
8
|
+
const RECONNECT_BASE_DELAY_MS = 5000;
|
|
9
|
+
const RECONNECT_MAX_DELAY_MS = 60000;
|
|
10
|
+
|
|
11
|
+
const heartbeatTimers = new WeakMap();
|
|
12
|
+
|
|
13
|
+
function stopHeartbeat(ws) {
|
|
14
|
+
if (!ws || typeof ws !== "object") {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
const timer = heartbeatTimers.get(ws);
|
|
18
|
+
if (timer) {
|
|
19
|
+
clearInterval(timer);
|
|
20
|
+
heartbeatTimers.delete(ws);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function attachHeartbeat(ws, options = {}) {
|
|
25
|
+
if (!ws || typeof ws.on !== "function") {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
stopHeartbeat(ws);
|
|
30
|
+
const intervalMs = Number(options.intervalMs) > 0 ? Number(options.intervalMs) : HEARTBEAT_INTERVAL_MS;
|
|
31
|
+
let alive = true;
|
|
32
|
+
const markAlive = () => {
|
|
33
|
+
alive = true;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const timer = setInterval(() => {
|
|
37
|
+
if (!alive) {
|
|
38
|
+
// Nothing received since the previous ping: the peer is gone even
|
|
39
|
+
// though the socket still looks open. terminate() emits "close",
|
|
40
|
+
// which lets the owner schedule its normal reconnect.
|
|
41
|
+
stopHeartbeat(ws);
|
|
42
|
+
try {
|
|
43
|
+
ws.terminate();
|
|
44
|
+
} catch (error) {
|
|
45
|
+
}
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
alive = false;
|
|
49
|
+
try {
|
|
50
|
+
ws.ping();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
}
|
|
53
|
+
}, intervalMs);
|
|
54
|
+
if (typeof timer.unref === "function") {
|
|
55
|
+
timer.unref();
|
|
56
|
+
}
|
|
57
|
+
heartbeatTimers.set(ws, timer);
|
|
58
|
+
|
|
59
|
+
ws.on("pong", markAlive);
|
|
60
|
+
ws.on("message", markAlive);
|
|
61
|
+
ws.on("close", () => stopHeartbeat(ws));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createReconnectBackoff(options = {}) {
|
|
65
|
+
const baseMs = Number(options.baseMs) > 0 ? Number(options.baseMs) : RECONNECT_BASE_DELAY_MS;
|
|
66
|
+
const maxMs = Number(options.maxMs) > 0 ? Number(options.maxMs) : RECONNECT_MAX_DELAY_MS;
|
|
67
|
+
const random = typeof options.random === "function" ? options.random : Math.random;
|
|
68
|
+
let attempts = 0;
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
nextDelay() {
|
|
72
|
+
const delay = Math.min(maxMs, baseMs * (2 ** attempts));
|
|
73
|
+
attempts += 1;
|
|
74
|
+
// Up to 20% jitter keeps several config nodes from reconnecting in
|
|
75
|
+
// lockstep without ever exceeding the maximum delay.
|
|
76
|
+
return Math.round(delay * (0.8 + (random() * 0.2)));
|
|
77
|
+
},
|
|
78
|
+
reset() {
|
|
79
|
+
attempts = 0;
|
|
80
|
+
},
|
|
81
|
+
get attempts() {
|
|
82
|
+
return attempts;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = {
|
|
88
|
+
HEARTBEAT_INTERVAL_MS,
|
|
89
|
+
RECONNECT_BASE_DELAY_MS,
|
|
90
|
+
RECONNECT_MAX_DELAY_MS,
|
|
91
|
+
attachHeartbeat,
|
|
92
|
+
stopHeartbeat,
|
|
93
|
+
createReconnectBackoff
|
|
94
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-red-contrib-unifi-ultimate",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.19",
|
|
4
4
|
"description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
|
|
5
5
|
"files": [
|
|
6
6
|
"nodes/",
|
|
@@ -66,12 +66,11 @@
|
|
|
66
66
|
}
|
|
67
67
|
},
|
|
68
68
|
"scripts": {
|
|
69
|
-
"test": "node
|
|
69
|
+
"test": "node tests/check-syntax.js && jest",
|
|
70
70
|
"registry:discover:network": "node scripts/discover-unifi-network-registry.js",
|
|
71
71
|
"registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
|
|
72
72
|
"registry:discover:access": "node scripts/discover-unifi-access-registry.js"
|
|
73
73
|
},
|
|
74
|
-
"main": "index.js",
|
|
75
74
|
"directories": {
|
|
76
75
|
"example": "examples"
|
|
77
76
|
},
|