-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1195 lines (979 loc) · 53.5 KB
/
index.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
//'use strict';
// ****************** start of settings
// name and version
const packagejson = require('./package.json');
const PLUGIN_NAME = packagejson.name;
const PLATFORM_NAME = packagejson.platformname;
const PLUGIN_VERSION = packagejson.version;
// required node modules
//const fs = require('fs'); -- removed in 1.0.4, not needed
//const fsPromises = require('fs').promises; -- removed in 1.0.4, not needed
//const path = require('path'); -- removed in 1.0.4, not needed
//import SamsungRemote from 'samsung-remote'; // https://github.com/natalan/samsung-remote
const SamsungRemote = require('samsung-remote'); // https://github.com/natalan/samsung-remote
// https://github.com/Samfox2/homebridge-cec-tv-platform/blob/main/index.js
//const CecController = require('cec-controller');
// exec spawns child process to run a bash script
const exec = require("child_process").exec;
// to detect dev env
var PLUGIN_ENV = ''; // controls the development environment, appended to UUID to make unique device when developing
// general constants
const NO_INPUT_ID = 999; // default to input 999, no input
const NO_INPUT_NAME = 'UNKNOWN'; // an input name that does not exist
const POWER_STATE_DEFAULT_POLLING_INTERVAL_MS = 3000; // default polling interval in millisec
const POWER_STATE_MAX_TRANSITION_TIME_S = 30; // the maximum transition time we allow for a device to come online after a power ON command, default 30 s
const mediaStateName = ["PLAY", "PAUSE", "STOP", "UNKNOWN3", "LOADING", "INTERRUPTED"];
const powerStateName = ["OFF", "ON"];
//const powerStateTransition = { NOT_TRANSITIONING: 0, TRANSITIONING_ON_TO_OFF: 1, TRANSITIONING_OFF_TO_ON: 2 }; // used by HDMI-CEC
Object.freeze(mediaStateName);
Object.freeze(powerStateName);
// global variables (urgh)
// let currentInputId;
//let currentPowerState;
//let currentMediaState;
//let targetMediaState;
let Accessory, Characteristic, Service, Categories, UUID;
// wait function
const wait=ms=>new Promise(resolve => setTimeout(resolve, ms));
// wait function with promise
function waitprom(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms)
}, ms )
})
}
// funtion to return a unique set of keys from an array
function uniqBy(arr, key) {
return Object.values([...arr].reverse().reduce((m, i) => {m[key.split('.').reduce((a, p) => a?.[p], i)] = i; return m;}, {}))
}
// ++++++++++++++++++++++++++++++++++++++++++++
// config
// ++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++
// platform setup
// ++++++++++++++++++++++++++++++++++++++++++++
module.exports = (api) => {
Accessory = api.platformAccessory;
Characteristic = api.hap.Characteristic;
Service = api.hap.Service;
Categories = api.hap.Categories;
UUID = api.hap.uuid;
api.registerPlatform(PLUGIN_NAME, PLATFORM_NAME, samsungTvHtPlatform, true);
};
class samsungTvHtPlatform {
// build the platform. Runs once on restart
constructor(log, config, api) {
// only load if configured
if (!config) {
log.warn('WARNING: No configuration found for %s', PLUGIN_NAME);
return;
}
if (!Array.isArray(config.devices)) {
log.warn('WARNING: No devices configured for %s, please add at least one device', PLUGIN_NAME);
return;
}
// abort load if device IP address are not unique
if (uniqBy(config.devices, 'ipAddress').length != config.devices.length) {
log.warn('WARNING: IP addresses not unique for %s. Please ensure you use a unique IP address per device', PLUGIN_NAME);
return;
}
this.log = log;
this.config = config;
this.api = api;
this.devices = [];
this.debugLevel = this.config.debugLevel || 0;
// show some useful version info
this.log.info('%s v%s, node %s, homebridge v%s', packagejson.name, packagejson.version, process.version, this.api.serverVersion)
this.api.on('didFinishLaunching', () => {
if (this.debugLevel > 0) {
this.log.warn('API event: didFinishLaunching');
}
// detect if running on development environment
// customStoragePath: 'C:\\Users\\jochen\\.homebridge'
if ( this.api.user.customStoragePath.includes( 'jochen' ) ) { PLUGIN_ENV = ' DEV' }
if (PLUGIN_ENV) { this.log.warn('%s running in %s environment with debugLevel %s', PLUGIN_NAME, PLUGIN_ENV.trim(), this.debugLevel); }
if (this.config.devices.length == 0) {
this.log.warn('No devices found in config for %s', PLUGIN_NAME)
} else {
// check all devices in config
this.log.debug('Checking devices found in config for %s', PLUGIN_NAME)
for (let i = 0, len = this.config.devices.length; i < len; i++) {
//this.log("Checking device %s %s", i, this.config.devices[i]);
this.log("Loading device %s: %s", i+1, this.config.devices[i].name, this.config.devices[i].ipAddress);
// constructor(log, config, api, parent, device, deviceIndex) {
// constructor(log, config, api, platform, device, deviceIndex, pingCommand, pingResponseOn, pingResponseOff) {
let newTvHtDevice = new samsungTvHtDevice(this.log, this.config, this.api, this, i);
this.devices.push(newTvHtDevice);
}
}
// start the regular powerStateMonitor
this.checkPowerInterval = setInterval(this.powerStateMonitor.bind(this), this.config.pingInterval * 1000 || POWER_STATE_DEFAULT_POLLING_INTERVAL_MS);
});
}
configureAccessory(platformAccessory) {
this.log.debug('configurePlatformAccessory');
}
removeAccessory(platformAccessory) {
this.log.debug('removePlatformAccessory');
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [platformAccessory]);
}
powerStateMonitor() {
// ping the devices regularly to check their power state
// need to add support for powerOnStartupTime
//this.suppressPowerStateMonitoringUntil // datetime
// for linux: pingCmd = 'ping -c 1 -w 10' + ' ' + this.config.devices[0].ipAddress;
// for win: pingCmd = 'ping -n 1 -w 10' + ' ' + this.config.devices[0].ipAddress;
// ping all devices in the config
for (let i = 0; i < this.config.devices.length; i++) {
this.devices[i].powerStateMonitorCounter++; // increment global counter by 1
let device = this.devices[i];
let logPrefix = 'powerStateMonitor(' + device.powerStateMonitorCounter + '): '; // set a log prefix for this instance of the powerStateMonitor to allow differentiation in the logs
// set a ping command
var pingCmd = this.config.pingCommand || 'ping -c 1 -w 20'; // default linux, 1 ping, 20ms wait
pingCmd = pingCmd.trim() + ' ' + this.config.devices[i].ipAddress;
this.log.debug(logPrefix + '%s pinging device with %s', device.name, pingCmd);
var self = this;
var deviceRealPowerState;
exec(pingCmd, function (error, stdout, stderr) {
self.log.debug(logPrefix + "%s ping response: %s", device.name, stdout);
self.log.debug(logPrefix + '%s powerLastKeyPress %s', device.name, device.powerLastKeyPress.toLocaleString());
var dateNow = new Date;
const secondsSinceLastPowerKeyPress = (dateNow - device.powerLastKeyPress) / 1000;
const yearsSinceLastPowerKeyPress = (dateNow.getFullYear() - device.powerLastKeyPress.getFullYear());
self.log.debug(logPrefix + '%s secondsSinceLastPowerKeyPress %s', device.name, secondsSinceLastPowerKeyPress);
self.log.debug(logPrefix + '%s yearsSinceLastPowerKeyPress %s', device.name, yearsSinceLastPowerKeyPress);
// get the current device power state from the ping results
// win10: Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
// linux: 1 packets transmitted, 0 received, 100% packet loss, time 0ms
// reworked to show 100% loss is OFF, anything else is ON
if (stdout.includes(self.config.pingResponseOff) && ((self.config.pingResponseOff || '') != '')) { // user-configred OFF response found which is not empty
self.log.debug(logPrefix + "%s is not responding to ping, power is currently OFF (using config detection)", device.name);
deviceRealPowerState = Characteristic.Active.INACTIVE;
} else if (stdout.includes('100% packet loss')) { // Linux: "1 packets transmitted, 0 received, 100% packet loss, time 0ms" detect "100% packet loss"
self.log.debug(logPrefix + "%s is not responding to ping, power is currently OFF (using Linux detection)", device.name);
deviceRealPowerState = Characteristic.Active.INACTIVE;
} else if (stdout.includes('(100% loss)')) { // Windows: "Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)", detect "(100% loss)"
self.log.debug(logPrefix + "%s is not responding to ping, power is currently OFF (using Windows detection)", device.name);
deviceRealPowerState = Characteristic.Active.INACTIVE;
} else {
// any ping where we did not have 100% loss, is considered being ON, as some packets were returned
self.log.debug(logPrefix + "%s is responding to ping, power is currently ON", device.name);
deviceRealPowerState = Characteristic.Active.ACTIVE;
//self.log.debug("powerStateMonitor: WARNING %s cannot determine power state from ping result! stdout:", device.name, stdout);
//deviceRealPowerState = device.currentPowerState; // maintain current state
}
// evaluate the real vs target power states
self.log.debug(logPrefix + "%s evaluating power state. deviceRealPowerState %s, currentPowerState %s, targetPowerState %s", device.name, deviceRealPowerState, device.currentPowerState, device.targetPowerState);
if (!(deviceRealPowerState === device.currentPowerState) && (yearsSinceLastPowerKeyPress > 100)) {
// (yearsSinceLastPowerKeyPress > 100) means no HomeKit key presses were made, but a deviceRealPowerState has detected which is differen to the currentPowerState. Probably changed through a non-HomeKit method, eg physical remote control
self.log.debug(logPrefix + "%s power state change detected from device, setting currentPowerState to deviceRealPowerState %s", device.name, deviceRealPowerState);
device.targetPowerState = deviceRealPowerState;
device.currentPowerState = deviceRealPowerState;
} else if ((deviceRealPowerState != device.targetPowerState) && (yearsSinceLastPowerKeyPress < 100)) {
self.log.debug(logPrefix + "%s is currently transitioning from %s to %s. Transition time so far: %s seconds", device.name, deviceRealPowerState, device.targetPowerState, secondsSinceLastPowerKeyPress);
// change in power state was requested. yearsSinceLastPowerKeyPress helps us detect a Homebridge reboot
if ((secondsSinceLastPowerKeyPress < POWER_STATE_MAX_TRANSITION_TIME_S) && (yearsSinceLastPowerKeyPress < 100)) {
// device is currently undergoing a power state transition to the targetPowerState, set currentPowerState to targetPowerState
self.log.debug(logPrefix + "%s is still within the allowed transition time of %s seconds, setting currentPowerState to targetPowerState %s", device.name, POWER_STATE_MAX_TRANSITION_TIME_S, device.targetPowerState);
device.currentPowerState = device.targetPowerState;
} else {
// transition time has timed out, cancel the targetPowerState, reset current and target to deviceRealPowerState
self.log.debug(logPrefix + "%s transition time longer than %s seconds, transition has timed out, no power state change occured, resetting currentPowerState to %s", device.name, POWER_STATE_MAX_TRANSITION_TIME_S, deviceRealPowerState);
device.targetPowerState = deviceRealPowerState;
device.currentPowerState = deviceRealPowerState;
}
} else {
device.currentPowerState = deviceRealPowerState || device.currentPowerState; // handle null if a parse error occured
self.log.debug(logPrefix + "%s currentPowerState stays unchanged at %s", device.name, device.currentPowerState);
}
// update device status
self.log.debug(logPrefix + "%s calling device.updateDeviceState with device.currentPowerState %s", device.name, device.currentPowerState);
device.updateDeviceState(device.currentPowerState);
});
}
}
}
class samsungTvHtDevice {
// build the device. Runs once on restart
constructor(log, config, api, platform, deviceIndex) {
this.log = log;
this.api = api;
this.config = config; // the entire platform config
this.platform = platform; // the entire platform
this.deviceIndex = deviceIndex; // the current device's index
this.debugLevel = platform.debugLevel || 0; // debugLevel defaults to 0 (minimum)
this.deviceConfig = this.config.devices[deviceIndex]; // the config for the current device
this.powerStateMonitorCounter=0; // the power state monitor counter for this device
this.name = this.deviceConfig.name // device name from config
this.ipAddress = this.deviceConfig.ipAddress // device ip address from config
// setup arrays
this.inputServices = []; // loaded input services, used by the accessory, as shown in the Home app. Limited to 96
this.configuredInputs = []; // a list of inputs that have been renamed by the user. EXPERIMENTAL
this.lastRemoteKeyPressed = -1; // holds the last key pressed, -1 = no key
this.lastRemoteKeyPress0 = []; // holds the time value of the last remote button press for key index i
this.lastRemoteKeyPress1 = []; // holds the time value of the last-1 remote button press for key index i
this.lastRemoteKeyPress2 = []; // holds the time value of the last-2 remote button press for key index i
this.lastVolDownKeyPress = []; // holds the time value of the last button press for the volume down button
this.inputList = []; // holds the input list, do we really need it?
//setup variables
this.accessoryConfigured = false; // true when the accessory is configured
// initial states. Will be updated by code
this.currentPowerState; // deliberately leave at undefined to detect a reboot and inital start = Characteristic.Active.INACTIVE;
this.targetPowerState = this.currentPowerState;
this.currentInputId = NO_INPUT_ID;
this.currentMediaState = Characteristic.CurrentMediaState.STOP; // default stop
this.targetMediaState = this.currentMediaState;
this.powerLastKeyPress = new Date("1900-01-01T00:00:00Z"); // set a valid date but many years in the past
// prepare the accessory
this.prepareAccessory();
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// START of preparing accessory and services
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//Prepare accessory (runs from samsungTvHtDevice)
prepareAccessory() {
if (this.debugLevel > 0) {
this.log.warn('%s: prepareAccessory', this.name);
}
// exit immediately if already configured (runs from session watchdog)
if (this.accessoryConfigured) { return }
//this.log("prepareAccessory", this.name, PLUGIN_NAME);
//this.log("prepareAccessory this.ipAddress", this.ipAddress);
const accessoryName = this.name;
// generate a constant uuid that will never change over the life of the accessory
const uuid = UUID.generate(this.ipAddress + PLUGIN_ENV);
if (this.debugLevel > 1) {
this.log.warn('%s: prepareAccessory: UUID %s', this.name, uuid);
}
// default category is TV, allow also RECEIVER (avr)
let accessoryCategory = Categories.TELEVISION;
switch (this.deviceConfig.type) {
case "receiver":
accessoryCategory = Categories.AUDIO_RECEIVER;
break;
default:
accessoryCategory = Categories.TELEVISION;
}
this.accessory = new Accessory(accessoryName, uuid, accessoryCategory);
this.prepareAccessoryInformationService(); // service 1 of 100
this.prepareTelevisionService(); // service 2 of 100
this.prepareTelevisionSpeakerService(); // service 3 of 100
this.prepareInputSourceServices(); // service 4....100
// set displayOrder
this.televisionService.getCharacteristic(Characteristic.DisplayOrder)
.value = Buffer.from(this.displayOrder).toString('base64');
this.api.publishExternalAccessories(PLUGIN_NAME, [this.accessory]);
this.accessoryConfigured = true;
}
//Prepare AccessoryInformation service
prepareAccessoryInformationService() {
if (this.debugLevel > 0) {
this.log.warn('%s: prepareAccessoryInformationService', this.name);
}
this.accessory.removeService(this.accessory.getService(Service.AccessoryInformation));
const informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Name, this.name)
.setCharacteristic(Characteristic.Manufacturer, this.deviceConfig.manufacturer || 'Samsung')
.setCharacteristic(Characteristic.Model, this.deviceConfig.modelName || PLATFORM_NAME)
.setCharacteristic(Characteristic.SerialNumber, this.deviceConfig.serialNumber || 'unknown')
.setCharacteristic(Characteristic.FirmwareRevision, this.deviceConfig.firmwareRevision || PLUGIN_VERSION) // must be numeric. Non-numeric values are not displayed
this.accessory.addService(informationService);
}
//Prepare Television service
prepareTelevisionService() {
if (this.debugLevel > 0) {
this.log.warn('%s: prepareTelevisionService', this.name);
}
//this.televisionService = new Service.Television(this.name, 'televisionService');
this.televisionService = new Service.Television(null, 'televisionService');
this.televisionService
.setCharacteristic(Characteristic.ConfiguredName, this.name)
.setCharacteristic(Characteristic.SleepDiscoveryMode, Characteristic.SleepDiscoveryMode.ALWAYS_DISCOVERABLE);
/* // not yet working
this.televisionService.getCharacteristic(Characteristic.ConfiguredName)
.on('get', this.getDeviceName.bind(this))
.on('set', (newName, callback) => { this.setDeviceName(newName, callback); });
*/
this.televisionService.getCharacteristic(Characteristic.Active)
.on('get', this.getPower.bind(this))
.on('set', this.setPower.bind(this));
this.televisionService.getCharacteristic(Characteristic.ActiveIdentifier)
.on('get', this.getInput.bind(this))
.on('set', (newInputIdentifier, callback) => { this.setInput(this.inputList[newInputIdentifier], callback); });
this.televisionService.getCharacteristic(Characteristic.RemoteKey)
.on('set', this.setRemoteKey.bind(this));
this.televisionService.getCharacteristic(Characteristic.PowerModeSelection)
.on('set', this.setPowerModeSelection.bind(this));
// Experimenting with removing some unwanted optional characteristics
// removeCharacteristic(accessory.service.getCharacteristic(Characteristic.ABC))
// this.televisionService
// .removeCharacteristic(this.televisionService.getCharacteristic(Characteristic.CurrentMediaState))
// .removeCharacteristic(this.televisionService.getCharacteristic(Characteristic.TargetMediaState))
//;
//this.televisionService.setCharacteristic(Characteristic.IsConfigured, configState)
/*
this.log('this.televisionService')
this.log(this.televisionService)
this.log('this.televisionService.Brightness.Props')
//this.log(this.televisionService.Brightness.Props)
this.log('this.televisionService Brightness')
this.log(this.televisionService.getCharacteristic(Characteristic.Brightness))
// Hidden ”hd” This characteristic is hidden from the user
this.televisionService.getCharacteristic(Characteristic.CurrentMediaState)
.setProps({
perms: [Characteristic.Perms.HIDDEN]
});
this.log('this.televisionService CurrentMediaState')
this.log(this.televisionService.getCharacteristic(Characteristic.CurrentMediaState))
*/
this.accessory.addService(this.televisionService);
}
//Prepare TelevisionSpeaker service
prepareTelevisionSpeakerService() {
if (this.debugLevel > 0) {
this.log.warn('%s: prepareTelevisionSpeakerService', this.name);
}
this.speakerService = new Service.TelevisionSpeaker(this.name + ' Speaker', 'speakerService');
this.speakerService
.setCharacteristic(Characteristic.Active, Characteristic.Active.ACTIVE)
.setCharacteristic(Characteristic.VolumeControlType, Characteristic.VolumeControlType.RELATIVE);
this.speakerService.getCharacteristic(Characteristic.VolumeSelector) // the volume selector allows the iOS device keys to be used to change volume
.on('set', (direction, callback) => { this.setVolume(direction, callback); });
this.speakerService.getCharacteristic(Characteristic.Volume)
.on('set', this.setVolume.bind(this));
this.speakerService.getCharacteristic(Characteristic.Mute)
.on('set', this.setMute.bind(this));
this.accessory.addService(this.speakerService);
this.televisionService.addLinkedService(this.speakerService);
}
//Prepare InputSource services
prepareInputSourceServices() {
// This is the input list, each input is a service, max 100 services less the services created so far
// on the samsung devices, the
// AVR: HDMI1, HDMI2, Analog
if (this.debugLevel > 1) {
this.log.warn('%s: prepareInputSourceServices', this.name);
}
// add dummy entry at index 0 for the inputList
this.inputList.push({inputId: '0', inputName: 'Dummy'});
this.displayOrder = [];
// For Release 1.0, I'll only support the source by sending the SOURCE key, which just goes to next source
// so disable HDMI 2 and Analog AUX. these need HDMI CEC support.
// see https://developers.homebridge.io/#/service/InputSource
// see https://developers.homebridge.io/#/characteristic/InputSourceType
// see https://developers.homebridge.io/#/characteristic/InputDeviceType
// HomeKit gets upset when the number of inputs changes. So configure 20 always, set conf and vis states if a deviceconfig exists
//this.log.warn('%s: prepareInputSourceServices inputs',this.name, this.deviceConfig.inputs);
if (this.deviceConfig.inputs){
for (let i = 0; i < 20; i++) {
this.log.debug('%s: prepareInputSourceServices loading input %s',this.name,i+1,this.deviceConfig.inputs[i] || 'no config found');
// show only if the deviceConfig setting exists
var configState = Characteristic.IsConfigured.NOT_CONFIGURED;
var visState = Characteristic.CurrentVisibilityState.HIDDEN;
if (this.deviceConfig.inputs[i]) {
configState = Characteristic.IsConfigured.CONFIGURED;
visState = Characteristic.CurrentVisibilityState.SHOWN;
}
let inputService = new Service.InputSource(1, "input_" + (i+1).toString() );
inputService
.setCharacteristic(Characteristic.Identifier, i+1)
.setCharacteristic(Characteristic.ConfiguredName, (this.deviceConfig.inputs[i] || {}).inputName || 'input_' + (i+1).toString())
.setCharacteristic(Characteristic.InputSourceType, (this.deviceConfig.inputs[i] || {}).inputSourceType || Characteristic.InputSourceType.HDMI)
.setCharacteristic(Characteristic.InputDeviceType, (this.deviceConfig.inputs[i] || {}).inputDeviceType || Characteristic.InputDeviceType.TV)
.setCharacteristic(Characteristic.IsConfigured, configState)
.setCharacteristic(Characteristic.CurrentVisibilityState, visState)
.setCharacteristic(Characteristic.TargetVisibilityState, visState);
this.inputServices.push(inputService);
this.accessory.addService(inputService);
this.televisionService.addLinkedService(inputService);
this.inputList.push({inputId: inputService.getCharacteristic(Characteristic.Identifier), inputName: inputService.getCharacteristic(Characteristic.ConfiguredName)});
// add DisplayOrder, see :
// https://github.com/homebridge/HAP-NodeJS/issues/644
// https://github.com/ebaauw/homebridge-zp/blob/master/lib/ZpService.js line 916: this.displayOrder.push(0x01, 0x04, identifier & 0xff, 0x00, 0x00, 0x00)
//this.displayOrder.push(0x01, 0x04, i & 0xff, 0x00, 0x00, 0x00);
// type len inputId empty empty empty
//this.displayOrder.push(0x01, 0x04, i, 0x00, 0x00, 0x00);
// inputId is the inputIdentifier (not the index), starting index 0 = identifier 1
// types:
// 0x00 end of TLV item
// 0x01 identifier...new TLV item for displayOrder
// length: Number of following bytes, excluding type and len fields
// value: A number of <len> bytes. Can be mepty if length=0
// 0x01 0x01 xx is a valid TLV8 as it contains only 1 data byte.
// the data must be a single 8-bit byte, hence the logical AND with 0xff
this.displayOrder.push(0x01, 0x01, i & 0xff); // 0x01 0x01 0xXX
}
// close off the TLV8 by sending 0x00 0x00
this.displayOrder.push(0x00, 0x00); // close off the displayorder array with 0x00 0x00
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// END of preparing accessory and services
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// START state handler
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// send a remote control keypress to the device
async sendKey(keySequence) {
if (this.debugLevel > 0) {
this.log.warn('%s: sendKey: keySequence %s', this.name, keySequence);
}
// make a new remote
const remote = new SamsungRemote({
ip: this.deviceConfig.ipAddress
});
let keyArray = keySequence.trim().split(' ');
if (keyArray.length > 1) { this.log('%s: sendKey: processing keySequence', this.name, keySequence); }
// supported key1 key2 key3 wait() wait(100)
for (let i = 0; i < keyArray.length; i++) {
const keyName = keyArray[i].trim();
this.log.debug('%s: sendKey: processing key %s of %s: %s', this.name, i+1, keyArray.length, keyName);
// if a wait appears, use it
let waitDelay; // default
if (keyName.toLowerCase().startsWith('wait(')) {
this.log.debug('%s: sendKey: reading delay from %s', this.name, keyName);
waitDelay = keyName.toLowerCase().replace('wait(', '').replace(')','');
if (waitDelay == ''){ waitDelay = 100; } // default 100ms
this.log.debug('%s: sendKey: delay read as %s', this.name, waitDelay);
}
// else if not first key and last key was not wait, and next key is not wait, then set a default delay of 100 ms
else if (i>0 && i<keyArray.length-1 && !(keyArray[i-1] || '').toLowerCase().startsWith('wait(') && !(keyArray[i+1] || '').toLowerCase().startsWith('wait(')) {
this.log.debug('%s: sendKey: not first key and neiher previous key %s nor next key %s is wait(). Setting default wait of 100 ms', this.name, keyArray[i-1], keyArray[i+1]);
waitDelay = 100;
}
// add a wait if waitDelay is defined
if (waitDelay) {
if (this.debugLevel > 0) {this.log('%s: sendKey: wait %s ms', this.name, waitDelay)};
await waitprom(waitDelay);
this.log.debug('%s: sendKey: wait %s done', this.name, waitDelay);
}
// send the key if not a wait()
if (!keyName.toLowerCase().startsWith('wait(')) {
if (this.debugLevel > 0) {this.log('%s: sendKey: send %s', this.name, keyName)};
remote.send(keyName, (err) => {
if (err && (err || '' != "Timeout")) {
// Timeout ignore, this is normal with SamsungRemote, some keys just do get a response from the TV / AVR
this.log.warn("%s: sendKey: %s error %s", this.name, keyName, err);
} else {
this.log.debug('%s: sendKey: send %s done', this.name, keyName);
}
});
}
} // end for loop
}
// get the device UI status
// incomplete, to be completed if I can ever figure out how
getUiStatus() {
if (this.debugLevel > 1) {
this.log.warn('getUiStatus');
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// END state handler
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// START regular device update polling functions
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// update the device state (async)
async updateDeviceState(powerState, mediaState, inputId, callback) {
// doesn't get the data direct from the device, but rather: gets it from the variables
if (this.debugLevel > 2) {
this.log.warn('%s: updateDeviceState: powerState %s, mediaState %s, inputId %s', this.name, powerState, mediaState, inputId);
}
// grab the input variables
if (powerState != null) { this.currentPowerState = powerState }
if (mediaState != null) { this.currentMediaState = mediaState }
if (inputId != null) { this.currentInputId = inputId }
// debugging, helps a lot to see InputName
if (this.debugLevel > 2) {
//let currentInputName; // let is scopt to the current {} block
let curInput = this.inputList.find(Input => Input.inputId === this.currentInputId);
//if (curInput) { currentInputName = curInput.InputName; }
this.log.warn('%s: updateDeviceState: currentPowerState %s, currentMediaState %s [%s], currentInputId %s [%s]',
this.name,
this.currentPowerState,
this.currentMediaState, mediaStateName[this.currentMediaState],
this.currentInputId, (curInput || {}).InputName
);
}
// change only if configured, and update only if changed
if (this.televisionService) {
// set power state if changed
const previousPowerState = this.televisionService.getCharacteristic(Characteristic.Active).value;
const currentPowerState = this.currentPowerState || Characteristic.Active.INACTIVE; // ensure never null
this.log.debug('%s: updateDeviceState: previousPowerState %s, currentPowerState %s',this.name, previousPowerState, currentPowerState);
if (previousPowerState !== currentPowerState) {
this.log('%s: Power changed from %s %s to %s %s',
this.name,
previousPowerState, powerStateName[previousPowerState],
currentPowerState, powerStateName[currentPowerState]);
this.televisionService.getCharacteristic(Characteristic.Active).updateValue(currentPowerState);
} else {
this.log.debug('%s: updateDeviceState: no change to current power, Characteristic.Active not updated',this.name);
}
// set active input if changed
var oldActiveIdentifier = this.televisionService.getCharacteristic(Characteristic.ActiveIdentifier).value;
//var currentActiveIdentifier = this.inputList.findIndex(input => input.inputId === currentInputId);
var currentActiveIdentifier = NO_INPUT_ID; // fixed at NO_INPUT_ID to clear the Tile
if (currentActiveIdentifier == -1) { currentActiveIdentifier = NO_INPUT_ID } // if nothing found, set to NO_INPUT to clear the name from the Home app tile
if (oldActiveIdentifier !== currentActiveIdentifier) {
// get names from loaded input list. Using SOURCE button on the remote rolls around the input list
var oldName, newName;
if (oldActiveIdentifier == NO_INPUT_ID) {
oldName = 'UNKNOWN';
}
if (currentActiveIdentifier == NO_INPUT_ID) {
newName = 'UNKNOWN';
}
// cannot show current input as it is unknown, so log at debug level only, as inputs often hold remote keys
this.log.debug('%s: Input changed from %s %s to %s %s',
this.name,
oldActiveIdentifier + 1, oldName,
currentActiveIdentifier + 1, newName);
this.televisionService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(currentActiveIdentifier);
} else {
this.log.debug('%s: updateDeviceState: no change to current input, Characteristic.ActiveIdentifier not updated',this.name);
}
// set current media state if changed
var oldMediaState = this.televisionService.getCharacteristic(Characteristic.CurrentMediaState).value;
if (oldMediaState !== this.currentMediaState) {
this.log('%s: Media state changed from %s %s to %s %s',
this.name,
oldMediaState, mediaStateName[oldMediaState],
this.currentMediaState, mediaStateName[this.currentMediaState]);
this.televisionService.getCharacteristic(Characteristic.CurrentMediaState).updateValue(this.currentMediaState);
}
}
return null;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// END regular device update polling functions
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// START of accessory get/set state handlers
// HomeKit polls for status regularly at intervals from 2min to 15min
//+++++++++++++++++++++++++++++++++++++++++++++++++++++
// get power state
async getPower(callback) {
// fired when the user clicks away from the Remote Control, regardless of which TV was selected
// fired when HomeKit wants to refresh the TV tile in HomeKit. Refresh occurs when tile is displayed.
// currentPowerState is updated by the polling mechanisn
//this.log('getPowerState current power state:', currentPowerState);
if (this.debugLevel > 1) {
this.log.warn('%s: getPower returning %s [%s]', this.name, this.currentPowerState || Characteristic.Active.INACTIVE, powerStateName[this.currentPowerState || Characteristic.Active.INACTIVE]);
}
callback(null, this.currentPowerState || Characteristic.Active.INACTIVE); // return current state: 0=off, 1=on. Default to OFF if null.
}
// set power state
async setPower(targetPowerState, callback) {
// fired when the user clicks the power button in the TV accessory in HomeKit
// fired when the user clicks the TV tile in HomeKit
// fired when the first key is pressed after opening the Remote Control
// wantedPowerState is the wanted power state: 0=off, 1=on
if (this.debugLevel > 1) { this.log.warn('%s: setPower: targetPowerState:', this.name, targetPowerState, powerStateName[targetPowerState]); }
this.targetPowerState = targetPowerState;
// only take action if the target state is different to the current state
if (this.currentPowerState != this.targetPowerState) {
// check what we want to do
this.powerLastKeyPress = new Date();
this.log.debug("%s: setPower: reset powerLastKeyPress to %s", this.name, this.powerLastKeyPress.toLocaleString());
this.currentPowerState = this.targetPowerState; // to ensure HomeKit gets the correct state at next poll, regardless
if (this.targetPowerState == Characteristic.Active.INACTIVE){
// we want to turn OFF, then we can turn it off with a sendKey
// avr: BD_KEY_POWER, tv: KEY_POWER
if (this.deviceConfig.powerOffButton) {this.sendKey(this.deviceConfig.powerOffButton)};
} else {
// we want to turn ON, can turn on only via HDMI-CEC
this.log("%s: setPower: powerOnCommand: %s", this.name, this.deviceConfig.powerOnCommand);
var self = this;
if (this.deviceConfig.powerOnCommand){
exec(this.deviceConfig.powerOnCommand, function (error, stdout, stderr) {
if (stderr){self.log.warn("%s: setPower: powerOnCommand: %s", self.name, stderr);} // show any error if any generated
if (stdout){self.log.debug("%s: setPower: powerOnCommand: %s", self.name, stdout);} // show any stdOut in debug mode
});
}
}
} else {
// if current is already same as target
this.log.debug("%s: Current power state is already %s [%s], doing nothing", this.name, this.currentPowerState, powerStateName[this.currentPowerState]);
}
callback();
}
// set mute state
async setMute(muteState, callbackMute) {
// sends the mute command
// works for TVs that accept a mute toggle command
if (this.debugLevel > 0) {
this.log.warn('%s: setMute: muteState:', this.name, muteState);
}
if (callbackMute && typeof(callbackMute) === 'function') {
callbackMute();
}
// mute state is a boolean, either true or false
// const NOT_MUTED = 0, MUTED = 1;
this.log('%s: Set mute: %s', this.name, (muteState) ? 'Muted' : 'Not muted');
// send only if a keycode exists
const keyCode = this.deviceConfig.muteButton;
if (keyCode.length > 0) {
this.sendKey(keyCode);
}
}
// set volume
async setVolume(volumeSelectorValue, callback) {
// set the volume of the TV using bash scripts
// so volume must be handled over a different method
// here we send execute a bash command on the raspberry pi using the samsungctl command
// to control the authors samsung stereo at 192.168.0.152
if (this.debugLevel > 0) { this.log.warn('%s: setVolume: volumeSelectorValue:', this.name, volumeSelectorValue); }
callback(null); // for rapid response
// volumeSelectorValue: only 2 values possible: INCREMENT: 0, DECREMENT: 1,
this.log.debug('%s: setVolume: Set volume: %s', (volumeSelectorValue === Characteristic.VolumeSelector.DECREMENT) ? 'Down' : 'Up');
// triple rapid VolDown presses triggers setMute
var tripleVolDownPress = 10000; // default high value to prevent a tripleVolDown detection when no triple key pressed
if (volumeSelectorValue === Characteristic.VolumeSelector.DECREMENT) {
this.lastVolDownKeyPress[2] = this.lastVolDownKeyPress[1] || 0;
this.lastVolDownKeyPress[1] = this.lastVolDownKeyPress[0] || 0;
this.lastVolDownKeyPress[0] = Date.now();
tripleVolDownPress = this.lastVolDownKeyPress[0] - this.lastVolDownKeyPress[2];
// check time difference between current keyPress and 2 keyPresses ago
this.log.debug('%s: setVolume: Timediff between lastVolDownKeyPress[0] now and lastVolDownKeyPress[2]: %s ms', this.name, this.lastVolDownKeyPress[0] - this.lastVolDownKeyPress[2]);
}
// check for triple press of volDown, send setmute if tripleVolDownPress less than 1000ms
var keyCode;
if (tripleVolDownPress < 1000) {
this.log.debug('%s: Triple-press of volume down detected', this.name);
keyCode = this.deviceConfig.voldownButtonTriplePress;
} else if (volumeSelectorValue === Characteristic.VolumeSelector.INCREMENT) {
keyCode = this.deviceConfig.volupButton;
} else if (volumeSelectorValue === Characteristic.VolumeSelector.DECREMENT) {
keyCode = this.deviceConfig.voldownButton;
}
// send only if a keycode exists
if ((keyCode || {}).length > 0) {
this.sendKey(keyCode);
}
}
// get input
async getInput(callback) {
// fired when the user clicks away from the iOS Device TV Remote Control, regardless of which TV was selected
// fired when the icon is clicked in HomeKit and HomeKit requests a refresh
// currentInputId is updated by the polling mechanisn
// must return a valid index, and must never return null
// find the currentInputId in the inputs and return the currentActiveInput once found
// this allows HomeKit to show the selected current input
/*
var currentInputName = NO_INPUT_NAME;
var currentActiveInput = this.inputServices.findIndex(input => input.inputId === currentInputId);
if (currentActiveInput == -1) { currentActiveInput = NO_INPUT_ID } // if nothing found, set to NO_INPUT_ID to clear the name from the Home app tile
if ((currentActiveInput > -1) && (currentActiveInput != NO_INPUT_ID)) {
currentInputName = this.inputServices[currentActiveInput].getCharacteristic(Characteristic.ConfiguredName).value;
}
*/
// return the fixed no input always. This prevents the input name from being displayed on the home tile
const currentActiveInput = NO_INPUT_ID;
const currentInputName = NO_INPUT_NAME;
if (this.debugLevel > 0) {
this.log.warn('%s: getInput returning input %s [%s]', this.name, currentActiveInput, currentInputName);
}
callback(null, currentActiveInput);
}
// set input
async setInput(input, callback) {
if ((this.debugLevel > 0) & (input !== undefined)) {
this.log.warn('%s: setInput input:', this.name,input.inputId.value, input.inputName.value, this.deviceConfig.inputs[input.inputId.value-1].inputKeyCode);
}
//one day I'll implement the HDMI CEC input control, then I'll need these functions:
/*
var currentInputName = 'UNKNOWN';
var foundIndex = this.inputList.findIndex(input => input.inputId === currentInputId);
if (foundIndex > -1) { currentInputName = this.inputList[foundIndex].InputName; }
this.log('Change input from %s %s to %s %s', currentInputId, currentInputName, input.inputId, input.InputName);
this.switchInput(input.inputId);
*/
// get keycode only if we have an input (sometimes not defined)
var keyCode = '';
if (input !== undefined) {
keyCode = this.deviceConfig.inputs[input.inputId.value-1].inputKeyCode;
}
// send only if a keycode exists
if ((keyCode || {}).length > 0) {
this.sendKey(keyCode);
}
// immediately reset the input back to nothing to clear any scenes and clear the tile display
if (this.televisionService.getCharacteristic(Characteristic.ActiveIdentifier).value != NO_INPUT_ID) {
this.log.warn('%s: setInput setting ActiveIdentifier to NO_INPUT_ID %s :', this.name, NO_INPUT_ID);
this.televisionService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(NO_INPUT_ID);
} else {
this.log.debug('%s: setInput: ActiveIdentifier OK, no need to change', this.name);
}
// start an async service to reset after 500ms
//this.log('processing wait of %s ms', delay);
//await waitprom(500);
//this.log('wait done');
callback();
}
// set input name
async setInputName(inputName, callback) {
// fired by the user changing an input name in Home app accessory setup
if (this.debugLevel > 0) {
this.log.warn('%s: setInputName inputName:', this.name, inputName);
}
callback();
};
// set power mode selection (View TV Settings menu option)
async setPowerModeSelection(state, callback) {
// fired by the View TV Settings command in the HomeKit TV accessory Settings
if (this.debugLevel > 0) {
this.log.warn('%s: setPowerModeSelection state:', this.name, state);
}
this.log('%s: Menu command: View TV Settings', this.name);
// only send the keys if the power is on
if (this.currentPowerState == Characteristic.Active.ACTIVE) {
this.sendKey(this.deviceConfig.viewTvSettingsCommand || 'KEY_MENU');
} else {
this.log('%s: Power is Off. View TV Settings command not sent', this.name);
}
callback();
}
// get current media state
async getCurrentMediaState(callback) {
// fired by ??
// cannot be controlled by Apple Home app, but could be controlled by other HomeKit apps
if (this.debugLevel > 0) {
this.log.warn('%s: getCurrentMediaState returning %s [%s]', this.name, this.currentMediaState, mediaStateName[this.currentMediaState]);
}
callback(null, this.currentMediaState);
}
// get target media state
async getTargetMediaState(callback) {
// fired by ??
// cannot be controlled by Apple Home app, but could be controlled by other HomeKit apps
// must never return null, so send STOP as default value
if (this.debugLevel > 0) {
this.log.warn('%s: getTargetMediaState returning %s [%s]', this.name, this.targetMediaState, mediaStateName[this.targetMediaState]);
}
callback(null, this.currentMediaState);
}
// set target media state
async setTargetMediaState(targetState, callback) {
// fired by ??
// cannot be controlled by Apple Home app, but could be controlled by other HomeKit apps
if (this.debugLevel > 1) { this.log.warn('%s: setTargetMediaState this.targetMediaState:',this.name, targetState, mediaStateName[targetState]); }
callback(null); // for rapid response
switch (targetState) {
case Characteristic.TargetMediaState.PLAY:
this.log('%s: setTargetMediaState: Set media to PLAY for', this.name, this.currentInputId);
this.setMediaState(this.currentInputId, 1)
break;
case Characteristic.TargetMediaState.PAUSE:
this.log('%s: setTargetMediaState: Set media to PAUSE for', this.name, this.currentInputId);
this.setMediaState(this.currentInputId, 0)
break;
case Characteristic.TargetMediaState.STOP:
this.log('%s: setTargetMediaState: Set media to STOP for', this.name, this.currentInputId);
this.setMediaState(this.currentInputId, 0)
break;
}
}
// get display order
async getDisplayOrder(callback) {
// fired when the user clicks away from the iOS Device TV Remote Control, regardless of which TV was selected
// fired when the icon is clicked in HomeKit and HomeKit requests a refresh
// log the display order
let dispOrder = this.televisionService.getCharacteristic(Characteristic.DisplayOrder).value;
if (this.config.debugLevel > 1) { this.log.warn("%s: getDisplayOrder returning '%s'", this.name, dispOrder); }
callback(null, dispOrder);
}
// set display order
async setDisplayOrder(displayOrder, callback) {
// fired when the user clicks away from the iOS Device TV Remote Control, regardless of which TV was selected
// fired when the icon is clicked in HomeKit and HomeKit requests a refresh
if (this.config.debugLevel > 1) { this.log.warn('%s: setDisplayOrder displayOrder',this.name, displayOrder); }
callback();
}
// set remote key
async setRemoteKey(remoteKey, callback) {
if (this.config.debugLevel > 1) { this.log.warn('%s: setRemoteKey: remoteKey:', this.name, remoteKey); }
callback(); // for rapid response
// remoteKey is the key pressed on the Apple TV Remote in the Control Center
// keys 0...15 exist, but keys 12, 13 & 14 are not defined by Apple
// ------------- double and triple press function ---------------
// triple key presses triggers a second layer function
var tripleVolDownPress = 100000; // default high value to prevent a tripleVolDown detection when no triple key pressed
var lastKeyPressTime = this.lastRemoteKeyPress0[remoteKey] || 0; // find the time the current key was last pressed
this.log.debug("%s: setRemoteKey: remoteKey %s, lastKeyPressTime %s",this.name, remoteKey, lastKeyPressTime);
// bump the array up one slot
/*
this.log("Shifting the array up one, and storing current time in index 0");