-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
319 lines (274 loc) · 12 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// eslint-disable-next-line node/no-unpublished-require,strict
'use strict';
const Homey = require('homey');
const ProtectAPI = require('./library/protectapi');
const UfvConstants = require('./library/constants');
const { Log } = require('homey-log');
// 2700000 miliseconds is 45 minutes
const RefreshCookieTime = 2700000;
class UniFiProtect extends Homey.App {
/**
* onInit is called when the app is initialized.
*/
async onInit() {
this.homeyLog = new Log({ homey: this.homey });
this.debuggedIn = false;
this.nvrIp = null;
this.nvrPort = null;
this.nvrUsername = null;
this.nvrPassword = null;
this.useCameraSnapshot = false;
this._refreshAuthTokensnterval = 60 * 60 * 1000; // 1 hour
// Single API instance for all devices
this.api = new ProtectAPI();
this.api.setHomeyObject(this.homey)
// Register snapshot image token
this._registerSnapshotToken();
this._snapshotTrigger = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SNAPSHOT_CREATED);
this._connectionStatusTrigger = this.homey.flow.getTriggerCard(UfvConstants.EVENT_CONNECTION_CHANGED);
this._doorbellRingingTrigger = this.homey.flow.getTriggerCard(UfvConstants.EVENT_DOORBELL_RINGING);
this._smartDetectionTrigger = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SMART_DETECTION);
this._smartDetectionTriggerPerson = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SMART_DETECTION_PERSON);
this._smartDetectionTriggerVehicle = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SMART_DETECTION_VEHICLE);
this._smartDetectionTriggerAnimal = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SMART_DETECTION_ANIMAL);
this._smartDetectionTriggerPackage = this.homey.flow.getTriggerCard(UfvConstants.EVENT_SMART_DETECTION_PACKAGE);
const _actionTakeSnapshot = this.homey.flow.getActionCard(UfvConstants.ACTION_TAKE_SNAPSHOT);
_actionTakeSnapshot.registerRunListener(async (args, state) => {
if (typeof args.device.getData === 'function' && typeof args.device.getData().id !== 'undefined') {
// Get device from camera id
const device = args.device.driver.getUnifiDeviceById(args.device.getData().id);
if (device) {
device._createSnapshotImage(true);
}
}
return Promise.resolve(true);
});
const _setRecordingMode = this.homey.flow.getActionCard(UfvConstants.ACTION_SET_RECORDING_MODE);
_setRecordingMode.registerRunListener(async (args, state) => {
if (typeof args.device.getData().id !== 'undefined') {
this.homey.app.api.setRecordingMode(args.device.getData(), args.recording_mode)
.then(this.homey.app.debug.bind(this, '[recordingmode.set]'))
.catch(this.error.bind(this, '[recordingmode.set]'));
}
return Promise.resolve(true);
});
// V2 Actions
const _actionTakeSnapshotV2 = this.homey.flow.getActionCard(UfvConstants.ACTION_TAKE_SNAPSHOT_V2);
_actionTakeSnapshotV2.registerRunListener(async (args, state) => {
if (typeof args.device.getData === 'function' && typeof args.device.getData().id !== 'undefined') {
// Get device from camera id
const device = args.device.driver.getUnifiDeviceById(args.device.getData().id);
if (device) {
device._createSnapshotImage(true);
}
}
return Promise.resolve(true);
});
const _setRecordingModeV2 = this.homey.flow.getActionCard(UfvConstants.ACTION_SET_RECORDING_MODE_V2);
_setRecordingModeV2.registerRunListener(async (args, state) => {
if (typeof args.device.getData().id !== 'undefined') {
this.homey.app.api.setRecordingMode(args.device.getData(), args.recording_mode)
.then(this.homey.app.debug.bind(this, '[recordingmode.set]'))
.catch(this.error.bind(this, '[recordingmode.set]'));
}
return Promise.resolve(true);
});
const _setChimeVolume = this.homey.flow.getActionCard(UfvConstants.ACTION_SET_CHIME_ONOFF);
_setChimeVolume.registerRunListener(async (args, state) => {
if (typeof args.device.getData().id !== 'undefined') {
let volume = 0;
if (args.enabled)
{
volume = args.volume;
}
this.homey.app.api.setChimeVolume(args.device.getData(), volume)
.then(this.homey.app.debug.bind(this, '[chime.volume.set]'))
.catch(this.error.bind(this, '[chime.volume.set]'));
}
return Promise.resolve(true);
});
const _setNightVisionMode = this.homey.flow.getActionCard(UfvConstants.ACTION_SET_NIGHT_VISION_MODE);
_setNightVisionMode.registerRunListener(async (args, state) => {
if (typeof args.device.getData().id !== 'undefined') {
this.homey.app.api.setNightVisionMode(args.device.getData(), args.nightvision_mode)
.then(this.homey.app.debug.bind(this, '[nightvision_mode.set]'))
.catch(this.error.bind(this, '[nightvision_mode.set]'));
}
return Promise.resolve(true);
});
const _setLCDMessage = this.homey.flow.getActionCard(UfvConstants.ACTION_SET_LCD_MESSAGE);
_setLCDMessage.registerRunListener(async (args, state) => {
if (typeof args.device.getData().id !== 'undefined') {
this.homey.app.api.setLCDMessage(args.device.getData(), args.message.substring(0, 29))
.then(this.homey.app.debug.bind(this, '[lcd_message.set]'))
.catch(this.error.bind(this, '[lcd_message.set]'));
}
return Promise.resolve(true);
});
// Subscribe to credentials updates
this.homey.settings.on('set', key => {
if (key === 'ufp:credentials' || key === 'ufp:nvrip' || key === 'ufp:nvrport') {
this._appLogin();
}
if (key === 'ufp:settings') {
const settings = this.homey.settings.get('ufp:settings');
this.useCameraSnapshot = settings.useCameraSnapshot;
}
});
// set settings
const settings = this.homey.settings.get('ufp:settings');
if (settings) {
this.useCameraSnapshot = settings.useCameraSnapshot;
}
this._appLogin();
// refresh auth tokens every hour
await this.refreshAuthTokens();
this.debug('UniFiProtect has been initialized');
}
async refreshAuthTokens() {
const refreshAuthTokens = setInterval(() => {
try {
this.debug('Refreshing auth tokens');
this._appLogin();
} catch (error) {
this.homey.error(`${JSON.stringify(error)}`);
}
}, this._refreshAuthTokensnterval);
}
async triggerSnapshotTrigger(tokens) {
await this._snapshotTrigger
.trigger(tokens)
.catch(this.error);
}
async triggerConnectionStatusTrigger(tokens) {
await this._connectionStatusTrigger
.trigger(tokens)
.then(this.debug)
.catch(this.error);
}
async triggerDoorbellRingingTrigger(tokens) {
await this._doorbellRingingTrigger
.trigger(tokens)
.then(this.debug)
.catch(this.error);
}
async triggerSmartDetectionTrigger(tokens) {
await this._smartDetectionTrigger
.trigger(tokens)
.then(this.debug)
.catch(this.error);
}
_registerSnapshotToken() {
// Register snapshot image token
this.homey.flow.createToken('ufv_snapshot', {
type: 'image',
title: 'Snapshot',
});
}
_appLogin() {
this.debug('Logging in...');
// Validate NVR IP address
const nvrip = this.homey.settings.get('ufp:nvrip');
if (!nvrip) {
this.debug('NVR IP address not set.');
return;
}
// Setting NVR Port when set
const nvrport = this.homey.settings.get('ufp:nvrport');
// Validate NVR credentials
const credentials = this.homey.settings.get('ufp:credentials');
if (!credentials) {
this.debug('Credentials not set.');
return;
}
// Log in to NVR
this.api.login(nvrip, nvrport, credentials.username, credentials.password)
.then(() => {
this.api.getBootstrapInfo()
.then(() => {
this.debug('Bootstrap loaded.');
this.debuggedIn = true;
this.nvrIp = nvrip;
this.nvrPort = nvrport;
this.nvrUsername = credentials.username;
this.nvrPassword = credentials.password;
// _refreshCookie after 45 minutes
const timeOutFunction = function () {
this._refreshCookie();
}.bind(this);
this.homey.setTimeout(timeOutFunction, RefreshCookieTime);
this.debug('Logged in.');
})
.catch(error => this.error(error));
})
.catch(error => this.error(error));
}
cleanDeviceStorage() {
const driverDoorbell = this.homey.drivers.getDriver('protectdoorbell');
const driverCamera = this.homey.drivers.getDriver('protectcamera');
driverDoorbell.getDevices().forEach(device => {
device.cleanSmartDetectionEvents();
});
driverCamera.getDevices().forEach(device => {
device.cleanSmartDetectionEvents();
});
}
_refreshCookie() {
//if (this.debuggedIn) {
this.api._lastUpdateId = null;
// Validate NVR IP address
const nvrip = this.homey.settings.get('ufp:nvrip');
if (!nvrip) {
this.debug('NVR IP address not set.');
return;
}
// Setting NVR Port when set
const nvrport = this.homey.settings.get('ufp:nvrport');
// Validate NVR credentials
const credentials = this.homey.settings.get('ufp:credentials');
if (!credentials) {
this.debug('Credentials not set.');
return;
}
this.api.login(nvrip, nvrport, credentials.username, credentials.password)
.then(() => {
this.debug('Logged in again to refresh cookie.');
this.api.getBootstrapInfo()
.then(() => {
this.debug('Bootstrap loaded.');
this.debuggedIn = true;
})
.catch(error => this.error(error));
})
.catch(error => this.error(error));
//}
// clean Device Storage
this.cleanDeviceStorage();
// _refreshCookie after 1 hour
const timeOutFunction = function () {
this._refreshCookie();
}.bind(this);
this.homey.setTimeout(timeOutFunction, RefreshCookieTime);
}
/**
* Convert a Homey time to a local time
* @param {Date} homeyTime
* @returns {Date}
*/
toLocalTime(homeyTime) {
const tz = this.homey.clock.getTimezone();
const localTime = new Date(homeyTime.toLocaleString('en-US', { timeZone: tz }));
return localTime;
}
getUnixTimestamp () {
return Math.floor(Date.now());
}
debug() {
if (Homey.env.DEBUG === 'true') {
const args = Array.prototype.slice.call(arguments);
args.unshift('[debug]');
this.homey.log(args.join(' '));
}
}
}
module.exports = UniFiProtect;