node-red-contrib-unifi-ultimate 1.1.18 → 1.1.21
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 +3 -0
- package/nodes/unifi-access-config.js +19 -7
- package/nodes/unifi-network-config.js +145 -37
- package/nodes/unifi-network-device.js +2 -0
- package/nodes/unifi-protect-config.js +11 -3
- package/nodes/unifi-protect-device.html +25 -1
- package/nodes/unifi-protect-device.js +9 -6
- package/nodes/utils/unifi-protect-device-registry.js +178 -9
- package/nodes/utils/unifi-protect-field-metadata.js +12 -1
- package/nodes/utils/unifi-websocket-resilience.js +94 -0
- package/package.json +2 -3
- package/scripts/unifi-registry-discovery-common.js +16 -16
package/README.md
CHANGED
|
@@ -149,6 +149,9 @@ 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
|
+
- 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.
|
|
152
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).
|
|
153
156
|
|
|
154
157
|
### Read license plates (LPR)
|
|
@@ -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();
|
|
@@ -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
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const { registerConnectionCheck } = require("./utils/unifi-connection-check");
|
|
4
4
|
const { actionGuidance } = require("./utils/unifi-action-guidance");
|
|
5
5
|
const { buildRequestError } = require("./utils/unifi-protect-alarm");
|
|
6
|
+
const { attachHeartbeat, stopHeartbeat, createReconnectBackoff } = require("./utils/unifi-websocket-resilience");
|
|
6
7
|
|
|
7
8
|
const {
|
|
8
9
|
buildBaseUrlFromHost,
|
|
@@ -204,6 +205,7 @@ module.exports = function(RED) {
|
|
|
204
205
|
node.wsDevices = null;
|
|
205
206
|
node.wsEvents = null;
|
|
206
207
|
node.reconnectTimer = null;
|
|
208
|
+
node.reconnectBackoff = createReconnectBackoff();
|
|
207
209
|
node.isClosing = false;
|
|
208
210
|
node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
209
211
|
node.knxAiCameraRefresh = null;
|
|
@@ -875,8 +877,8 @@ module.exports = function(RED) {
|
|
|
875
877
|
return;
|
|
876
878
|
}
|
|
877
879
|
|
|
878
|
-
// Back off
|
|
879
|
-
//
|
|
880
|
+
// Back off exponentially so temporary controller restarts do not
|
|
881
|
+
// cause a tight reconnect loop.
|
|
880
882
|
node.reconnectTimer = setTimeout(() => {
|
|
881
883
|
node.reconnectTimer = null;
|
|
882
884
|
try {
|
|
@@ -884,7 +886,7 @@ module.exports = function(RED) {
|
|
|
884
886
|
} catch (error) {
|
|
885
887
|
node.warn(`Protect websocket reconnect failed: ${error && error.message ? error.message : error}`);
|
|
886
888
|
}
|
|
887
|
-
},
|
|
889
|
+
}, node.reconnectBackoff.nextDelay());
|
|
888
890
|
};
|
|
889
891
|
|
|
890
892
|
node.attachSocket = (kind, path, handler) => {
|
|
@@ -918,6 +920,11 @@ module.exports = function(RED) {
|
|
|
918
920
|
return;
|
|
919
921
|
}
|
|
920
922
|
|
|
923
|
+
ws.on("open", () => {
|
|
924
|
+
node.reconnectBackoff.reset();
|
|
925
|
+
});
|
|
926
|
+
attachHeartbeat(ws);
|
|
927
|
+
|
|
921
928
|
ws.on("message", (rawData) => {
|
|
922
929
|
try {
|
|
923
930
|
// Protect streams send JSON messages; malformed frames are
|
|
@@ -972,6 +979,7 @@ module.exports = function(RED) {
|
|
|
972
979
|
// Clear ownership before close so the close callback knows this was
|
|
973
980
|
// intentional and does not schedule an unnecessary reconnect.
|
|
974
981
|
node[propertyName] = null;
|
|
982
|
+
stopHeartbeat(socket);
|
|
975
983
|
try {
|
|
976
984
|
socket.close();
|
|
977
985
|
} catch (error) {
|
|
@@ -1210,6 +1210,7 @@
|
|
|
1210
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>
|
|
1211
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>
|
|
1212
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>NVR → Trigger Alarm Manager Webhook</code> triggers the Alarm Manager alarms whose webhook trigger uses the same <b>Webhook ID</b>. Configure the alarm in Protect first; the ID is case-sensitive text, for example <code>garage-door</code>. A successful request returns HTTP 204 with an empty <code>msg.payload</code>.</p>
|
|
1213
1214
|
<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
1215
|
<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
1216
|
<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>
|
|
@@ -1217,6 +1218,8 @@
|
|
|
1217
1218
|
<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>
|
|
1218
1219
|
<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>
|
|
1219
1220
|
<p>The event list also covers the official Protect event families for NFC and fingerprint scans on supported cameras; vape, smoke/CO health, and button events on sensors; relay input changes; and Alarm Hub motion, entry, smoke, glass-break, emergency-button, tamper, relay, and battery events. Resource families without a granular official event type retain only <code>All</code>.</p>
|
|
1221
|
+
<p><code>Camera → Digital Input</code> follows the digital input of ONVIF cameras that expose one: <code>true</code> when the circuit closes, <code>false</code> when it opens. With several inputs, use <code>msg.details.raw.event.metadata.inputChannel</code> to tell them apart. <code>Alarm Hub → Hub Tamper</code> reports the hub's own enclosure: <code>true</code> when tampered, <code>false</code> when restored. <code>Tamper</code> remains the tamper state of the hub inputs.</p>
|
|
1222
|
+
<p>When a sensor reports its features (Protect 7.3 and later), the event list shows only the events the sensor supports. A previously saved event remains selectable. Older Protect versions show the full list.</p>
|
|
1220
1223
|
<p>To read plates, select <code>Camera</code> → <code>Receive Events</code> → <code>License Plate (LPR)</code>. Use an LPR-capable camera and enable license plate recognition in Protect. Open the shared <b>Connection</b> and enter its optional <b>Local User</b> and <b>Local Password</b> for a local UniFi OS account that can view the camera's recordings. All Protect nodes using that connection share this account. The official event stream identifies license plate detections but does not include OCR text in its documented schema, so the node retrieves the matching event's metadata through Protect's local, unofficial events API. Compatibility of this lookup depends on the Protect version.</p>
|
|
1221
1224
|
<p>LPR emits the first available reading immediately, including low-confidence text, as a string such as <code>"AB123CD"</code> in <code>msg.payload</code>, with <code>msg.eventName = "licensePlate"</code>. Text already present in a live event bypasses any outstanding HTTP lookup. Otherwise the node starts looking for OCR as soon as a vehicle is detected, using a prepared local session without waiting for the live LPR classification or for the event to end. Only actual plate metadata is emitted.</p>
|
|
1222
1225
|
<p>After a detection/update, up to five follow-up reads look for missing or improved OCR, with delays of 150, 350, 750, 1500 and 3000 milliseconds between requests. Corrected text, additional plates and higher confidence for the same text produce another message. Identical readings and lower confidence for previously emitted text are suppressed. The first text still depends on when Protect makes OCR available; a later reading is not a guarantee of accuracy.</p>
|
|
@@ -1255,11 +1258,32 @@ msg.payload = [{ eventId: "event-123", cameraId: "camera-1",
|
|
|
1255
1258
|
XY456ZT = Delivery van</code></pre>
|
|
1256
1259
|
<p>LPR keeps the recognized text in <code>msg.payload</code> and adds <code>msg.knownPlate</code> (boolean), <code>msg.plateName</code> (only for a match), and <code>known</code>/<code>name</code> in <code>msg.details.lpr</code>. Photo/history detections expose these fields in each <code>plates</code> entry. Unknown plates still produce messages.</p>
|
|
1257
1260
|
|
|
1261
|
+
<h3>POS transactions</h3>
|
|
1262
|
+
<p><code>Camera → Send POS Transaction</code> records a point of sale transaction as an event on the selected camera, so Protect overlays it on the recorded footage. The transaction comes from <code>msg.payload</code>; the optional <b>Default currency</b> applies when <code>msg.payload.currency</code> is missing. The API key needs write access to the camera.</p>
|
|
1263
|
+
<ul>
|
|
1264
|
+
<li><code>type</code> (required): <code>"sale"</code> or <code>"refund"</code>.</li>
|
|
1265
|
+
<li><code>externalId</code> (required): your POS transaction id, unique per camera. Protect ignores a repeated id for a short time and returns the existing event.</li>
|
|
1266
|
+
<li><code>amount</code> (required): total, a number of 0 or more.</li>
|
|
1267
|
+
<li><code>currency</code>: ISO 4217 code such as <code>EUR</code>.</li>
|
|
1268
|
+
<li><code>lineItems</code>: up to 200 <code>{ title, quantity }</code> entries.</li>
|
|
1269
|
+
<li><code>location</code>: <code>{ id, name }</code> of the register or shop.</li>
|
|
1270
|
+
<li><code>paymentTypes</code>: up to 20 payment method names.</li>
|
|
1271
|
+
<li><code>timestamp</code>: epoch milliseconds or a date string, within the last 24 hours. Defaults to now.</li>
|
|
1272
|
+
</ul>
|
|
1273
|
+
<pre><code>msg.payload = {
|
|
1274
|
+
type: "sale", externalId: "R1-000123", amount: 12.5, currency: "EUR",
|
|
1275
|
+
lineItems: [{ title: "Espresso", quantity: 2 }],
|
|
1276
|
+
location: { id: "r1", name: "Register 1" }, paymentTypes: ["card"]
|
|
1277
|
+
}
|
|
1278
|
+
// Output 1
|
|
1279
|
+
msg.payload = { created: true, eventId: "event-id" }</code></pre>
|
|
1280
|
+
<p>The overlay appears only where the camera was recording during the transaction. <code>created: false</code> means the same <code>externalId</code> was already recorded. HTTP 409 means the same transaction is still being processed; retry shortly.</p>
|
|
1281
|
+
|
|
1258
1282
|
<h3>Input</h3>
|
|
1259
1283
|
<ul>
|
|
1260
1284
|
<li>When <code>Receive Events</code> is selected, the input pin is hidden.</li>
|
|
1261
1285
|
<li>Any incoming message triggers the configured action.</li>
|
|
1262
|
-
<li>Input message properties are ignored by this node
|
|
1286
|
+
<li>Input message properties are ignored by this node, except <code>msg.payload</code> for <code>Send POS Transaction</code>.</li>
|
|
1263
1287
|
</ul>
|
|
1264
1288
|
|
|
1265
1289
|
<h3>Outputs</h3>
|
|
@@ -269,13 +269,14 @@ module.exports = function(RED) {
|
|
|
269
269
|
sendOutputs(send, stateMsg, null);
|
|
270
270
|
}
|
|
271
271
|
|
|
272
|
-
async function invokeCapability(send, triggerSource) {
|
|
272
|
+
async function invokeCapability(send, triggerSource, inputPayload) {
|
|
273
273
|
if (!node.server) {
|
|
274
274
|
throw new Error("Unifi Protect configuration is missing.");
|
|
275
275
|
}
|
|
276
276
|
|
|
277
277
|
// The incoming message is only a trigger. The node always uses the
|
|
278
|
-
// device, capability and options configured in the editor
|
|
278
|
+
// device, capability and options configured in the editor; only
|
|
279
|
+
// actions declaring usesInputPayload read msg.payload.
|
|
279
280
|
const deviceType = resolveDeviceType(node.deviceType);
|
|
280
281
|
const deviceId = resolveDeviceId(node.deviceId);
|
|
281
282
|
const capabilityId = resolveCapabilityId(node.capability);
|
|
@@ -315,7 +316,7 @@ module.exports = function(RED) {
|
|
|
315
316
|
return;
|
|
316
317
|
}
|
|
317
318
|
|
|
318
|
-
const execution = composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, selectedDevice);
|
|
319
|
+
const execution = composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, selectedDevice, inputPayload);
|
|
319
320
|
const request = buildCapabilityRequest(deviceType, capabilityId, deviceId, execution.params, selectedDevice);
|
|
320
321
|
|
|
321
322
|
setNodeStatus({ fill: "blue", shape: "dot", text: `${capability.label}` });
|
|
@@ -479,13 +480,13 @@ module.exports = function(RED) {
|
|
|
479
480
|
setNodeStatus({ fill: "grey", shape: "ring", text: `every ${node.autoEmitIntervalSeconds}s` });
|
|
480
481
|
}
|
|
481
482
|
|
|
482
|
-
node.on("input", async function(
|
|
483
|
+
node.on("input", async function(msg, send, done) {
|
|
483
484
|
send = send || function() {
|
|
484
485
|
node.send.apply(node, arguments);
|
|
485
486
|
};
|
|
486
487
|
|
|
487
488
|
try {
|
|
488
|
-
await invokeCapability(send, "manual-refresh");
|
|
489
|
+
await invokeCapability(send, "manual-refresh", msg && msg.payload);
|
|
489
490
|
if (typeof done === "function") {
|
|
490
491
|
done();
|
|
491
492
|
}
|
|
@@ -528,7 +529,9 @@ module.exports = function(RED) {
|
|
|
528
529
|
const capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
|
|
529
530
|
const observable = resolveConfiguredObservable(capabilityConfig);
|
|
530
531
|
// An unrelated partial update must not replay an old alarm value.
|
|
531
|
-
|
|
532
|
+
// Hub tamper changes arrive as alarmHubDeviceTamper events.
|
|
533
|
+
if ((node.deviceType === "alarmHub" && observable === "deviceTamper")
|
|
534
|
+
|| (node.deviceType === "alarmHub" && observable === "armed" && !(item.alarmHub && Object.prototype.hasOwnProperty.call(item.alarmHub, "armed")))
|
|
532
535
|
|| (node.deviceType === "nvr" && observable === "armStatus" && !(item.armMode && Object.prototype.hasOwnProperty.call(item.armMode, "status")))) return;
|
|
533
536
|
setNodeStatus({ fill: "green", shape: "dot", text: buildNodeStatus(node.deviceType, item) });
|
|
534
537
|
sendOutputs(node.send.bind(node), buildObservedStateMessage(
|
|
@@ -256,6 +256,25 @@ const SENSOR_OBSERVABLE_DEFINITIONS = [
|
|
|
256
256
|
}
|
|
257
257
|
];
|
|
258
258
|
|
|
259
|
+
// Newer Protect versions report sensor.featureFlags.<capability>.channelCount.
|
|
260
|
+
// Observables without an entry here are shown for every sensor.
|
|
261
|
+
const SENSOR_OBSERVABLE_FEATURE_FLAGS = {
|
|
262
|
+
contact: "open",
|
|
263
|
+
motion: "motion",
|
|
264
|
+
alarm: "smoke",
|
|
265
|
+
waterLeak: "waterLeak",
|
|
266
|
+
tamper: "tamper",
|
|
267
|
+
smokeTest: "smoke",
|
|
268
|
+
smokeBatteryLow: "smoke",
|
|
269
|
+
smokeNeedsCleaning: "smoke",
|
|
270
|
+
smokeFault: "smoke",
|
|
271
|
+
coFault: "smoke",
|
|
272
|
+
smokeEndOfLife: "smoke",
|
|
273
|
+
temperature: "temperature",
|
|
274
|
+
humidity: "humidity",
|
|
275
|
+
lightLevel: "light"
|
|
276
|
+
};
|
|
277
|
+
|
|
259
278
|
const CAMERA_OBSERVABLE_DEFINITIONS = [
|
|
260
279
|
{
|
|
261
280
|
id: "licensePlate",
|
|
@@ -303,6 +322,11 @@ const CAMERA_OBSERVABLE_DEFINITIONS = [
|
|
|
303
322
|
label: "Fingerprint identified",
|
|
304
323
|
eventTypes: ["fingerprintIdentified"],
|
|
305
324
|
occurrence: true
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
id: "digitalInput",
|
|
328
|
+
label: "Digital input",
|
|
329
|
+
eventTypes: ["cameraDigitalInputChanged"]
|
|
306
330
|
}
|
|
307
331
|
];
|
|
308
332
|
|
|
@@ -393,6 +417,11 @@ const ALARM_HUB_OBSERVABLE_DEFINITIONS = [
|
|
|
393
417
|
label: "Tamper",
|
|
394
418
|
eventTypes: ["alarmHubTamper"]
|
|
395
419
|
},
|
|
420
|
+
{
|
|
421
|
+
id: "deviceTamper",
|
|
422
|
+
label: "Hub tamper",
|
|
423
|
+
eventTypes: ["alarmHubDeviceTamper"]
|
|
424
|
+
},
|
|
396
425
|
{
|
|
397
426
|
id: "relaySwitched",
|
|
398
427
|
label: "Relay switched",
|
|
@@ -682,6 +711,30 @@ const TYPE_CAPABILITIES = {
|
|
|
682
711
|
}
|
|
683
712
|
})
|
|
684
713
|
},
|
|
714
|
+
{
|
|
715
|
+
id: "sendPosTransaction",
|
|
716
|
+
label: "Send POS Transaction",
|
|
717
|
+
description: "Record a point of sale transaction from msg.payload as a camera event.",
|
|
718
|
+
method: "POST",
|
|
719
|
+
path: "/v1/pos/cameras/:id/transactions",
|
|
720
|
+
mode: "request",
|
|
721
|
+
usesInputPayload: true,
|
|
722
|
+
useConfiguredPayload: true,
|
|
723
|
+
editor: {
|
|
724
|
+
fields: [
|
|
725
|
+
{
|
|
726
|
+
id: "currency",
|
|
727
|
+
label: "Default currency",
|
|
728
|
+
type: "text",
|
|
729
|
+
placeholder: "EUR",
|
|
730
|
+
tip: "Used when msg.payload.currency is missing."
|
|
731
|
+
}
|
|
732
|
+
]
|
|
733
|
+
},
|
|
734
|
+
requestComposer: ({ capabilityConfig, inputPayload }) => ({
|
|
735
|
+
payload: buildPosTransactionPayload(inputPayload, capabilityConfig)
|
|
736
|
+
})
|
|
737
|
+
},
|
|
685
738
|
createSetPropertyCapability()
|
|
686
739
|
],
|
|
687
740
|
liveview: [
|
|
@@ -790,6 +843,36 @@ const TYPE_CAPABILITIES = {
|
|
|
790
843
|
path: "/v1/arm-profiles/disable",
|
|
791
844
|
mode: "request",
|
|
792
845
|
ignoreInputPayload: true
|
|
846
|
+
},
|
|
847
|
+
{
|
|
848
|
+
id: "triggerAlarmWebhook",
|
|
849
|
+
label: "Trigger Alarm Manager Webhook",
|
|
850
|
+
description: "Trigger the Alarm Manager alarms configured with the same webhook ID.",
|
|
851
|
+
method: "POST",
|
|
852
|
+
path: "/v1/alarm-manager/webhook/:triggerId",
|
|
853
|
+
mode: "request",
|
|
854
|
+
parameterNames: ["triggerId"],
|
|
855
|
+
ignoreInputPayload: true,
|
|
856
|
+
editor: {
|
|
857
|
+
fields: [
|
|
858
|
+
{
|
|
859
|
+
id: "triggerId",
|
|
860
|
+
label: "Webhook ID",
|
|
861
|
+
type: "text",
|
|
862
|
+
placeholder: "garage-door"
|
|
863
|
+
}
|
|
864
|
+
]
|
|
865
|
+
},
|
|
866
|
+
requestComposer: ({ capabilityConfig }) => {
|
|
867
|
+
const triggerId = String(capabilityConfig.triggerId || "").trim();
|
|
868
|
+
if (!triggerId) {
|
|
869
|
+
throw new Error("Enter the Alarm Manager webhook ID before using this action.");
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
return {
|
|
873
|
+
params: { triggerId }
|
|
874
|
+
};
|
|
875
|
+
}
|
|
793
876
|
}
|
|
794
877
|
],
|
|
795
878
|
bridge: [],
|
|
@@ -1099,14 +1182,15 @@ function buildCapabilityRequest(deviceType, capabilityId, deviceId, params, devi
|
|
|
1099
1182
|
};
|
|
1100
1183
|
}
|
|
1101
1184
|
|
|
1102
|
-
function composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, device) {
|
|
1185
|
+
function composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, device, inputPayload) {
|
|
1103
1186
|
const capability = getCapabilityDefinition(deviceType, capabilityId, device);
|
|
1104
1187
|
if (!capability) {
|
|
1105
1188
|
throw new Error(`Unsupported capability '${capabilityId}' for device type '${deviceType}'.`);
|
|
1106
1189
|
}
|
|
1107
1190
|
|
|
1108
1191
|
// Input messages are triggers only. Execution data comes from the editor
|
|
1109
|
-
// configuration and capability defaults
|
|
1192
|
+
// configuration and capability defaults, except for actions that declare
|
|
1193
|
+
// usesInputPayload because their data changes on every message.
|
|
1110
1194
|
if (typeof capability.requestComposer !== "function") {
|
|
1111
1195
|
return {
|
|
1112
1196
|
params: {},
|
|
@@ -1117,7 +1201,8 @@ function composeCapabilityExecution(deviceType, capabilityId, capabilityConfig,
|
|
|
1117
1201
|
}
|
|
1118
1202
|
|
|
1119
1203
|
const composedRequest = capability.requestComposer({
|
|
1120
|
-
capabilityConfig: normalizeObject(capabilityConfig)
|
|
1204
|
+
capabilityConfig: normalizeObject(capabilityConfig),
|
|
1205
|
+
inputPayload: capability.usesInputPayload ? inputPayload : undefined
|
|
1121
1206
|
}) || {};
|
|
1122
1207
|
|
|
1123
1208
|
const params = {
|
|
@@ -1521,7 +1606,7 @@ async function buildObservableFields(deviceType, context) {
|
|
|
1521
1606
|
// Observables let the generic "Receive Events" capability expose a typed
|
|
1522
1607
|
// value (boolean, number or plate text) tailored to the selected device.
|
|
1523
1608
|
const capabilityConfig = normalizeObject(context && context.capabilityConfig);
|
|
1524
|
-
const observableOptions = getObservableOptions(deviceType);
|
|
1609
|
+
const observableOptions = getObservableOptions(deviceType, context && context.device, capabilityConfig.observable);
|
|
1525
1610
|
const selectedObservable = resolveSelectedObservable(observableOptions, capabilityConfig.observable);
|
|
1526
1611
|
const fields = [
|
|
1527
1612
|
{
|
|
@@ -1907,6 +1992,48 @@ function buildDoorbellMessagePayload(capabilityConfig) {
|
|
|
1907
1992
|
return payload;
|
|
1908
1993
|
}
|
|
1909
1994
|
|
|
1995
|
+
function buildPosTransactionPayload(inputPayload, capabilityConfig) {
|
|
1996
|
+
// Protect rejects unknown keys, so copy only the documented fields.
|
|
1997
|
+
const transaction = normalizeObject(inputPayload);
|
|
1998
|
+
const type = String(transaction.type || "").trim().toLowerCase();
|
|
1999
|
+
if (type !== "sale" && type !== "refund") {
|
|
2000
|
+
throw new Error("msg.payload.type must be 'sale' or 'refund'.");
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
const externalId = String(transaction.externalId === undefined || transaction.externalId === null ? "" : transaction.externalId).trim();
|
|
2004
|
+
if (!externalId) {
|
|
2005
|
+
throw new Error("msg.payload.externalId is required: use your POS transaction id.");
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
const amount = typeof transaction.amount === "string" ? Number(transaction.amount.trim()) : transaction.amount;
|
|
2009
|
+
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
|
|
2010
|
+
throw new Error("msg.payload.amount must be a number greater than or equal to 0.");
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
const payload = { type, externalId, amount };
|
|
2014
|
+
const currency = String(transaction.currency || capabilityConfig.currency || "").trim().toUpperCase();
|
|
2015
|
+
if (currency) {
|
|
2016
|
+
payload.currency = currency;
|
|
2017
|
+
}
|
|
2018
|
+
["lineItems", "location", "paymentTypes"].forEach((key) => {
|
|
2019
|
+
if (transaction[key] !== undefined && transaction[key] !== null) {
|
|
2020
|
+
payload[key] = transaction[key];
|
|
2021
|
+
}
|
|
2022
|
+
});
|
|
2023
|
+
if (transaction.timestamp !== undefined && transaction.timestamp !== null && transaction.timestamp !== "") {
|
|
2024
|
+
const rawTimestamp = transaction.timestamp;
|
|
2025
|
+
const timestamp = typeof rawTimestamp === "number" || /^\d+$/.test(String(rawTimestamp).trim())
|
|
2026
|
+
? Number(rawTimestamp)
|
|
2027
|
+
: new Date(rawTimestamp).getTime();
|
|
2028
|
+
if (!Number.isInteger(timestamp) || timestamp <= 0) {
|
|
2029
|
+
throw new Error("msg.payload.timestamp must be epoch milliseconds or a date string.");
|
|
2030
|
+
}
|
|
2031
|
+
payload.timestamp = timestamp;
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
return payload;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
1910
2037
|
function parseResetAtValue(value) {
|
|
1911
2038
|
const normalized = String(value === undefined || value === null ? "" : value).trim();
|
|
1912
2039
|
if (normalized === "") {
|
|
@@ -1934,15 +2061,32 @@ function getObservableDefinitions(deviceType) {
|
|
|
1934
2061
|
return definitionsByDeviceType[String(deviceType || "").trim()] || [];
|
|
1935
2062
|
}
|
|
1936
2063
|
|
|
1937
|
-
function getObservableOptions(deviceType) {
|
|
1938
|
-
const specificOptions = getObservableDefinitions(deviceType)
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
2064
|
+
function getObservableOptions(deviceType, device, configuredObservable) {
|
|
2065
|
+
const specificOptions = getObservableDefinitions(deviceType)
|
|
2066
|
+
.filter((definition) => definition.id === configuredObservable || isObservableSupportedForDevice(deviceType, device, definition.id))
|
|
2067
|
+
.map((definition) => ({
|
|
2068
|
+
value: definition.id,
|
|
2069
|
+
label: formatObservableLabel(deviceType, definition.id, definition.label)
|
|
2070
|
+
}));
|
|
1942
2071
|
|
|
1943
2072
|
return [ALL_OBSERVABLE_OPTION].concat(specificOptions);
|
|
1944
2073
|
}
|
|
1945
2074
|
|
|
2075
|
+
function isObservableSupportedForDevice(deviceType, device, observable) {
|
|
2076
|
+
// Older Protect versions do not report sensor feature flags: keep every
|
|
2077
|
+
// observable available unless the sensor explicitly describes its features.
|
|
2078
|
+
const featureFlags = deviceType === "sensor" ? getValueAtPath(device, "featureFlags") : undefined;
|
|
2079
|
+
const reportsFeatures = featureFlags && typeof featureFlags === "object"
|
|
2080
|
+
&& Object.values(SENSOR_OBSERVABLE_FEATURE_FLAGS).some((flag) => Object.prototype.hasOwnProperty.call(featureFlags, flag));
|
|
2081
|
+
const flag = SENSOR_OBSERVABLE_FEATURE_FLAGS[observable];
|
|
2082
|
+
if (!reportsFeatures || !flag) {
|
|
2083
|
+
return true;
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
const capability = featureFlags[flag];
|
|
2087
|
+
return Boolean(capability && Number(capability.channelCount) > 0);
|
|
2088
|
+
}
|
|
2089
|
+
|
|
1946
2090
|
function resolveSelectedObservable(options, configuredObservable) {
|
|
1947
2091
|
const normalized = String(configuredObservable || "").trim();
|
|
1948
2092
|
if (normalized && options.some((option) => option.value === normalized)) {
|
|
@@ -1961,6 +2105,10 @@ function resolveObservableState(deviceType, device, observable, fallbackValue) {
|
|
|
1961
2105
|
const value = readAlarmState(deviceType, device);
|
|
1962
2106
|
return value === undefined ? fallbackValue : value;
|
|
1963
2107
|
}
|
|
2108
|
+
if (deviceType === "alarmHub" && observable === "deviceTamper") {
|
|
2109
|
+
const status = getValueAtPath(device, "alarmHub.deviceTamperStatus");
|
|
2110
|
+
return status === "tampered" || status === "restored" ? status === "tampered" : fallbackValue;
|
|
2111
|
+
}
|
|
1964
2112
|
if (deviceType === "sensor") {
|
|
1965
2113
|
return resolveSensorObservableState(device, observable, fallbackValue);
|
|
1966
2114
|
}
|
|
@@ -2225,6 +2373,15 @@ function resolveCameraObservableEventValue(event, observable, observableScopeId)
|
|
|
2225
2373
|
return { matched: false };
|
|
2226
2374
|
}
|
|
2227
2375
|
|
|
2376
|
+
if (observable === "digitalInput") {
|
|
2377
|
+
const inputState = String(firstDefinedValue(event, ["metadata.inputState.text", "metadata.inputState.value"]) || "").trim();
|
|
2378
|
+
return {
|
|
2379
|
+
matched: inputState === "circuitClosed" || inputState === "circuitOpen",
|
|
2380
|
+
eventTypeMatched: true,
|
|
2381
|
+
value: inputState === "circuitClosed"
|
|
2382
|
+
};
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2228
2385
|
if (observable === "licensePlate") {
|
|
2229
2386
|
const plates = extractLicensePlates(event);
|
|
2230
2387
|
return {
|
|
@@ -2347,6 +2504,18 @@ function resolveAlarmHubObservableEventValue(event, observable) {
|
|
|
2347
2504
|
return { matched: false };
|
|
2348
2505
|
}
|
|
2349
2506
|
|
|
2507
|
+
if (observable === "deviceTamper") {
|
|
2508
|
+
if (eventType !== "alarmHubDeviceTamper") {
|
|
2509
|
+
return { matched: false };
|
|
2510
|
+
}
|
|
2511
|
+
const status = String(firstDefinedValue(event, ["metadata.status.text", "metadata.status.value"]) || "").trim();
|
|
2512
|
+
return {
|
|
2513
|
+
matched: status === "tampered" || status === "restored",
|
|
2514
|
+
eventTypeMatched: true,
|
|
2515
|
+
value: status === "tampered"
|
|
2516
|
+
};
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2350
2519
|
const definition = ALARM_HUB_OBSERVABLE_DEFINITIONS.find((entry) => entry.id === observable);
|
|
2351
2520
|
if (!definition || !definition.eventTypes.includes(eventType)) {
|
|
2352
2521
|
return { matched: false };
|
|
@@ -222,6 +222,11 @@ const OBSERVABLE_METADATA = {
|
|
|
222
222
|
label: "Fingerprint Identified",
|
|
223
223
|
description: "Emits true when a fingerprint is scanned at the camera device.",
|
|
224
224
|
source: "official"
|
|
225
|
+
},
|
|
226
|
+
digitalInput: {
|
|
227
|
+
label: "Digital Input",
|
|
228
|
+
description: "True when an ONVIF camera digital input circuit closes and false when it opens.",
|
|
229
|
+
source: "official"
|
|
225
230
|
}
|
|
226
231
|
},
|
|
227
232
|
sensor: {
|
|
@@ -372,7 +377,8 @@ const OBSERVABLE_METADATA = {
|
|
|
372
377
|
source: "official"
|
|
373
378
|
}
|
|
374
379
|
},
|
|
375
|
-
|
|
380
|
+
// Keys are matched in lower case, like the device type.
|
|
381
|
+
alarmhub: {
|
|
376
382
|
armed: {
|
|
377
383
|
label: "Armed",
|
|
378
384
|
description: "Current Alarm Hub armed state: on becomes true and off becomes false. Updated by device state messages, not a dedicated arm/disarm event.",
|
|
@@ -408,6 +414,11 @@ const OBSERVABLE_METADATA = {
|
|
|
408
414
|
description: "True while an Alarm Hub input reports tampering.",
|
|
409
415
|
source: "official"
|
|
410
416
|
},
|
|
417
|
+
deviceTamper: {
|
|
418
|
+
label: "Hub Tamper",
|
|
419
|
+
description: "True when the Alarm Hub enclosure is tampered with and false when it is restored.",
|
|
420
|
+
source: "official"
|
|
421
|
+
},
|
|
411
422
|
relaySwitched: {
|
|
412
423
|
label: "Relay Switched",
|
|
413
424
|
description: "Emits true when an Alarm Hub relay output is switched.",
|
|
@@ -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.21",
|
|
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
|
},
|
|
@@ -842,27 +842,27 @@ function buildRegistrySuggestions(product, docs) {
|
|
|
842
842
|
});
|
|
843
843
|
}
|
|
844
844
|
|
|
845
|
-
async function
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
const
|
|
849
|
-
const startPath = `/${product}/${initialVersion}/gettingstarted`;
|
|
850
|
-
const start = await safeRequest({
|
|
845
|
+
async function resolveLatestDocsVersion(baseDocsUrl, product) {
|
|
846
|
+
// The portal has no "latest" path; the product root redirects to the
|
|
847
|
+
// current version's getting started page.
|
|
848
|
+
const response = await requestJson({
|
|
851
849
|
baseUrl: baseDocsUrl,
|
|
852
|
-
path:
|
|
850
|
+
path: `/${product}`
|
|
853
851
|
});
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
852
|
+
const location = String(response.headers.location || "");
|
|
853
|
+
const match = location.match(new RegExp(`/${product}/([^/]+)/`));
|
|
854
|
+
if (!match) {
|
|
855
|
+
throw new Error(`Unable to resolve the latest ${product} docs version from ${baseDocsUrl}/${product} (${response.statusCode}).`);
|
|
857
856
|
}
|
|
857
|
+
return match[1];
|
|
858
|
+
}
|
|
858
859
|
|
|
859
|
-
|
|
860
|
-
const
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
const version = versionAnswer === "latest" ? latestVersion : initialVersion;
|
|
860
|
+
async function fetchDeveloperPortalReport({ product, defaultVersion, registry, includePages = "api" }) {
|
|
861
|
+
const versionAnswer = await ask(`${product.toUpperCase()} docs version`, defaultVersion || "latest");
|
|
862
|
+
const baseDocsUrl = "https://developer.ui.com";
|
|
863
|
+
const version = versionAnswer === "latest" ? await resolveLatestDocsVersion(baseDocsUrl, product) : versionAnswer;
|
|
864
864
|
const docsPath = `/${product}/${version}/gettingstarted`;
|
|
865
|
-
const docsPage =
|
|
865
|
+
const docsPage = await safeRequest({
|
|
866
866
|
baseUrl: baseDocsUrl,
|
|
867
867
|
path: docsPath
|
|
868
868
|
});
|