unifi-protect: watch for websocket silent death

This commit is contained in:
Koushik Dutta
2022-06-27 12:31:36 -07:00
parent b64fa56222
commit 9f4144ffaa
4 changed files with 23 additions and 7 deletions

View File

@@ -1,12 +1,12 @@
{
"name": "@scrypted/unifi-protect",
"version": "0.0.117",
"version": "0.0.118",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@scrypted/unifi-protect",
"version": "0.0.117",
"version": "0.0.118",
"hasInstallScript": true,
"license": "Apache",
"dependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "@scrypted/unifi-protect",
"version": "0.0.117",
"version": "0.0.118",
"description": "Unifi Protect Plugin for Scrypted",
"author": "Scrypted",
"license": "Apache",
@@ -33,7 +33,6 @@
]
},
"devDependencies": {
"@types/lodash": "^4.14.158",
"@types/node": "^16.7.1",
"@types/ws": "^7.4.7"
},

View File

@@ -95,7 +95,7 @@ export class UnifiProtect extends ScryptedDeviceBase implements Settings, Device
return fetch(url, options);
}
listener = (event: Buffer) => {
listener(event: Buffer) {
const updatePacket = ProtectApiUpdates.decodeUpdatePacket(this.console, event);
if (!updatePacket)
return;
@@ -249,6 +249,7 @@ export class UnifiProtect extends ScryptedDeviceBase implements Settings, Device
}
this.api?.eventsWs?.removeAllListeners();
this.api?.eventsWs?.close();
if (!this.api) {
this.api = new ProtectApi(ip, username, password, {
debug() { },
@@ -268,7 +269,23 @@ export class UnifiProtect extends ScryptedDeviceBase implements Settings, Device
return;
}
this.api.eventsWs?.on('message', this.listener);
const onWsTimeout = () => {
this.console.log('Event Listener timeout. Restarting listener.');
this.api?.eventsWs?.removeAllListeners();
this.api?.eventsWs?.close();
this.discoverDevices(0);
};
let wsTimeout: NodeJS.Timeout;
const resetWsTimeout = () => {
clearTimeout(wsTimeout);
wsTimeout = setTimeout(onWsTimeout, 5 * 60 * 1000);
};
resetWsTimeout();
this.api.eventsWs?.on('message', (data) => {
resetWsTimeout();
this.listener(data as Buffer);
});
this.api.eventsWs?.on('close', async () => {
this.console.error('Event Listener closed. Reconnecting in 10 seconds.');
await sleep(10000);