-
Notifications
You must be signed in to change notification settings - Fork 13
/
zigbee2mqtt-adapter.js
4233 lines (3447 loc) · 188 KB
/
zigbee2mqtt-adapter.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
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
/**
* zigbee2mqtt-adapter.js - Adapter to use all those zigbee devices via
* zigbee2mqtt.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
'use strict';
const {
spawn,
exec,
execSync,
} = require('child_process');
const https = require('https');
const os = require('os');
const fs = require('fs');
const path = require('path');
//import { promises as fs } from 'fs';
//import { access } from "fs/promises"; // requires node 14
//const crypto = require('crypto');
//const crypto = require('node:crypto');
let crypto;
try {
crypto = require('node:crypto');
} catch (err) {
console.error('modern node crypto support is not available!');
try{
crypto = require('crypto');
}catch (err) {
console.error('node 12 crypto support is not available!');
}
}
const mqtt = require('mqtt');
const {
Adapter,
Device,
Property,
Event
} = require('gateway-addon');
const Zigbee2MQTTHandler = require('./api-handler');
//const DBHandler = require('./lib/db-handler');
const Devices = require('./devices');
const ExposesDeviceGenerator = require('./ExposesDeviceGenerator');
//const colorTranslator = require('./colorTranslator');
const barometer = require('barometer-trend');
const identity = (v) => v;
//console.log("identity = ", identity);
// TODO: noticed these error from the Gateway
//2022-01-24 22:22:38.213 ERROR : zigbee2mqtt-adapter: The `manifest` object is deprecated and will be removed soon. Instead of using `manifest.name`, please read the `id` field from your manifest.json instead.
//2022-01-24 22:22:38.216 ERROR : zigbee2mqtt-adapter: The `manifest` object is deprecated and will be removed soon. Instead of using `manifest.moziot`, please read the user configuration with the `Database` class instead.
class ZigbeeMqttAdapter extends Adapter {
constructor(addonManager, manifest) {
//
// STARTING THE ADDON
//
super(addonManager, 'ZigbeeMqttAdapter', manifest.name);
this.config = manifest.moziot.config;
this.ready = false;
//this.current_os = os.platform().toLowerCase();
this.DEBUG = false;
this.DEBUG2 = false; // debug for incoming messages only
if(typeof this.config == 'undefined'){
console.log("ERROR, THIS.CONFIG IS UNDEFINED! (sqlite error?)");
this.config = {};
this.config.manual_toggle_response = "both";
}
else{
this.DEBUG = this.config.debug;
}
if (typeof this.config.debug == "undefined") {
console.log("Debugging is disabled");
this.DEBUG = false;
} else if (this.config.debug) {
console.log("Debugging is enabled");
console.log(this.config);
//console.log("OS: " + this.current_os);
}
addonManager.addAdapter(this);
this.addon_start_time = Math.floor(+new Date() / 1000);
this.exposesDeviceGenerator = new ExposesDeviceGenerator(this, this.config);
this.reverse_list_contact = ['RH3001']; // All the devices for which the contact property should be reversed. RH3001 is a great usb-rechargeable contact sensor.
this.data_blur_options = ['Off','1 minute','2 minutes','5 minutes','10 minutes','15 minutes','30 minutes','1 hour'];
this.data_blur_option_seconds = [0 ,60 ,120 ,300 ,600 ,900 ,1800 , 3600 ];
// Handle missing default values
if (typeof this.config.local_zigbee2mqtt == "undefined") {
this.config.local_zigbee2mqtt = true;
}
if (typeof this.config.auto_update == "undefined") {
this.config.auto_update = true;
}
if (typeof this.config.measurement_poll_interval == "undefined") {
this.config.measurement_poll_interval = '60'; // tells Z2M how often to poll sockets that measure energy use but need to be periodically polled for their data.
}
//if (typeof this.config.virtual_brightness_alternative == "undefined") {
// this.config.virtual_brightness_alternative = true;
// console.log("this.config.virtual_brightness_alternative = " + this.config.virtual_brightness_alternative);
//}
if (typeof this.config.manual_toggle_response == "undefined") {
if (this.DEBUG) {
console.log("this.config.manual_toggle_response was undefined. Set to BOTH");
}
this.config.manual_toggle_response = "both";
}
if (typeof this.config.prefix == "undefined") {
this.config.prefix = "zigbee2mqtt";
}
if (typeof this.config.mqtt == "undefined") {
this.config.mqtt = "mqtt://localhost";
}
if (this.DEBUG) {
console.log('this.config.mqtt: ', this.config.mqtt);
console.log('this.config.serial_port: ', this.config.serial_port);
}
if (this.config.local_zigbee2mqtt) {
try {
if (typeof this.config.serial_port == "undefined" || this.config.serial_port == "" || this.config.serial_port == null) {
console.log("Serial port is not defined in settings. Will attempt auto-detect.");
this.config.serial_port = null; //"/dev/ttyAMA0";
this.config.serial_port = this.look_for_usb_stick();
}
else{
console.log("this.config.serial_port seems to be pre-defined: ", this.config.serial_port);
}
} catch (e) {
console.log("Error while trying to read serial port: ", e);
this.config.serial_port == null
this.sendPairingPrompt("Error. Looking for Zigbee USB stick failed.");
}
}
else{
console.log("not using local Z2M instance");
}
this.client = null; // will hold MQTT client
this.security = {pan_id: "", network_key: ""};
this.usb_port_issue = false;
this.find_missing_stick_attempted = false;
this.fix_usb_stick_attempted = false;
this.last_really_run_time = 0;
this.z2m_command = 'node /home/pi/.webthings/data/zigbee2mqtt-adapter/zigbee2mqtt/index.js';
this.z2m_installed_succesfully = false;
this.busy_rebuilding_z2m = false;
this.z2m_started = false; // true while running
this.z2m_should_be_running = false; // true is started at least once
this.z2m_state = false;
this.z2m_had_error = false;
this.waiting_for_map = false;
this.updating_firmware = false;
this.update_result = {'status':'idle'}; // will contain the message that Z2M returns after the update process succeeds or fails.
//this.updating_firmware_progress = 0;
this.busy_installing_z2m = false; // True while Z2M is being downloaded and installed
this.config.virtual_brightness_alternative = true;
try{
if (typeof this.config.virtual_brightness_alternative_speed == "undefined") {
this.config.virtual_brightness_alternative_speed = 10;
}
else{
this.config.virtual_brightness_alternative_speed = parseInt(this.config.virtual_brightness_alternative_speed);
}
}
catch(e){
this.config.virtual_brightness_alternative_speed = 10;
}
//console.log("this.config.virtual_brightness_alternative = " + this.config.virtual_brightness_alternative);
//this.persistent_data.virtual_brightness_alternatives = {};
// Availability checking
//this.ignored_first_availability_device_list = []; // For now this has been replaced with just ignoring availabiliy messages for 10 seconds.
//this.addon_start_time = Date.now(); // During the first 10 second after Zigbee2MQTT starts, the availability messages are ignored.
this.availability_interval = 3; // polls devices on the zigbee network every X minutes. Used to discover if lightbulb have been powered down manually.
this.mqtt_connection_attempted = false;
const homedir = require('os').homedir();
//console.log("homedir = " + homedir);
// configuration files location
this.zigbee2mqtt_data_dir_path = path.join(homedir, '.webthings', 'data', 'zigbee2mqtt-adapter');
if (this.DEBUG) {
console.log("this.zigbee2mqtt_data_dir_path = ", this.zigbee2mqtt_data_dir_path);
}
this.node18_shortcut_available = false;
this.node18_shortcut_path = path.join(homedir, 'webthings', 'gateway', 'node18');
if (this.DEBUG) {
console.log("this.node18_shortcut_path = ", this.node18_shortcut_path);
}
// log files location
this.zigbee2mqtt_log_path = path.join(homedir, '.webthings', 'data', 'zigbee2mqtt-adapter','zigbee2mqtt-adapter','log');
if (this.DEBUG) {
console.log("this.zigbee2mqtt_log_path = ", this.zigbee2mqtt_log_path);
}
fs.access(this.zigbee2mqtt_log_path, (err) => {
if (err && err.code === 'ENOENT') {
if (this.DEBUG) {
console.log("z2m logs did not exist, so not necessary to delete them");
}
}
else {
if (this.DEBUG) {
console.log("Deleting any old logs");
}
fs.readdir(this.zigbee2mqtt_log_path, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(this.zigbee2mqtt_log_path, file), err => {
if (err) throw err;
});
}
});
}
});
if (fs.existsSync(this.zigbee2mqtt_log_path)) {
}
// Persistent data file path
this.persistent_data_file_path = path.join(this.zigbee2mqtt_data_dir_path, 'persistent_data.json');
// actual zigbee2mqt location
this.zigbee2mqtt_dir_path = path.join(this.zigbee2mqtt_data_dir_path, 'zigbee2mqtt');
if (this.DEBUG) {
console.log("this.zigbee2mqtt_dir_path = ", this.zigbee2mqtt_dir_path);
}
// download latest Z2M tar file release to this file
this.zigbee2mqtt_data_z2m_release_tar_path = path.join(this.zigbee2mqtt_data_dir_path, 'latest_z2m.tar.gz');
// Directory that should exist is Z2M was installe succesfully
this.zigbee2mqtt_data_z2m_test_path = path.join(this.zigbee2mqtt_dir_path, 'node_modules','zigbee-herdsman');
// index.js file to be started by node
this.zigbee2mqtt_file_path = path.join(this.zigbee2mqtt_dir_path, 'index.js');
// console.log("this.zigbee2mqtt_dir_path =", this.zigbee2mqtt_dir_path);
// should be copied at the first installation
this.zigbee2mqtt_configuration_file_source_path =
path.join(this.zigbee2mqtt_dir_path, 'data', 'configuration.yaml');
this.zigbee2mqtt_configuration_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'configuration.yaml');
// console.log("this.zigbee2mqtt_configuration_file_path =",
// this.zigbee2mqtt_configuration_file_path);
this.zigbee2mqtt_configuration_devices_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'devices.yaml');
this.zigbee2mqtt_configuration_groups_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'groups.yaml');
this.zigbee2mqtt_configuration_security_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'security.yaml');
// console.log("this.zigbee2mqtt_configuration_devices_file_path =",
// this.zigbee2mqtt_configuration_devices_file_path);
this.zigbee2mqtt_coordinator_backup_json_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'coordinator_backup.json');
this.zigbee2mqtt_package_file_path =
path.join(this.zigbee2mqtt_data_dir_path, 'zigbee2mqtt', 'package.json');
// console.log("this.zigbee2mqtt_package_file_path =", this.zigbee2mqtt_package_file_path);
this.zigbee2mqtt_configuration_log_path = path.join(this.zigbee2mqtt_data_dir_path, 'log');
// console.log("this.zigbee2mqtt_configuration_log_path =",
// this.zigbee2mqtt_configuration_log_path);
//this.persistent_data.devices_overview = {}; //new Map(); // stores all the connected devices, and if they can be updated. Could potentially also be used to force-remove devices from the network.
this.persistent_data = {'devices_overview':{},'virtual_brightness_alternatives': {}}
//
// LOAD PERSISTENT
//
try {
fs.access(this.persistent_data_file_path, (err) => {
if (err && err.code === 'ENOENT') {
console.log('persistent data file did not exist yet. Creating it now.');
this.save_persistent_data();
}
else {
if (this.DEBUG) {
console.log('zigbee2mqtt persistent data file existed:');
}
fs.readFile(this.persistent_data_file_path, 'utf8', (error, data) => {
if (error){
console.log("Error reading persistent data file: " + error);
}
//console.log("READING PERSISTENT DATA NOW from data: ", data);
try {
const parsed = JSON.parse(data);
this.persistent_data = parsed;
}
catch (e) {
console.error("Error while parsing loaded persistent data: ", e, data);
}
//console.log(this.persistent_data);
});
}
});
}
catch (e) {
console.error("Error while reading persistent data file: ",e);
}
//
// RESTORE BAROMETER
//
if( typeof this.persistent_data['barometer_measurements'] != 'undefined'){
console.log("barometer values were present in persistent data: ", this.persistent_data['barometer_measurements']);
for (let q = 0; q < this.persistent_data['barometer_measurements'].length; q++){
//this.persistent_data['barometer_measurements'][q].datetime
//this.persistent_data['barometer_measurements'][q].value
var timestamp = Date.parse( this.persistent_data['barometer_measurements'][q].datetime );
var dateObject = new Date(timestamp);
console.log("re-adding value to barometer: " + this.persistent_data['barometer_measurements'][q].value);
barometer.addPressure(dateObject, this.persistent_data['barometer_measurements'][q].value);
}
this.persistent_data['barometer_measurements'].forEach(function(measurement) {
console.log("measurement for-each: ", measurement);
});
}
//
// EXTRA SECURITY
//
this.improve_security = false;
// Check security file
try {
fs.access(this.zigbee2mqtt_configuration_security_file_path, (err) => {
if (err && err.code === 'ENOENT') {
if (this.DEBUG) {
console.log('zigbee2mqtt security file did not exist.');
}
this.security = {
pan_id: rand_hex(4),
network_key: generate_security_key()
};
if (this.DEBUG) {
console.log("new security details: ", this.security);
}
fs.writeFile( this.zigbee2mqtt_configuration_security_file_path, JSON.stringify( this.security ), "utf8", (err, result) => {
if(err){
console.log('security file write error:', err);
this.improve_security = false;
}
else{
if(typeof this.config != 'undefined'){
// Security file now exists. But do we use it?
if(this.config.disable_improved_security == true){
console.log('WARNING: (extra) security has been manually disabled.');
this.improve_security = false;
}
else {
this.improve_security = true;
}
// START
this.pre_run_z2m();
}
else{
console.log("Error: this.config was not defined")
}
}
});
}
else {
if (this.DEBUG) {
console.log('zigbee2mqtt security file existed:');
}
//this.security = require( this.zigbee2mqtt_configuration_security_file_path );
fs.readFile(this.zigbee2mqtt_configuration_security_file_path, 'utf8', (error, data) => {
if (error){
console.log("Error reading security file: " + error);
}
else{
this.security = JSON.parse(data);
if (this.DEBUG) {
console.log("Security settings have been loaded from file: ", this.security);
}
// adding extra security
if(this.config.disable_improved_security == true){
console.log('WARNING: (extra) security has been manually disabled.');
this.improve_security = false;
}
else {
this.improve_security = true;
}
// START
this.pre_run_z2m();
}
});
}
});
}
catch (error) {
console.error("Error while checking/opening security file: " + error.message);
}
// Allow UI to connect
try {
this.apiHandler = new Zigbee2MQTTHandler(
addonManager,
this,
this.config
);
} catch (error) {
console.log("Error loading api handler: " + error)
}
// Start the periodic availability check, which pings routers every 2 minutes.
/*
this.pinging_things = false;
this.ping_interval = setInterval(() => {
// this.config.manual_toggle_response
if (!this.DEBUG) { // TODO: remove this again for more ping testing.
//this.ping_things();
}
}, 120000);
*/
// Every 10 seconds check if Zigbee2MQTT hasn't somehow crashed
this.check_z2m_running = setInterval(() => {
if(this.z2m_should_be_running){
// this.config.manual_toggle_response
if (!this.DEBUG) { // TODO: remove this again for more ping testing.
//this.ping_things();
}
this.check_z2m_is_running();
}
else{
if (this.DEBUG) {
console.log("interval: this.z2m_should_be_running is still false, so not checking if z2m is running");
}
}
// node /home/pi/.webthings/data/zigbee2mqtt-adapter/zigbee2mqtt/index.js
}, 30000);
this.ready = true;
}
// Added yet an even earlier phase...
pre_run_z2m(){
//
// CHECK IF ZIGBEE2MQTT SHOULD BE INSTALLED OR UPDATED
//
if (this.config.local_zigbee2mqtt == true) {
fs.access(this.zigbee2mqtt_data_z2m_test_path, (err) => {
if (err && err.code === 'ENOENT') {
console.log("zigbee2mqtt folder was missing, should download and install");
this.download_z2m(); // this then also installs and starts zigbee2mqtt
} else {
if (this.DEBUG) {
console.log('zigbee2mqtt folder existed.');
}
if (this.config.auto_update) {
console.log('Auto-update is enabled. Checking if Zigbee2MQTT should be updated...');
// downloads json from https://api.github.com/repos/Koenkk/zigbee2mqtt/releases/latest;
try {
const options = {
hostname: 'api.github.com',
port: 443,
path: '/repos/Koenkk/zigbee2mqtt/releases/latest',
method: 'GET',
timeout: 3000,
headers: {
'X-Forwarded-For': 'xxx',
'User-Agent': 'Node',
},
};
const req = https.request(options, (res) => {
if (this.DEBUG) {
console.log('statusCode:', res.statusCode);
}
// console.log('headers:', res.headers);
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
try {
// Parse JSON from api.github
const github_json = JSON.parse(body);
if (this.DEBUG) {
console.log('latest zigbee2MQTT version found on Github =', github_json.tag_name);
}
fs.readFile(this.zigbee2mqtt_package_file_path, 'utf8', (err, data) => {
if (err) {
console.log(`Error reading file from disk: ${err}`);
} else {
const z2m_package_json = JSON.parse(data);
if (this.DEBUG) {
console.log(`local zigbee2MQTT version = ${z2m_package_json.version}`);
}
if (github_json.tag_name == z2m_package_json.version) {
if (this.DEBUG) {
console.log('zigbee2mqtt versions are the same, no need to update zigbee2mqtt');
}
this.run_zigbee2mqtt();
} else {
console.log('a new official release of zigbee2mqtt is available.',
'Will attempt to upgrade.');
this.sendPairingPrompt("Updating Zigbee2MQTT to " + github_json.tag_name);
this.delete_z2m();
this.download_z2m(); // this also then installs and starts zigbee2mqtt
}
}
});
} catch (error) {
console.error(error.message);
this.run_zigbee2mqtt();
}
});
});
req.on('error', (e) => {
console.error(e);
this.run_zigbee2mqtt();
});
req.end();
} catch (error) {
console.error(error.message);
this.run_zigbee2mqtt();
}
} else {
// Skipping auto-update check
this.z2m_installed_succesfully = true;
this.run_zigbee2mqtt();
}
}
}); // end of fs.access check
} else {
console.log("Not using built-in zigbee2mqtt");
this.z2m_started = true;
}
}
look_for_usb_stick(){
if (this.DEBUG) {
console.log("in look_for_usb_stick");
}
var serial_port = null;
try{
if (fs.existsSync('/dev/serial/by-id')) {
let result = require('child_process').execSync('ls -l /dev/serial/by-id').toString();
console.log("output from ls -l/dev/serial/by-id was: ", result);
result = result.split(/\r?\n/);
for (const i in result) {
if (this.DEBUG) {
console.log("line: " + result[i]);
}
if (result[i].length == 3 && result[i].includes("->")) { // If there is only one USB device, grab what you can.
serial_port = "/dev/" + result[i].split("/").pop();
}
// In general, be picky, and look for hints that we found a viable Zigbee stick
if (result[i].toLowerCase().includes("cc253") || result[i].toLowerCase().includes("conbee") || result[i].toLowerCase().includes('cc26x') || result[i].toLowerCase().includes('cc265') || result[i].toLowerCase().includes('igbee') ){ // CC26X2R1, CC253, CC2652
serial_port = "/dev/" + result[i].split("/").pop();
console.log("- USB stick spotted at: " + serial_port);
}
}
}
else{
if (this.DEBUG) {
console.log('/dev/serial/by-id directory did not exist - no serial devices connected');
}
}
if(serial_port == null){
this.sendPairingPrompt("No Zigbee USB stick detected");
}
}
catch(e){
console.log("Error while looking for USB stick: ", e);
}
return serial_port;
}
// This does a brute-force attempt to fix the Zigbee USB stick not responding by turning it off and on again.
// It will currently only do this if only one USB stick was detected.
fix_usb(){
if(this.usb_port_issue && this.fix_usb_stick_attempted == false){
this.fix_usb_stick_attempted = true;
console.log("in fix_usb");
exec("find /sys/bus/usb/devices/usb*/ -name dev | grep ttyUSB", (error, stdout, stderr) => {
console.log(error, stdout, stderr);
const lines = stdout.split(/\r?\n/);
console.log("lines: ", lines.length);
if(lines.length == 2){
if(lines[0].length > 20 && lines[1].length == 0){
const parts = lines[0].split(/\//);
console.log("parts: ", parts);
if(parts.length > 7){
console.log("part 7: ", parts[7]);
const usb_id = parts[7];
// echo 1-1.3 | sudo tee /sys/bus/usb/drivers/usb/unbind
exec("echo " + usb_id + " | sudo tee /sys/bus/usb/drivers/usb/unbind", (error, stdout, stderr) => {
console.log("Turned USB stick off");
setTimeout(() => {
exec("echo " + usb_id + " | sudo tee /sys/bus/usb/drivers/usb/bind", (error, stdout, stderr) => {
console.log("Turned USB stick back on again");
this.look_for_usb_stick();
});
},2000);
});
}
}
}
});
}
}
// Pings all routers to see if they are (still) connected. E.g. lightbulbs that may have been turned off.
ping_things(){
if (this.DEBUG) {
console.log("in ping_things");
}
try{
if(this.z2m_state == true && this.pinging_things == false && typeof this.persistent_data.devices_overview != 'undefined'){
this.pinging_things = true;
var query_delay = 1;
var ping_counter = 0;
for (const device_id in this.persistent_data.devices_overview) {
if (this.persistent_data.devices_overview.hasOwnProperty(device_id)) {
const device_info = this.persistent_data.devices_overview[device_id];
//console.log("availability check loop: " + device_id);
//console.log(device_info);
if( typeof device_info.type != 'undefined'){
//console.log("- device_info.type: " + device_info.type);
//console.log("- device_info.power_source: " + device_info.power_source);
if(device_info.type == 'Router' && device_info.power_source != 'battery'){
var device = this.getDevice(device_id);
if(device){
const wt_id = device_id + "-" + "state";
var property = device.findProperty(wt_id);
if (property) {
//console.log("PINGING TO:");
//console.log(property);
//console.log("property.options: ", property.options);
//console.log("should ping this device. query_delay: " + query_delay);
ping_counter++;
setTimeout(() => {
const z_id = device_info.zigbee_id;
if (this.DEBUG) {
console.log(query_delay + " pinging: " + device_info.zigbee_id);
}
//console.log("ping alt: " + z_id);
this.publishMessage(`${device_info.zigbee_id}/get`, {
"state": ""
});
}, query_delay);
query_delay += 1000;
}
else{
console.log("ping: potential device didn't have state, skipping: " + device_id);
}
}
}
}
}
}
setTimeout(() => {
if (this.DEBUG) {
console.log('finished pinging devices');
}
this.pinging_things = false;
}, ping_counter * 1001);
}
}
catch(e){
console.log("error in ping_things: ", e);
}
}
// By having the config files outside of the zigbee2mqtt folder it becomes easier to update zigbee2mqtt
check_if_config_file_exists() {
try {
if (this.DEBUG) {
console.log('Checking if config file exists');
}
if(this.config.manual_configuration_file){
if (this.DEBUG) {
console.log('Configuration file is set to manual mode, skipping creation of new file.');
}
return;
}
fs.access(this.zigbee2mqtt_configuration_file_path, (err) => {
if (err && err.code === 'ENOENT') {
console.log('The configuration.yaml source file didn\'t exist yet:', this.zigbee2mqtt_configuration_file_path);
}
var base_config = "";
// Home Assistant support
if (this.config.home_assistant_support == true) {
base_config += "homeassistant: true\n";
}
else{
base_config += "homeassistant: false\n";
}
base_config += "permit_join: false\n" +
"devices: devices.yaml\n" +
"groups: groups.yaml\n" +
"mqtt:\n" +
" base_topic: zigbee2mqtt\n" +
" server: 'mqtt://localhost'\n" +
"serial:\n" +
" port: " + this.config.serial_port + "\n";
if(typeof this.config.custom_serial != 'undefined'){
if(this.config.custom_serial != ""){
base_config += " " + this.config.custom_serial + "\n";
}
}
base_config += "availability:\n" +
" active:\n" +
" timeout: " + this.availability_interval + "\n" +
" passive:\n" +
" timeout: 1500\n" +
"ota:\n" +
" update_check_interval: 2880\n" +
"advanced:\n" +
" cache_state: true\n" +
" cache_state_persistent: true\n" +
" cache_state_send_on_startup: true\n" +
" last_seen: 'epoch'\n";
//console.log("this.config.disable_improved_security = " + this.config.disable_improved_security);
if(this.improve_security){
if (this.DEBUG) {
console.log('Adding extra security.');
console.log("this.security.pan_id = " + this.security.pan_id);
}
if(this.security.pan_id != ""){
base_config += " pan_id: " + this.security.pan_id + "\n" +
" network_key: [" + this.security.network_key + "]\n";
}
else{
console.log('Warning: security pan_id was empty! Security was not upgraded, and is using default values.');
}
}
base_config += " legacy_api: false\n" +
"device_options:\n" +
" debounce: .1\n" +
//" debounce_ignore: action\n" +
" legacy: false\n" +
" measurement_poll_interval: " + this.config.measurement_poll_interval + "\n" +
" filtered_attributes: ['Action group', 'Action rate', 'xy']\n";
//if(!this.config.virtual_brightness_alternative){
//console.log("using Zigbee2MQTT's built-in simulated brightness feature");
base_config += " simulated_brightness:\n" +
" delta: 2\n" +
" interval: 100\n";
//}
//base_config += "external_converters:\n" +
//" - door_lock.js\n" +;
//" - TZE200_kzm5w4iz.js\n";
//" - leak.js\n";
if (this.DEBUG) {
console.log("- - -");
console.log(base_config);
console.log("- - -");
}
fs.writeFile(this.zigbee2mqtt_configuration_file_path, base_config, (err) => {
if (err) {
console.log("Error writing base configuration.yaml file");
} else {
console.log('basic configuration.yaml file was succesfully created at: ' + this.zigbee2mqtt_configuration_file_path);
}
});
});
} catch (error) {
console.error(`Error checking if zigbee2mqtt config file exists: ${error.message}`);
}
}
stop_zigbee2mqtt() {
if (this.DEBUG) {
console.log("in stop-zigbee2mqtt");
}
try {
this.zigbee2mqtt_subprocess.kill();
} catch (error) {
console.error(`Error stopping zigbee2mqtt: ${error.message}`);
if (this.config.local_zigbee2mqtt == true) {
// Make sure previous instances of Zigbee2mqtt are gone
try {
//execSync("pgrep -f 'zigbee2mqtt-adapter/zigbee2mqtt/index.js' | xargs kill -9");
execSync("pkill 'zigbee2mqtt-adapter/zigbee2mqtt/index.js'");
console.log("pkill done");
} catch (error) {
console.log("exec pkill error: " + error);
}
}
}
}
run_zigbee2mqtt(delay = 10) {
if (this.DEBUG) {
console.log("in run_zigbee2mqtt. Will really start in: " + delay + " seconds. this.config.serial_port: ", this.config.serial_port);
}
if(this.config.serial_port == null || this.config.serial_port == ""){
console.log("ZIGBEE2MQTT will not start: no USB stick detected");
return;
}
setTimeout(this.check_if_config_file_exists.bind(this), 4000);
setTimeout(this.connect_to_mqtt.bind(this), delay * 1000); // wait 10 seconds before really starting Zigbee2MQTT, to make sure serial port has been released.
}
//if(this.mqtt_connection_attempted == false){
// this.connect_to_mqtt();
//}
connect_to_mqtt(){
//console.log("attempting to latch onto MQTT");
// Start MQTT connection
this.client = mqtt.connect(this.config.mqtt);
this.client.on('connect', () => {
this.mqtt_connected = true;
this.client.subscribe(`${this.config.prefix}/bridge/devices`);
this.client.subscribe(`${this.config.prefix}/bridge/state`);
//this.client.subscribe(`${this.config.prefix}/bridge/event`); // in practise these messages hardly ever appear, and were useless. Used availability instead.
this.client.subscribe(`${this.config.prefix}/bridge/response/networkmap`);
this.client.subscribe(`${this.config.prefix}/bridge/response/device/ota_update/update`);
this.client.subscribe(`${this.config.prefix}/bridge/response/device/ota_update/check`);
if(this.z2m_started == false){
if (this.DEBUG) {
console.log("MQTT is now connected. Next, starting Zigbee2MQTT");
}
if(this.z2m_had_error){
setTimeout(() => {
this.really_run_zigbee2mqtt();
}, 15000);
}
else{
this.really_run_zigbee2mqtt();
}