-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.js
More file actions
1904 lines (1685 loc) · 50.6 KB
/
Copy pathapp.js
File metadata and controls
1904 lines (1685 loc) · 50.6 KB
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* jslint node: true */
'use strict';
if (process.env.DEBUG === '1')
{
// eslint-disable-next-line node/no-unsupported-features/node-builtins, global-require
require('inspector').open(9224, '0.0.0.0', true);
}
const Homey = require('homey');
const { OAuth2App } = require('homey-oauth2app');
const nodemailer = require('nodemailer');
const HubInterface = require('./lib/hub_interface');
const BLEHubInterface = require('./lib/ble_hub_interface');
const SwitchBotOAuth2Client = require('./lib/SwitchBotOAuth2Client');
const MINIMUM_POLL_INTERVAL = 15; // in Seconds
const SECONDS_PER_DAY = 86400;
const DAILY_API_QUOTA = 10000;
const COMMAND_API_OVERHEAD = 500;
const POLLING_DAILY_BUDGET = DAILY_API_QUOTA - COMMAND_API_OVERHEAD;
const BLE_POLLING_INTERVAL = 30000; // in milliSeconds
class MyApp extends OAuth2App
{
toPositiveInteger(value, fallback = 1)
{
const parsedValue = Number.parseInt(value, 10);
if (!Number.isFinite(parsedValue) || (parsedValue < 1))
{
return fallback;
}
return parsedValue;
}
installProcessErrorGuards()
{
if (this.processErrorGuardsInstalled)
{
return;
}
this.processErrorGuardsInstalled = true;
process.on('unhandledRejection', (reason) =>
{
const message = this.varToString(reason);
try
{
this.updateLog(`Unhandled rejection captured: ${message}`, 0, 'hub');
}
catch (err)
{
if (this.originalError)
{
this.originalError(`Unhandled rejection captured: ${message}`);
}
}
});
process.on('uncaughtException', (error) =>
{
const message = this.varToString(error);
try
{
this.updateLog(`Uncaught exception captured: ${message}`, 0, 'hub');
}
catch (err)
{
if (this.originalError)
{
this.originalError(`Uncaught exception captured: ${message}`);
}
}
});
}
safeSetSetting(key, value)
{
try
{
const result = this.homey.settings.set(key, value);
if (result && typeof result.catch === 'function')
{
result.catch((err) =>
{
this.updateLog(`Failed to persist setting \"${key}\": ${err.message}`, 0, 'hub');
});
}
}
catch (err)
{
this.updateLog(`Failed to persist setting \"${key}\": ${err.message}`, 0, 'hub');
}
}
persistApiCalls(immediate = false)
{
if (immediate)
{
if (this.apiCallsPersistTimer)
{
this.homey.clearTimeout(this.apiCallsPersistTimer);
this.apiCallsPersistTimer = null;
}
this.safeSetSetting('apiCalls', this.apiCalls);
return;
}
if (this.apiCallsPersistTimer)
{
return;
}
this.apiCallsPersistTimer = this.homey.setTimeout(() =>
{
this.apiCallsPersistTimer = null;
this.safeSetSetting('apiCalls', this.apiCalls);
}, 5000);
}
incrementApiCalls(increment = 1)
{
const value = Number.parseInt(increment, 10);
const step = Number.isFinite(value) && (value > 0) ? value : 1;
this.apiCalls = this.toPositiveInteger(this.apiCalls, 0) + step;
this.persistApiCalls();
return this.apiCalls;
}
formatRateLimitErrorMessage(message)
{
const rawMessage = message ? String(message) : 'Unknown error';
const isRateLimitError = /rate\s*limit|too\s*many\s*requests|\b429\b|\b190\b/i.test(rawMessage);
if (!isRateLimitError || /API calls/i.test(rawMessage))
{
return rawMessage;
}
return `${rawMessage} (${this.apiCalls} API calls)`;
}
formatMacAddress(value)
{
if (!value)
{
return value;
}
const macText = String(value);
if (macText.includes(':'))
{
return macText;
}
const hexText = macText.replace(/[^a-fA-F0-9]/g, '');
if (hexText.length !== 12)
{
return macText;
}
return hexText.match(/.{1,2}/g).join(':').toUpperCase();
}
getWebhookAuthMode()
{
const oAuth2Client = this.getFirstSavedOAuth2Client();
if (oAuth2Client)
{
return 'OAuth2 session';
}
if (this.openToken && this.openSecret)
{
return 'API token/secret';
}
return 'unavailable (no OAuth session and no API token/secret)';
}
normalizeLogMessage(newMessage)
{
const message = this.redactSensitiveLogData((typeof newMessage === 'string') ? newMessage : this.varToString(newMessage));
const peripheralFormatted = message.replace(/(Peripheral Not Found:\s*)([a-fA-F0-9]{12})(\b)/g, (fullText, prefix, id, suffix) => `${prefix}${this.formatMacAddress(id)}${suffix}`);
return peripheralFormatted.replace(/(No data for\s*)([a-fA-F0-9]{12})(\b)/gi, (fullText, prefix, id, suffix) => `${prefix}${this.formatMacAddress(id)}${suffix}`);
}
redactSensitiveLogData(message)
{
if (typeof message !== 'string' || message.length === 0)
{
return message;
}
let sanitized = message;
// Redact known query/body secret patterns.
sanitized = sanitized
.replace(/([?&]client_id=)[^&\s]+/gi, '$1***')
.replace(/([?&]client_secret=)[^&\s]+/gi, '$1***')
.replace(/([?&]code=)[^&\s]+/gi, '$1***')
.replace(/([?&]token=)[^&\s]+/gi, '$1***')
.replace(/(Authorization\s*:\s*Bearer\s+)[^\s]+/gi, '$1***')
.replace(/(\"Authorization\"\s*:\s*\"Bearer\s+)[^\"]+(\")/gi, '$1***$2');
// Redact env.json values if they accidentally appear in logs.
const env = Homey && Homey.env ? Homey.env : {};
const envKeysToRedact = [
'CLIENT_ID',
'CLIENT_SECRET',
'MAIL_HOST',
'MAIL_USER',
'MAIL_SECRET',
'MAIL_RECIPIENT',
'WEBHOOK_ID',
'WEBHOOK_SECRET',
'WEBHOOK_URL',
'USER_AGENT_HEADER',
];
for (const key of envKeysToRedact)
{
const value = env[key];
if (typeof value === 'string' && value.length > 0)
{
sanitized = sanitized.split(value).join('***');
}
}
return sanitized;
}
overrideLoggingMethods()
{
// Store original console methods to restore later
this.originalLog = console.log;
this.originalError = console.error;
this.originalWarn = console.warn;
this.originalInfo = console.info;
console.log = (message, ...optionalParams) =>
{
if (this.handleLogMessage(message, ...optionalParams))
{
this.originalLog.apply(console, [message, ...optionalParams]);
}
};
console.error = (message, ...optionalParams) =>
{
if (this.handleLogMessage(message, ...optionalParams))
{
this.originalError.apply(console, [message, ...optionalParams]);
}
};
console.warn = (message, ...optionalParams) =>
{
if (this.handleLogMessage(message, ...optionalParams))
{
this.originalWarn.apply(console, [message, ...optionalParams]);
}
};
console.info = (message, ...optionalParams) =>
{
if (this.handleLogMessage(message, ...optionalParams))
{
this.originalInfo.apply(console, [message, ...optionalParams]);
}
};
}
restoreLoggingMethods()
{
if (this.originalLog)
{
console.log = this.originalLog;
console.error = this.originalError;
console.warn = this.originalWarn;
console.info = this.originalInfo;
}
}
handleLogMessage(message, ...optionalParams)
{
const logMessage = optionalParams
.map((param) => this.varToString(param))
.join(' ');
// if the logMessage contains 'User-Agent' then replace the user-agent value with '***'
if (logMessage.includes('User-Agent:'))
{
const logMessageArray = logMessage.split(' ');
const userAgentIndex = logMessageArray.findIndex((element) => element === 'User-Agent:');
if (userAgentIndex !== -1)
{
logMessageArray[userAgentIndex + 2] = '***';
}
this.updateLog(logMessageArray.join(' '), 2, 'hub');
return true;
}
this.updateLog(this.varToString(logMessage), 2, 'hub');
return true;
}
static OAUTH2_CLIENT = SwitchBotOAuth2Client; // Default: OAuth2Client
static OAUTH2_DEBUG = true; // Default: false
static OAUTH2_MULTI_SESSION = false; // Default: false
static OAUTH2_DRIVERS = [
'air_con_hub',
'air_puifier_hub',
'blind_tilt_hub',
'bot_hub',
'camera_hub',
'camera_plus_hub',
'color_bulb_hub',
'contact_hub',
'curtains_hub',
'custom_remote_hub',
'dvd',
'fan_hub',
'hub3',
'humidifier_hub',
'humidifier2_hub',
'light_remote_hub',
'lock_hub',
"lock_ultra_hub",
'lock_vision_pro_hub',
'meter_pro_CO2_hub',
'meter_pro_hub',
'plug_eu_hub',
'plug_hub',
'presence_hub',
'relay_hub',
'relay2pm_hub',
'robot_vacuum_hub',
'robot_vacuum_K20_hub',
'robot_vacuum_S10_hub',
'roller_blind_hub',
'S10_water_station',
'scene',
'settop_box_hub',
'smart_fan_hub',
'smart_fan_new_hub',
'speaker',
'strip_light',
'temperature_hub',
'tv_hub',
'water_leak_hub',
];
/**
* onInit is called when the app is initialized.
*/
async onOAuth2Init()
{
this.overrideLoggingMethods();
this.installProcessErrorGuards();
this.log('SwitchBot has been initialized');
this.logLevel = this.homey.settings.get('logLevel');
if (this.logLevel === null)
{
this.logLevel = 0;
this.safeSetSetting('logLevel', this.logLevel);
}
this.diagLog = '';
this.deviceStatusLog = '';
this.openToken = this.homey.settings.get('openToken');
this.openSecret = this.homey.settings.get('openSecret');
this.blePolling = false;
this.bleBusy = false;
this.devicesMACs = [];
this.homeyWebhookRegTimerID = null;
this.switchBotWebhookTimerID = null;
this.apiCallsPersistTimer = null;
if (this.logLevel >= 0)
{
this.enableOAuth2Debug();
}
else
{
this.disableOAuth2Debug();
}
this.processWebhookMessage.bind(this);
this.numConnections = this.toPositiveInteger(this.homey.settings.get('numConnections'));
if (!this.homey.settings.get('numConnections'))
{
this.numConnections = 1;
this.safeSetSetting('numConnections', this.numConnections);
}
this.apiCalls = this.homey.settings.get('apiCalls');
if (!this.apiCalls)
{
this.apiCalls = 0;
}
// Set timer to reset the api counter at midnight
if (this.apiCountReset)
{
this.homey.clearTimeout(this.apiCountReset);
}
const nowTime = new Date(Date.now());
let newTime = new Date(Date.now());
newTime.setDate(nowTime.getDate() + 1);
newTime.setHours(0);
newTime.setMinutes(0);
newTime -= nowTime;
this.resetAPICount = this.resetAPICount.bind(this);
const resestIn = newTime.valueOf();
this.apiCountReset = this.homey.setTimeout(this.resetAPICount, resestIn);
if (process.env.DEBUG === '1')
{
this.safeSetSetting('debugMode', true);
}
else
{
this.safeSetSetting('debugMode', false);
}
this.hub = new HubInterface(this.homey);
try
{
this.homeyID = await this.homey.cloud.getHomeyId();
}
catch (err)
{
this.homeyID = 'unknown-homey';
this.updateLog(`Failed to get Homey ID at startup: ${err.message}`, 0, 'all');
}
// Setup the SwitchBot webhook after a short delay to allow devices to register
this.updateLog(`Webhook auth mode at startup: ${this.getWebhookAuthMode()}`, 0, 'all');
this.switchBotWebhookTimerID = this.homey.setTimeout(() =>
{
this.setupSwitchBotWebhook();
}, 5000);
this.homeyHash = this.homeyID;
this.homeyHash = this.hashCode(this.homeyHash).toString();
try
{
this.homeyIP = await this.homey.cloud.getLocalAddress();
}
catch (err)
{
// For cloud debugging only
this.logLevel = 0;
this.safeSetSetting('logLevel', this.logLevel);
this.homeyIP = null;
}
// Callback for app settings changed
this.homey.settings.on('set', async (setting) =>
{
try
{
this.homey.app.updateLog(`Setting ${setting} has changed.`, 3, 'hub');
if (setting === 'logLevel')
{
this.logLevel = this.homey.settings.get('logLevel');
if (this.logLevel > 2)
{
this.homey.app.enableOAuth2Debug();
}
else
{
this.homey.app.disableOAuth2Debug();
}
}
else if (setting === 'openToken')
{
this.openToken = this.homey.settings.get('openToken');
}
else if (setting === 'openSecret')
{
this.openSecret = this.homey.settings.get('openSecret');
}
else if (setting === 'numConnections')
{
this.numConnections = this.toPositiveInteger(this.homey.settings.get('numConnections'));
}
}
catch (err)
{
this.updateLog(`settings.on('set') handler error (${setting}): ${err.message}`, 0, 'hub');
}
});
// Set to true to enable use of my BLE hub (WIP)
this.BLEHub = null;
try
{
this.homeyIP = await this.homey.cloud.getLocalAddress();
if (this.homeyIP)
{
this.BLEHub = new BLEHubInterface(this.homey, this.homeyIP);
}
}
catch (err)
{
// Homey cloud or Bridge so no LAN access
this.homeyIP = null;
}
this.onHubPoll = this.onHubPoll.bind(this);
this.hubDevices = 0;
this.timerHubID = null;
this.onBLEPoll = this.onBLEPoll.bind(this);
this.bleDevices = 0;
this.bleTimerID = null;
// Webhook registration backoff tracking
this.webhookRetryCount = 0;
// Track in-progress OAuth flows started from settings
this.settingsOAuthFlows = {};
// Register flow cards
const operateAction = this.homey.flow.getActionCard('operate_aircon');
operateAction
.registerRunListener(async (args, state) =>
{
// this.log('activate_instant_mode');
return args.device.onCapabilityAll(args);
});
const onAction = this.homey.flow.getActionCard('on');
onAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('turnOn');
});
const offAction = this.homey.flow.getActionCard('off');
offAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('turnOff');
});
const muteAction = this.homey.flow.getActionCard('mute');
muteAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('mute');
});
const playAction = this.homey.flow.getActionCard('play');
playAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('play');
});
const startAction = this.homey.flow.getActionCard('start');
startAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('start');
});
const pauseAction = this.homey.flow.getActionCard('pause');
pauseAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('pause');
});
const stopAction = this.homey.flow.getActionCard('stop');
stopAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('stop');
});
const dockAction = this.homey.flow.getActionCard('dock');
dockAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('dock');
});
const prevAction = this.homey.flow.getActionCard('prev');
prevAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('prev');
});
const nextAction = this.homey.flow.getActionCard('next');
nextAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('next');
});
const setChannelAction = this.homey.flow.getActionCard('set_channel');
setChannelAction
.registerRunListener(async (args, state) =>
{
return args.device._operateDevice('SetChannel', args.channel_number.toString());
});
const rewindAction = this.homey.flow.getActionCard('rewind');
rewindAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('rewind');
});
const forwardAction = this.homey.flow.getActionCard('forward');
forwardAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('forward');
});
const startSceneAction = this.homey.flow.getActionCard('start_scene');
startSceneAction
.registerRunListener(async (args, state) =>
{
// this.log('activate_instant_mode');
return args.device.onCapabilityStartScene();
});
const runSceneAction = this.homey.flow.getActionCard('run_scene');
runSceneAction.registerRunListener(async (args, state) =>
{
await this.runScene(args.scene.data.id);
});
runSceneAction.registerArgumentAutocompleteListener('scene', async (query, args) =>
{
const results = await this.getScenes();
if (query === '')
{
return results;
}
// filter based on the query
return results.filter((result) =>
{
return result.name.toLowerCase().includes(query.toLowerCase());
});
});
const nebulizationModeAction = this.homey.flow.getActionCard('nebulization_mode');
nebulizationModeAction.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityNebulization(args);
});
const nebulizationEfficiencyAction = this.homey.flow.getActionCard('nebulization_efficiency');
nebulizationEfficiencyAction.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityNebulization(args);
});
const smartFanAction = this.homey.flow.getActionCard('smart_fan_mode');
smartFanAction.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityFanSettings(args);
});
const circulatingFanAction = this.homey.flow.getActionCard('circulating_fan_mode');
circulatingFanAction.registerRunListener(async (args, state) =>
{
args.device.setCapabilityValue('smart_fan_mode2', args.fan_mode).catch(this.error);
return args.device.onCapabilityFanMode(args.fan_mode);
});
const setNightLightAction = this.homey.flow.getActionCard('set_night_light');
setNightLightAction.registerRunListener(async (args, state) =>
{
args.device.setCapabilityValue('night_light', args.night_light).catch(this.error);
return args.device.onCapabilityNightLight(args.night_light);
});
const fanSwingAction = this.homey.flow.getActionCard('fan_swing');
fanSwingAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('swing');
});
const fanLowSpeedAction = this.homey.flow.getActionCard('fan_low_speed');
fanLowSpeedAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('lowSpeed');
});
const fanMediumSpeedAction = this.homey.flow.getActionCard('fan_medium_speed');
fanMediumSpeedAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('middleSpeed');
});
const fanHighSpeedAction = this.homey.flow.getActionCard('fan_high_speed');
fanHighSpeedAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('highSpeed');
});
const sendRemoteCommandAction = this.homey.flow.getActionCard('send_custom_remote_command');
sendRemoteCommandAction.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityButtonPressed(args.command.id);
});
sendRemoteCommandAction.registerArgumentAutocompleteListener('command', async (query, args) =>
{
const results = await args.device.getButtonList();
// filter based on the query
return results.filter((result) =>
{
return result.name.toLowerCase().includes(query.toLowerCase());
});
});
const brightnessDownAction = this.homey.flow.getActionCard('brightness_down');
brightnessDownAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('brightnessDown');
});
const brightnessUpAction = this.homey.flow.getActionCard('brightness_up');
brightnessUpAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityCommand('brightnessUp');
});
const tiltAction = this.homey.flow.getActionCard('windowcoverings_tilt_set');
tiltAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityPosition(args.windowcoverings_tilt_set);
});
const vaccumPowerAction = this.homey.flow.getActionCard('set_vaccum_power');
vaccumPowerAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityPowerLevel(parseInt(args.power, 10));
});
const humidifierModeAction = this.homey.flow.getActionCard('set_humidifier_mode');
humidifierModeAction
.registerRunListener(async (args, state) =>
{
args.device.setCapabilityValue('measure_humidity', parseInt(args.humidity, 10));
args.device.setCapabilityValue('humidifier_mode', args.mode);
const valueObj = {
humidifier_mode: parseInt(args.mode, 10),
target_humidity: parseInt(args.humidity, 10),
}
return args.device.onCapabilityMode(valueObj);
});
const airPurifierModeAction = this.homey.flow.getActionCard('set_air_purifier_mode');
airPurifierModeAction
.registerRunListener(async (args, state) =>
{
args.device.setCapabilityValue('fan_level', args.fan_level.toString()).catch(this.error);
args.device.setCapabilityValue('air_purifier_mode', args.mode.toString()).catch(this.error);
return args.device.onCapabilityMode({ air_purifier_mode: args.mode, fan_level: args.fan_level });
});
const windowCoversAction = this.homey.flow.getActionCard('windowcoverings_custom_set');
windowCoversAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityPosition(args.percentage, args.speed);
});
const vaccumStartAction = this.homey.flow.getActionCard('set_vaccum_start');
vaccumStartAction
.registerRunListener(async (args, state) =>
{
return args.device.startVacuum(args.action, parseInt(args.fanPower, 10), parseInt(args.waterLevel, 10), parseInt(args.times, 10));
});
const lockAction = this.homey.flow.getActionCard('lock');
lockAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityLock();
});
const unlockAction = this.homey.flow.getActionCard('unlock');
unlockAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityUnlock();
});
const deadboltAction = this.homey.flow.getActionCard('deadbolt');
deadboltAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityDeadbolt();
});
const relay1OnAction = this.homey.flow.getActionCard('onoff_relay1_true');
relay1OnAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOnOff('1', true)
});
const relay1OffAction = this.homey.flow.getActionCard('onoff_relay1_false');
relay1OffAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOnOff('1', false)
});
const relay2OnAction = this.homey.flow.getActionCard('onoff_relay2_true');
relay2OnAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOnOff('2', true)
});
const relay2OffAction = this.homey.flow.getActionCard('onoff_relay2_false');
relay2OffAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOnOff('2', false);
});
const radiatorThermostatModeAction = this.homey.flow.getActionCard('set_radiator_thermostat_mode');
radiatorThermostatModeAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityRadiatorThermostatMode(args.mode);
});
const openCloseOnAction = this.homey.flow.getActionCard('open_close_true');
openCloseOnAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOpenClose(true)
});
const openCloseOffAction = this.homey.flow.getActionCard('open_close_false');
openCloseOffAction
.registerRunListener(async (args, state) =>
{
return args.device.onCapabilityOpenClose(false)
});
/** * CONDITIONS ** */
this.conditionVaccumStateIs = this.homey.flow.getConditionCard('vaccum_state_is');
this.conditionVaccumStateIs.registerRunListener((args) =>
{
const { device, state } = args;
const conditionMet = (device.getCapabilityValue('robot_vaccum_state') === state);
return Promise.resolve(conditionMet);
});
// Device Triggers
this.stateChangedTrigger = this.homey.flow.getDeviceTriggerCard('vaccum_state_changed');
this.stateChangedToTrigger = this.homey.flow.getDeviceTriggerCard('vaccum_state_changed_to');
this.stateChangedToTrigger.registerRunListener(async (args, state) =>
{
if (state && (args.state === state.state))
{
return true;
}
return false;
});
this.taskChangedTrigger = this.homey.flow.getDeviceTriggerCard('vaccum_task_changed');
this.taskChangedToTrigger = this.homey.flow.getDeviceTriggerCard('vaccum_task_changed_to');
this.taskChangedToTrigger.registerRunListener(async (args, state) =>
{
if (state && (args.state === state.state))
{
return true;
}
return false;
});
this.positionLessThanTrigger = this.homey.flow.getDeviceTriggerCard('position_became_less');
this.positionLessThanTrigger.registerRunListener(async (args, state) =>
{
if ((args.position_threshold > state.position) && (args.position_threshold <= state.lastPosition))
{
return true;
}
return false;
});
this.positionGreaterThanTrigger = this.homey.flow.getDeviceTriggerCard('position_became_greater');
this.positionGreaterThanTrigger.registerRunListener(async (args, state) =>
{
if ((args.position_threshold < state.position) && (args.position_threshold >= state.lastPosition))
{
return true;
}
return false;
});
this.homey.app.updateLog('****** App has initialised. ******', 'hub');
}
async triggerPositionLessThan(device, tokens, state)
{
this.positionLessThanTrigger.trigger(device, tokens, state).catch(this.error);
}
async triggerPositionGreaterThan(device, tokens, state)
{
this.positionGreaterThanTrigger.trigger(device, tokens, state).catch(this.error);
}
async onUninit()
{
if (this.apiCountReset)
{
this.homey.clearTimeout(this.apiCountReset);
this.apiCountReset = null;
}
if (this.homeyWebhookRegTimerID)
{
this.homey.clearTimeout(this.homeyWebhookRegTimerID);
this.homeyWebhookRegTimerID = null;
}
if (this.switchBotWebhookTimerID)
{
this.homey.clearTimeout(this.switchBotWebhookTimerID);
this.switchBotWebhookTimerID = null;
}
if (this.timerHubID)
{
this.homey.clearTimeout(this.timerHubID);
this.timerHubID = null;
}
if (this.bleTimerID)
{
this.homey.clearTimeout(this.bleTimerID);
this.bleTimerID = null;
}
this.persistApiCalls(true);
this.restoreLoggingMethods();
await this.deleteSwitchBotWebhook();
}
resetAPICount()
{
this.apiCalls = 0;
this.persistApiCalls(true);
// Set timer to reset the count at midnight
this.apiCountReset = this.homey.setTimeout(this.resetAPICount, 86400 * 1000);
}
getAPICount()
{
return this.apiCalls;
}
hashCode(s)
{
let h = 0;
for (let i = 0; i < s.length; i++) h = Math.imul(31, h) + s.charCodeAt(i) | 0;
return h;
}
varToString(source)
{
try
{
if (source === null)
{
return 'null';
}
if (source === undefined)
{
return 'undefined';