-
Notifications
You must be signed in to change notification settings - Fork 14
/
ownRingCamera.js
867 lines (867 loc) · 43.1 KB
/
ownRingCamera.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OwnRingCamera = void 0;
const rxjs_1 = require("rxjs");
const fs = __importStar(require("fs"));
const util = __importStar(require("util"));
const sharp_1 = __importDefault(require("sharp"));
const strftime_1 = __importDefault(require("strftime"));
const node_schedule_1 = __importDefault(require("node-schedule"));
const constants_1 = require("./constants");
const lastAction_1 = require("./lastAction");
const file_service_1 = require("./services/file-service");
const ownRingDevice_1 = require("./ownRingDevice");
var EventState;
(function (EventState) {
EventState[EventState["Idle"] = 0] = "Idle";
EventState[EventState["ReactingOnMotion"] = 1] = "ReactingOnMotion";
EventState[EventState["ReactingOnDing"] = 2] = "ReactingOnDing";
EventState[EventState["ReactingOnDoorbell"] = 3] = "ReactingOnDoorbell";
})(EventState || (EventState = {}));
class OwnRingCamera extends ownRingDevice_1.OwnRingDevice {
get lastLiveStreamDir() {
return this._lastLiveStreamDir;
}
get lastSnapShotDir() {
return this._lastSnapShotDir;
}
get lastHDSnapShotDir() {
return this._lastHDSnapShotDir;
}
get ringDevice() {
return this._ringDevice;
}
async startLivestream(duration) {
this.silly(`${this.shortId}.startLivestream()`);
duration !== null && duration !== void 0 ? duration : (duration = this._durationLiveStream);
const { visURL, visPath, fullPath } = await this.prepareLivestreamTargetFile().catch(reason => {
this.catcher("Couldn't prepare Livestream Target File.", reason);
return { visURL: "", visPath: "", fullPath: "" };
});
if (!visURL || !visPath || !fullPath) {
await this.updateLivestreamRequest(false);
return;
}
if (this._ringDevice.isOffline) {
this.info(` is offline --> won't take LiveStream`);
await this.updateLivestreamRequest(false);
return;
}
const tempPath = (await file_service_1.FileService.getTempDir(this._adapter)) + `/temp_${this.shortId}_livestream.mp4`;
const liveCall = await this._ringDevice.streamVideo({
video: this.videoFilter(this._adapter.config.overlay_Livestream),
output: ["-t", duration.toString(), tempPath],
}).catch(reason => {
this.catcher("Couldn't create Livestream.", reason);
return null;
});
if (!liveCall) {
this.warn(`Couldn't create Livestream`);
await this.updateLivestreamRequest(false);
return;
}
const liveCallSucceeded = await (0, rxjs_1.firstValueFrom)(liveCall.onCallEnded).then(_result => {
return true;
}).catch(reason => {
this.catcher("Couldn't create HD Snapshot.", reason);
return null;
});
if (!fs.existsSync(tempPath) || !liveCallSucceeded) {
this.warn(`Couldn't create livestream`);
await this.updateLivestreamRequest(false);
return;
}
const video = fs.readFileSync(tempPath);
// clean up
fs.unlink(tempPath, (err) => {
if (err) {
this._adapter.logCatch(`Couldn't delete temp file`, err);
}
});
if (this._lastLiveStreamDir !== "" && this._adapter.config.del_old_livestream) {
file_service_1.FileService.deleteFileIfExistSync(this._lastLiveStreamDir, this._adapter);
}
if (visPath) {
this.silly(`Locally storing Filestream (Length: ${video.length})`);
await file_service_1.FileService.writeFile(visPath, video, this._adapter);
this._lastLiveStreamUrl = visURL;
}
this.silly(`Writing Filestream (Length: ${video.length}) to "${fullPath}"`);
await file_service_1.FileService.writeFile(fullPath, video, this._adapter);
this._lastLiveStreamDir = fullPath;
this._lastLiveStreamTimestamp = Date.now();
await this.updateLiveStreamObject();
this.debug(`Done creating livestream to ${fullPath}`);
}
async takeHDSnapshot() {
var _a;
this.silly(`${this.shortId}.takeHDSnapshot()`);
// const duration = 2.0;
const { visURL, visPath } = await file_service_1.FileService.getVisUrl(this._adapter, this.fullId, "HDSnapshot.jpg").catch(reason => {
this.catcher("Couldn't get Vis URL.", reason);
return { visURL: "", visPath: "" };
});
if (!visURL || !visPath) {
this.warn("Vis not available! Please install e.g. flot or other Vis related adapter");
await this.updateHDSnapshotRequest(false);
return;
}
const { fullPath, dirname } = file_service_1.FileService.getPath(this._adapter.config.path_snapshot, `HD${this._adapter.config.filename_snapshot}`, ++this._snapshotCount, this.shortId, this.fullId, this.kind);
if (!(await file_service_1.FileService.prepareFolder(dirname))) {
this.warn(`prepare folder problem --> won't take HD Snapshot`);
await this.updateHDSnapshotRequest(false);
return;
}
file_service_1.FileService.deleteFileIfExistSync(fullPath, this._adapter);
if (this._ringDevice.isOffline) {
this.info(`is offline --> won't take HD Snapshot`);
await this.updateHDSnapshotRequest(false);
return;
}
const { night_contrast, night_sharpen } = this.getActiveNightImageOptions();
const tempPath = (await file_service_1.FileService.getTempDir(this._adapter)) + `/temp_${this.shortId}_livestream.jpg`;
const liveCall = await this._ringDevice.streamVideo({
video: this.videoFilter(this._adapter.config.overlay_HDsnapshot, night_contrast ? this._adapter.config.contrast_HDsnapshot : 0),
// output: ["-t", duration.toString(), "-f", "mjpeg", "-q:v", 3, "-frames:v", 1, tempPath]
output: ["-f", "mjpeg", "-q:v", 3, "-frames:v", 1, tempPath]
}).catch(reason => {
this.catcher("Couldn't create HD Snapshot.", reason);
return null;
});
if (!liveCall) {
this.warn(`Couldn't create HD Snapshot`);
await this.updateHDSnapshotRequest(false);
return;
}
const liveCallSucceeded = await (0, rxjs_1.firstValueFrom)(liveCall.onCallEnded).then(_result => {
return true;
}).catch(reason => {
this.catcher("Couldn't create HD Snapshot.", reason);
return null;
});
if (!fs.existsSync(tempPath) || !liveCallSucceeded) {
this.warn(`Couldn't create HD Snapshot`);
await this.updateHDSnapshotRequest(false);
return;
}
else {
this.silly(`HD Snapshot from livestream created`);
}
let jpg = fs.readFileSync(tempPath);
if (night_sharpen && this._adapter.config.sharpen_HDsnapshot && this._adapter.config.sharpen_HDsnapshot > 0) {
const sharpen = this._adapter.config.sharpen_HDsnapshot == 1 ? undefined : { sigma: this._adapter.config.sharpen_HDsnapshot - 1 };
jpg = (_a = await (0, sharp_1.default)(jpg)
.sharpen(sharpen)
.toBuffer()
.catch(reason => {
this.catcher("Couldn't sharpen HD Snapshot.", reason);
return null;
})) !== null && _a !== void 0 ? _a : jpg;
}
// clean up
fs.unlink(tempPath, (err) => {
if (err) {
this._adapter.logCatch(`Couldn't delete temp file ${tempPath}`, err);
}
});
if (this._lastHDSnapShotDir !== "" && this._adapter.config.del_old_HDsnapshot) {
file_service_1.FileService.deleteFileIfExistSync(this._lastHDSnapShotDir, this._adapter);
}
if (visPath) {
this.silly(`Locally storing HD Snapshot (Length: ${jpg.length})`);
await file_service_1.FileService.writeFile(visPath, jpg, this._adapter);
this._lastHDSnapShotUrl = visURL;
}
this.silly(`Writing HD Snapshot to ${fullPath} (Length: ${jpg.length})`);
await file_service_1.FileService.writeFile(fullPath, jpg, this._adapter);
this._lastHDSnapShotDir = fullPath;
this._lastHDSnapshotTimestamp = Date.now();
await this.updateHDSnapshotObject();
this.debug(`Done creating HDSnapshot to ${visPath}`);
}
async takeSnapshot(uuid, eventBased = false) {
this.silly(`${this.shortId}.takeSnapshot()`);
const { visURL, visPath } = await file_service_1.FileService.getVisUrl(this._adapter, this.fullId, "Snapshot.jpg");
if (!visURL || !visPath) {
this.warn("Vis not available");
}
const { fullPath, dirname } = file_service_1.FileService.getPath(this._adapter.config.path_snapshot, this._adapter.config.filename_snapshot, ++this._HDsnapshotCount, this.shortId, this.fullId, this.kind);
if (!(await file_service_1.FileService.prepareFolder(dirname))) {
this.warn(`prepare folder problem --> won't take Snapshot`);
await this.updateSnapshotRequest(false);
return;
}
file_service_1.FileService.deleteFileIfExistSync(fullPath, this._adapter);
if (this._ringDevice.isOffline) {
this.info(`is offline --> won't take Snapshot`);
await this.updateSnapshotRequest(false);
return;
}
/*
const image = await this._ringDevice.getNextSnapshot({uuid: uuid}).catch((reason) => {
if (eventBased) {
this.warn("Taking Snapshot on Event failed. Will try again after livestream finished.");
} else {
this.catcher("Couldn't get Snapshot from api.", reason);
}
})
*/
const image = await this._ringDevice.getNextSnapshot({ force: true, uuid: uuid })
.then((result) => result)
.catch((err) => {
if (eventBased) {
this.warn("Taking Snapshot on Event failed. Will try again after livestream finished.");
}
else {
this.catcher("Couldn't get Snapshot from api.", err);
}
return err;
});
if (!image.byteLength) {
if (!eventBased) {
this.warn("Could not create snapshot from image");
}
await this.updateSnapshotRequest(false);
return;
}
else {
this.silly(`Response timestamp: ${image.responseTimestamp},
Byte Length: ${image.byteLength},
Byte Offset: ${image.byteOffset},
Length: ${image.length},
Time in ms: ${image.timeMillis}`);
}
let image_txt = image;
if (this._adapter.config.overlay_snapshot) {
image_txt = await this.addText(image)
.catch(reason => {
this.catcher("Couldn't add text to Snapshot.", reason);
return reason;
});
}
if (this._lastSnapShotDir !== "" && this._adapter.config.del_old_snapshot) {
file_service_1.FileService.deleteFileIfExistSync(this._lastSnapShotDir, this._adapter);
}
this._lastSnapShotUrl = visURL;
this._lastSnapShotDir = fullPath;
this._lastSnapshotTimestamp = image.timeMillis;
if (visPath) {
this.silly(`Locally storing Snapshot (Length: ${image.length})`);
await file_service_1.FileService.writeFile(visPath, image_txt, this._adapter);
}
this.silly(`Writing Snapshot (Length: ${image.length}) to "${fullPath}"`);
await file_service_1.FileService.writeFile(fullPath, image_txt, this._adapter);
await this.updateSnapshotObject();
this.debug(`Done creating snapshot to ${fullPath}`);
}
async prepareLivestreamTargetFile() {
const { visURL, visPath } = await file_service_1.FileService.getVisUrl(this._adapter, this.fullId, "Livestream.mp4").catch(reason => {
this.catcher("Couldn't get Vis URL.", reason);
return { visURL: "", visPath: "" };
});
return new Promise(async (resolve, reject) => {
if (!visURL || !visPath) {
reject("Vis not available");
}
const { fullPath, dirname } = file_service_1.FileService.getPath(this._adapter.config.path_livestream, this._adapter.config.filename_livestream, ++this._liveStreamCount, this.shortId, this.fullId, this.kind);
const folderPrepared = await file_service_1.FileService.prepareFolder(dirname).catch(reason => {
this.catcher("Couldn't prepare folder.", reason);
return false;
});
if (!folderPrepared) {
this.warn(`Failed to prepare Livestream folder ("${fullPath}")`);
reject("Failed to prepare Livestream folder");
return;
}
file_service_1.FileService.deleteFileIfExistSync(fullPath, this._adapter);
resolve({ visURL: visURL, visPath: visPath, fullPath: fullPath });
});
}
getActiveNightImageOptions() {
let night_contrast = false;
let night_sharpen = false;
if (this._adapter.Sunrise > 0 && this._adapter.Sunset > 0) {
const today = Date.now();
this.silly(`Now: ${today}, sunrise: ${this._adapter.Sunrise}, sunset: ${this._adapter.Sunset}`);
const isNight = today < this._adapter.Sunrise || today > this._adapter.Sunset;
this.debug(`is Night: ${isNight}`);
night_contrast = this._adapter.config.night_contrast_HDsnapshot && isNight || !this._adapter.config.night_contrast_HDsnapshot;
night_sharpen = this._adapter.config.night_sharpen_HDsnapshot && isNight || !this._adapter.config.night_sharpen_HDsnapshot;
}
return { night_contrast, night_sharpen };
}
async updateHistory() {
this.silly(`Update History`);
this._ringDevice.getEvents({ limit: 50 })
.then(async (r) => {
this.silly(`Received Event History`);
const lastAction = r.events.find((event) => {
const kind = event.kind;
switch (kind) {
case "motion":
case "ding":
case "alarm":
case "on_demand":
return true;
}
return false;
});
if (lastAction === undefined) {
return;
}
const url = await this._ringDevice.getRecordingUrl(lastAction.ding_id_str);
this.lastAction = new lastAction_1.LastAction(lastAction, url);
this.updateHistoryObject(this.lastAction);
});
}
getDay() {
const en = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const de = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"];
const ru = ["Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"];
const pt = ["segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado", "domingo"];
const nl = ["maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag", "zondag"];
const fr = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
const it = ["lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato", "domenica"];
const es = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"];
const pl = ["Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"];
const uk = ["понеділок", "вівторок", "середа", "четвер", "п'ятниця", "субота", "неділя"];
const zh = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
const dow = (new Date().getDay() + 6) % 7;
switch (this._adapter.language) {
case "en":
return en[dow];
case "de":
return de[dow];
case "ru":
return ru[dow];
case "pt":
return pt[dow];
case "nl":
return nl[dow];
case "fr":
return fr[dow];
case "it":
return it[dow];
case "es":
return es[dow];
case "uk":
return uk[dow];
case "pl":
return pl[dow];
case "uk":
return uk[dow];
case "zh-cn":
return zh[dow];
}
return en[dow];
}
set ringDevice(device) {
this._ringDevice = device;
this.subscribeToEvents();
}
constructor(ringDevice, location, adapter, apiClient) {
super(location, adapter, apiClient, OwnRingCamera.evaluateKind(ringDevice.deviceType, adapter, ringDevice), `${ringDevice.id}`, ringDevice.data.description);
this._durationLiveStream = this._adapter.config.recordtime_livestream;
this._lastLightCommand = 0;
this._lastLiveStreamUrl = "";
this._lastLiveStreamDir = "";
this._lastLiveStreamTimestamp = 0;
this._lastSnapShotUrl = "";
this._lastSnapShotDir = "";
this._lastSnapshotTimestamp = 0;
this._snapshotCount = 0;
this._lastHDSnapShotUrl = "";
this._lastHDSnapShotDir = "";
this._lastHDSnapshotTimestamp = 0;
this._HDsnapshotCount = 0;
this._liveStreamCount = 0;
this._state = EventState.Idle;
this._doorbellEventActive = false;
this._ringDevice = ringDevice;
this.debug(`Create device`);
this.infoChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_INFO}`;
this.historyChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_HISTORY}`;
this.lightChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_LIGHT}`;
this.snapshotChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_SNAPSHOT}`;
this.HDsnapshotChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_HDSNAPSHOT}`;
this.liveStreamChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_LIVESTREAM}`;
this.eventsChannelId = `${this.fullId}.${constants_1.CHANNEL_NAME_EVENTS}`;
this.recreateDeviceObjectTree();
this.updateDeviceInfoObject(ringDevice.data);
this.updateHealth();
// noinspection JSIgnoredPromiseFromCall
this.updateHistory();
this.updateSnapshotObject();
this.updateHDSnapshotObject();
this.updateLiveStreamObject();
this.ringDevice = ringDevice; // subscribes to the events
this.autoSched();
}
async processUserInput(channelID, stateID, state) {
switch (channelID) {
case "":
if (stateID !== constants_1.STATE_ID_DEBUG_REQUEST) {
return;
}
const targetVal = state.val;
if (targetVal) {
this._adapter.log.info(`Device Debug Data for ${this.shortId}: ${util.inspect(this._ringDevice, false, 1)}`);
this._adapter.upsertState(`${this.fullId}.${constants_1.STATE_ID_DEBUG_REQUEST}`, constants_1.COMMON_DEBUG_REQUEST, false);
}
return;
case "Light":
if (!this._ringDevice.hasLight) {
return;
}
if (stateID === constants_1.STATE_ID_LIGHT_SWITCH) {
const targetVal = state.val;
this._adapter.log.debug(`Set light for ${this.shortId} to value ${targetVal}`);
this._lastLightCommand = Date.now();
this._ringDevice.setLight(targetVal).then((success) => {
if (success) {
this._adapter.upsertState(`${this.lightChannelId}.light_state`, constants_1.COMMON_LIGHT_STATE, targetVal);
this._adapter.upsertState(`${this.lightChannelId}.light_switch`, constants_1.COMMON_LIGHT_SWITCH, targetVal, true, true);
setTimeout(() => this.updateHealth.bind(this), 65000);
}
});
}
else {
this._adapter.log.error(`Unknown State/Switch with channel "${channelID}" and state "${stateID}"`);
}
break;
case "Snapshot":
if (stateID === constants_1.STATE_ID_SNAPSHOT_REQUEST) {
const targetVal = state.val;
this._adapter.log.debug(`Get Snapshot request for ${this.shortId} to value ${targetVal}`);
if (targetVal) {
await this.takeSnapshot().catch(reason => {
this.updateSnapshotRequest();
this.catcher("Couldn't retrieve Snapshot.", reason);
});
}
}
else {
this._adapter.log.error(`Unknown State/Switch with channel "${channelID}" and state "${stateID}"`);
}
break;
case "HD Snapshot":
if (stateID === constants_1.STATE_ID_HDSNAPSHOT_REQUEST) {
const targetVal = state.val;
this._adapter.log.debug(`Get HDSnapshot request for ${this.shortId} to value ${targetVal}`);
if (targetVal) {
await this.takeHDSnapshot().catch((reason) => {
this.updateHDSnapshotRequest();
this.catcher("Couldn't retrieve HDSnapshot.", reason);
});
}
}
else {
this._adapter.log.error(`Unknown State/Switch with channel "${channelID}" and state "${stateID}"`);
}
break;
case "Livestream":
if (stateID === constants_1.STATE_ID_LIVESTREAM_REQUEST) {
const targetVal = state.val;
this._adapter.log.debug(`Get Livestream request for ${this.shortId} to value ${targetVal}`);
if (targetVal) {
await this.startLivestream().catch(reason => {
this.updateLivestreamRequest();
this.catcher("Couldn't retrieve Livestream.", reason);
});
}
}
else if (stateID === constants_1.STATE_ID_LIVESTREAM_DURATION) {
const targetVal = isNaN(state.val) ? 20 : state.val;
this._adapter.log.debug(`Get Livestream duration for ${this.shortId} to value ${targetVal}`);
this.setDurationLivestream(targetVal);
}
else {
this._adapter.log.error(`Unknown State/Switch with channel "${channelID}" and state "${stateID}"`);
}
break;
default:
this._adapter.log.error(`Unknown State/Switch with channel "${channelID}" and state "${stateID}"`);
}
}
updateByDevice(ringDevice) {
this.ringDevice = ringDevice;
this._state = EventState.Idle;
this.update(ringDevice.data);
}
update(data) {
this.debug(`Received Update`);
this.updateDeviceInfoObject(data);
this.updateHealth();
// noinspection JSIgnoredPromiseFromCall
this.updateHistory();
this.updateSnapshotObject();
this.updateHDSnapshotObject();
}
setDurationLivestream(val) {
this.silly(`${this.shortId}.durationLivestream()`);
this._durationLiveStream = val;
this._adapter.upsertState(`${this.liveStreamChannelId}.${constants_1.STATE_ID_LIVESTREAM_DURATION}`, constants_1.COMMON_LIVESTREAM_DURATION, this._durationLiveStream, true);
this.debug(`Livestream duration set to: ${val}`);
}
getDateFormat() {
let sPattern = "/";
if (!this._adapter.dateFormat.includes(sPattern)) {
sPattern = "-";
if (!this._adapter.dateFormat.includes(sPattern)) {
sPattern = ".";
if (!this._adapter.dateFormat.includes(sPattern))
return "%y/%m/%d";
}
}
let rDate = "";
for (const val of this._adapter.dateFormat.split(sPattern)) {
switch (val) {
case "YYYY":
rDate += "%y";
break;
case "YY":
rDate += "%y";
break;
case "Y":
rDate += "%Y";
break;
case "MMMM":
rDate += "%B";
break;
case "MMM":
rDate += "%b";
break;
case "MM":
rDate += "%m";
break;
case "M":
rDate += "%-m";
break;
case "DD":
rDate += "%d";
break;
case "D":
rDate += "%-d";
break;
}
rDate = rDate + sPattern;
}
rDate = rDate.slice(0, rDate.length - 1);
return rDate;
}
videoFilter(overlay, startTime = 0) {
const start = `00:00:0${startTime.toString()}`;
const filter = `drawtext='
fontsize=30:
fontcolor=white:
x=(main_w-text_w-20):
y=20:shadowcolor=black:
shadowx=2:
shadowy=2:
text=${this._ringDevice.data.description}',
drawtext='
fontsize=30:
fontcolor=white:
x=20:
y=(main_h-text_h-20):
shadowcolor=black:
shadowx=2:
shadowy=2:
text=%{localtime\\:${this.getDay()}, ${this.getDateFormat()} %T}'`;
return (overlay && startTime > 0 ? ["-ss", start, "-vf", filter] :
(overlay ? ["-vf", filter] :
(startTime > 0 ? ["-ss", start] : [])));
}
async addText(jpg) {
const width = 640;
const height = 360;
const font_size = 15;
const border_dist = 10;
const text1 = this._ringDevice.data.description;
const text2 = (0, strftime_1.default)(`${this.getDay()}, ${this.getDateFormat()} %T`);
const svgText = `
<svg width="${width}" height="${height}">
<style>
.title { fill: white; font-size: ${font_size}px; filter: drop-shadow(2px 2px 1px rgb(0 0 0 / 0.9))}
</style>
<text x="${width - border_dist}" y="${border_dist + font_size}" text-anchor="end" class="title">${text1}</text>
<text x="10" y="${height - border_dist}" text-anchor="start" class="title">${text2}</text>
</svg>`;
const svgBuffer = Buffer.from(svgText);
return (0, sharp_1.default)(jpg)
.composite([{ input: svgBuffer, left: 0, top: 0 }])
.toBuffer();
}
updateHealth() {
this.silly(`Update Health`);
this._ringDevice.getHealth().then(this.updateHealthObject.bind(this));
}
autoSched() {
const media = [
{
name: "Snaspshot", val: this._adapter.config.save_snapshot, fct: () => {
this.takeSnapshot();
}, start: 0
},
{
name: "HD Snapshot", val: this._adapter.config.save_HDsnapshot, fct: () => {
this.takeHDSnapshot();
}, start: 2
},
{
name: "Livestream", val: this._adapter.config.save_livestream, fct: () => {
this.startLivestream();
}, start: 4
}
];
for (const m of media) {
if (m.val > 0) {
let schedMinute = "*";
let schedHour = "*";
if (m.val === 3600) {
schedMinute = "1";
schedHour = "12";
}
else if (m.val === 60) {
schedMinute = "3";
}
else if (m.val < 60) {
schedMinute = `${m.start}-59/${m.val.toString()}`;
}
node_schedule_1.default.scheduleJob(`Auto save ${m.name}_${this._adapter.name}_${this._adapter.instance}`, `${m.start * 10} ${schedMinute} ${schedHour} * * *`, () => {
this.info(`Cronjob Auto save ${m.name} starts`);
m.fct();
});
}
}
}
async recreateDeviceObjectTree() {
this.silly(`Recreate DeviceObjectTree`);
this._adapter.createDevice(this.fullId, {
name: `Device ${this.shortId} ("${this._ringDevice.data.description}")`,
});
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_INFO, { name: `Info ${this.shortId}` });
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_SNAPSHOT, { name: `Snapshot ${this.shortId}` });
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_HDSNAPSHOT, { name: `HD Snapshot ${this.shortId}` });
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_LIVESTREAM, { name: `Livestream ${this.shortId}` });
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_HISTORY);
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_EVENTS);
if (this._ringDevice.hasLight) {
this.debug(`Device with Light Capabilities detected`);
this._adapter.createChannel(this.fullId, constants_1.CHANNEL_NAME_LIGHT, { name: `Light ${this.shortId}` });
this._adapter.upsertState(`${this.lightChannelId}.${constants_1.STATE_ID_LIGHT_SWITCH}`, constants_1.COMMON_LIGHT_SWITCH, false, true, true);
}
this._lastSnapShotDir = await this._adapter.tryGetStringState(`${this.snapshotChannelId}.file`);
this._lastHDSnapShotDir = await this._adapter.tryGetStringState(`${this.HDsnapshotChannelId}.file`);
this._lastLiveStreamDir = await this._adapter.tryGetStringState(`${this.liveStreamChannelId}.file`);
if (this._adapter.config.auto_snapshot === undefined)
this._adapter.config.auto_snapshot = false;
if (this._adapter.config.auto_HDsnapshot === undefined)
this._adapter.config.auto_HDsnapshot = false;
if (this._adapter.config.auto_livestream === undefined)
this._adapter.config.auto_livestream = false;
this._adapter.upsertState(`${this.fullId}.${constants_1.STATE_ID_DEBUG_REQUEST}`, constants_1.COMMON_DEBUG_REQUEST, false, true, true);
this._adapter.upsertState(`${this.snapshotChannelId}.auto`, constants_1.COMMON_SNAPSHOT_AUTO, this._adapter.config.auto_snapshot, true, true);
this._adapter.upsertState(`${this.HDsnapshotChannelId}.auto`, constants_1.COMMON_HDSNAPSHOT_AUTO, this._adapter.config.auto_HDsnapshot, true, true);
this._adapter.upsertState(`${this.liveStreamChannelId}.auto`, constants_1.COMMON_LIVESTREAM_AUTO, this._adapter.config.auto_livestream, true, true);
// Remove legacy states
this._adapter.delObject(`${this.snapshotChannelId}.snapshot_request`);
this._adapter.delObject(`${this.snapshotChannelId}.snapshot_file`);
this._adapter.delObject(`${this.snapshotChannelId}.snapshot_url`);
this._adapter.delObject(`${this.liveStreamChannelId}.livestream_request`);
this._adapter.delObject(`${this.liveStreamChannelId}.livestream_file`);
this._adapter.delObject(`${this.liveStreamChannelId}.livestream_url`);
}
async subscribeToEvents() {
this.silly(`Start device subscriptions`);
await this._ringDevice.subscribeToDingEvents().catch((r) => {
this.catcher(`Failed subscribing to Ding Events for ${this._ringDevice.name}`, r);
});
await this._ringDevice.subscribeToMotionEvents().catch((r) => {
this.catcher(`Failed subscribing to Motion Events for ${this._ringDevice.name}`, r);
});
this._ringDevice.onData.subscribe(this.update.bind(this));
this._ringDevice.onMotionDetected.subscribe({
next: (motion) => {
this.onMotion(motion);
},
error: (err) => {
this.catcher(`Motion Observer received error`, err);
},
});
this._ringDevice.onDoorbellPressed.subscribe({
next: (ding) => {
this.onDoorbell(ding);
},
error: (err) => {
this.catcher(`Doorbell Observer received error`, err);
},
});
this._ringDevice.onNewNotification.subscribe({
next: (ding) => {
this.onDing(ding);
},
error: (err) => {
this.catcher(`Ding Observer received error`, err);
},
});
}
updateDeviceInfoObject(data) {
this._adapter.upsertState(`${this.infoChannelId}.id`, constants_1.COMMON_INFO_ID, data.device_id);
this._adapter.upsertState(`${this.infoChannelId}.kind`, constants_1.COMMON_INFO_KIND, data.kind);
this._adapter.upsertState(`${this.infoChannelId}.description`, constants_1.COMMON_INFO_DESCRIPTION, data.description);
this._adapter.upsertState(`${this.infoChannelId}.external_connection`, constants_1.COMMON_INFO_EXTERNAL_CONNECTION, data.external_connection);
this._adapter.upsertState(`${this.infoChannelId}.hasLight`, constants_1.COMMON_INFO_HAS_LIGHT, this._ringDevice.hasLight);
this._adapter.upsertState(`${this.infoChannelId}.hasBattery`, constants_1.COMMON_INFO_HAS_BATTERY, this._ringDevice.hasBattery);
this._adapter.upsertState(`${this.infoChannelId}.hasSiren`, constants_1.COMMON_INFO_HAS_SIREN, this._ringDevice.hasSiren);
}
updateHistoryObject(lastAction) {
this._adapter.upsertState(`${this.historyChannelId}.created_at`, constants_1.COMMON_HISTORY_CREATED_AT, lastAction.event.created_at);
this._adapter.upsertState(`${this.historyChannelId}.history_url`, constants_1.COMMON_HISTORY_URL, lastAction.historyUrl);
this._adapter.upsertState(`${this.historyChannelId}.kind`, constants_1.COMMON_HISTORY_KIND, lastAction.event.kind);
}
async updateSnapshotRequest(ack = true) {
this._adapter.upsertState(`${this.snapshotChannelId}.${constants_1.STATE_ID_SNAPSHOT_REQUEST}`, constants_1.COMMON_SNAPSHOT_REQUEST, false, ack, true);
}
async updateHDSnapshotRequest(ack = true) {
this._adapter.upsertState(`${this.HDsnapshotChannelId}.${constants_1.STATE_ID_HDSNAPSHOT_REQUEST}`, constants_1.COMMON_HDSNAPSHOT_REQUEST, false, ack, true);
}
async updateSnapshotObject() {
this.debug(`Update Snapshot Object`);
if (this._lastSnapshotTimestamp !== 0) {
this._adapter.upsertState(`${this.snapshotChannelId}.file`, constants_1.COMMON_SNAPSHOT_FILE, this._lastSnapShotDir);
this._adapter.upsertState(`${this.snapshotChannelId}.moment`, constants_1.COMMON_SNAPSHOT_MOMENT, this._lastSnapshotTimestamp);
this._adapter.upsertState(`${this.snapshotChannelId}.url`, constants_1.COMMON_SNAPSHOT_URL, this._lastSnapShotUrl);
}
await this.updateSnapshotRequest();
}
async updateHDSnapshotObject() {
this.debug(`Update HD Snapshot Object`);
if (this._lastHDSnapshotTimestamp !== 0) {
this._adapter.upsertState(`${this.HDsnapshotChannelId}.file`, constants_1.COMMON_HDSNAPSHOT_FILE, this._lastHDSnapShotDir);
this._adapter.upsertState(`${this.HDsnapshotChannelId}.moment`, constants_1.COMMON_HDSNAPSHOT_MOMENT, this._lastHDSnapshotTimestamp);
this._adapter.upsertState(`${this.HDsnapshotChannelId}.url`, constants_1.COMMON_HDSNAPSHOT_URL, this._lastHDSnapShotUrl);
}
await this.updateHDSnapshotRequest();
}
async updateLivestreamRequest(ack = true) {
this._adapter.upsertState(`${this.liveStreamChannelId}.${constants_1.STATE_ID_LIVESTREAM_REQUEST}`, constants_1.COMMON_LIVESTREAM_REQUEST, false, ack, true);
this._durationLiveStream = this._adapter.config.recordtime_livestream;
this._adapter.upsertState(`${this.liveStreamChannelId}.${constants_1.STATE_ID_LIVESTREAM_DURATION}`, constants_1.COMMON_LIVESTREAM_DURATION, this._durationLiveStream, ack, true);
}
async updateLiveStreamObject() {
this.debug(`Update Livestream Object`);
if (this._lastLiveStreamTimestamp !== 0) {
this._adapter.upsertState(`${this.liveStreamChannelId}.file`, constants_1.COMMON_LIVESTREAM_FILE, this._lastLiveStreamDir);
this._adapter.upsertState(`${this.liveStreamChannelId}.url`, constants_1.COMMON_LIVESTREAM_URL, this._lastLiveStreamUrl);
this._adapter.upsertState(`${this.liveStreamChannelId}.moment`, constants_1.COMMON_LIVESTREAM_MOMENT, this._lastLiveStreamTimestamp);
}
await this.updateLivestreamRequest();
}
updateHealthObject(health) {
var _a;
this.debug("Update Health Callback");
let batteryPercent = parseInt((_a = health.battery_percentage) !== null && _a !== void 0 ? _a : "-1");
if (isNaN(batteryPercent)) {
batteryPercent = -1;
}
this._adapter.upsertState(`${this.infoChannelId}.battery_percentage`, constants_1.COMMON_INFO_BATTERY_PERCENTAGE, batteryPercent);
this._adapter.upsertState(`${this.infoChannelId}.battery_percentage_category`, constants_1.COMMON_INFO_BATTERY_PERCENTAGE_CATEGORY, health.battery_percentage_category);
this._adapter.upsertState(`${this.infoChannelId}.wifi_name`, constants_1.COMMON_INFO_WIFI_NAME, health.wifi_name);
this._adapter.upsertState(`${this.infoChannelId}.latest_signal_strength`, constants_1.COMMON_INFO_LATEST_SIGNAL_STRENGTH, health.latest_signal_strength);
this._adapter.upsertState(`${this.infoChannelId}.latest_signal_category`, constants_1.COMMON_INFO_LATEST_SIGNAL_CATEGORY, health.latest_signal_category);
this._adapter.upsertState(`${this.infoChannelId}.firmware`, constants_1.COMMON_INFO_FIRMWARE, health.firmware);
if (this._ringDevice.hasLight && (Date.now() - this._lastLightCommand > 60000)) {
// this.silly(JSON.stringify(this._ringDevice.data));
const floodlightOn = this._ringDevice.data.health.floodlight_on;
this.debug(`Update Light within Health Update Floodlight is ${floodlightOn}`);
this._adapter.upsertState(`${this.lightChannelId}.light_state`, constants_1.COMMON_LIGHT_STATE, floodlightOn);
}
}
onDing(value) {
var _a;
this.debug(`Received Ding Event (${util.inspect(value, true, 1)})`);
this.conditionalRecording(EventState.ReactingOnDing, value.ding.image_uuid);
this._adapter.upsertState(`${this.eventsChannelId}.type`, constants_1.COMMON_EVENTS_TYPE, value.subtype);
this._adapter.upsertState(`${this.eventsChannelId}.detectionType`, constants_1.COMMON_EVENTS_DETECTIONTYPE, (_a = value.ding.detection_type) !== null && _a !== void 0 ? _a : value.subtype);
this._adapter.upsertState(`${this.eventsChannelId}.created_at`, constants_1.COMMON_EVENTS_MOMENT, Date.now());
this._adapter.upsertState(`${this.eventsChannelId}.message`, constants_1.COMMON_EVENTS_MESSAGE, value.aps.alert);
}
onMotion(value) {
this.debug(`Received Motion Event (${util.inspect(value, true, 1)})`);
this._adapter.upsertState(`${this.eventsChannelId}.motion`, constants_1.COMMON_MOTION, value);
value && this.conditionalRecording(EventState.ReactingOnMotion);
}
onDoorbell(value) {
if (this._doorbellEventActive) {
this.debug(`Received Doorbell Event, but we are already reacting. Ignoring.`);
return;
}
this.info("Doorbell pressed --> Will ignore additional presses for the next 25s.");
this.debug(`Received Doorbell Event (${util.inspect(value, true, 1)})`);
this._doorbellEventActive = true;
this._adapter.upsertState(`${this.eventsChannelId}.doorbell`, constants_1.COMMON_EVENTS_DOORBELL, true);
setTimeout(() => {
this._adapter.upsertState(`${this.eventsChannelId}.doorbell`, constants_1.COMMON_EVENTS_DOORBELL, false);
}, 5000);
setTimeout(() => this._doorbellEventActive = false, 25000);
this.conditionalRecording(EventState.ReactingOnDoorbell, value.ding.image_uuid);
}
async conditionalRecording(state, uuid) {
if (this._state !== EventState.Idle) {
this.silly(`Would have recorded due to "${EventState[state]}", but we are already reacting.`);
if (this._adapter.config.auto_HDsnapshot && uuid) {
setTimeout(() => {
this.debug(`delayed HD recording`);
this.takeHDSnapshot();
}, this._adapter.config.recordtime_auto_livestream * 1000 + 3000);
}
if (this._adapter.config.auto_snapshot && uuid) {
setTimeout(() => {
this.debug(`delayed uuid recording`);
this.takeSnapshot(uuid);
}, this._adapter.config.recordtime_auto_livestream * 1000 + 4000);
}
return;
}
this.silly(`Start recording for Event "${EventState[state]}"...`);
this._state = state;
try {
this._adapter.config.auto_HDsnapshot && await this.takeHDSnapshot();
this._adapter.config.auto_snapshot && !this._ringDevice.hasBattery && await this.takeSnapshot(uuid, true);
this._adapter.config.auto_livestream && await this.startLivestream(this._adapter.config.recordtime_auto_livestream);
}
finally {
this._state = EventState.Idle;
}
return;
}
}
exports.OwnRingCamera = OwnRingCamera;
//# sourceMappingURL=ownRingCamera.js.map