-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.js
1041 lines (958 loc) · 46 KB
/
main.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';
/**
*
* cec2 adapter
*
* Created with @iobroker/create-adapter v2.5.0
*
* //native parameters will be in adapter.config
*
* Structure:
* create a "device" for every physical address we encounter.
* set name to OSD Name -> probably clean up old device if OSD Name != new OSD Name
* for device create states:
* * power
* * activeSource true/false (must set to false, if somebody else gets active.
* * vendorId
* * device class (device from logical address?)
* * lastKnownLogicalAddress
* * ...
* * some Information what works and what not? (like capabilities?)
* * some things dependent on device class
* for device create folder(s):
* * remote buttons -> with buttons for all possible remote buttons to be clicked.
* * poll -> poll buttons for some states
*/
//TODO:
// - add user control as states in device (sub folder)
// - could also need a state with button press length
// - testing!!!
// - especially setting stuff, everything besides on off needs testing, i.e.:
// activeSource (on AND off!),
// recording (do we have a device that can record at all??),
// deck (what can I control with this?),
// tuner (can I control TV tuner with that?),
// menu (can I open menu with that? On TV? On FireTV?),
// - add more specific polling, i.e. ask audio device for audio status and tuner maybe?
// - should we add parameter sub folder and allow polling of single states?
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
/**
* @typedef stateDefinition - imported type..
* @type {import('./lib/stateDefinitions').stateDefinition}
*/
//imports:
const CEC = require('./lib/cec-constants');
const CECMonitor = require('./lib/cec-monitor');
const fs = require('fs').promises;
const fsConstants = require('fs').constants;
const stateDefinitions = /** @type {Record<string, stateDefinition>} */ (require('./lib/stateDefinitions'));
/**
* Remove forbidden characters from names so I can use them as ID.
* @type {RegExp}
*/
const forbiddenCharacters = /[\][*,;'"`<>\\\s?]/g;
/**
* Translate Event IDs to stateDefinitions.
* @type {Record<number|string, stateDefinition>}
*/
const eventToStateDefinition = {
0: stateDefinitions.active, //0 === polling.
'ACTIVE_SOURCE': stateDefinitions.activeSource,
'INACTIVE_SOURCE': stateDefinitions.activeSource,
//'ROUTING_CHANGE': stateDefinitions.route,
//'ROUTING_INFORMATION': stateDefinitions.routingInfo,
//'SET_MENU_LANGUAGE': stateDefinitions.language,
'RECORD_STATUS': stateDefinitions.recording,
'CEC_VERSION': stateDefinitions.cecVersion,
'GET_CEC_VERSION': stateDefinitions.maxCecVersionSupported,
'REPORT_PHYSICAL_ADDRESS': stateDefinitions.physicalAddress,
'DECK_STATUS': stateDefinitions.deck,
'TUNER_DEVICE_STATUS': stateDefinitions.tuner,
'DEVICE_VENDOR_ID': stateDefinitions.vendor,
'SET_OSD_NAME': stateDefinitions.name,
'MENU_STATUS': stateDefinitions.menuStatus,
'REPORT_POWER_STATUS': stateDefinitions.powerState,
'POLLING_MESSAGE': stateDefinitions.active,
'REPORT_AUDIO_STATUS': stateDefinitions.volume,
'SYSTEM_AUDIO_MODE_STATUS': stateDefinitions.systemAudio,
'SET_SYSTEM_AUDIO_MODE': stateDefinitions.systemAudio,
'REPORT_ARC_STARTED': stateDefinitions.arc,
'REPORT_ARC_ENDED': stateDefinitions.arc
};
/**
* Build ID from device and stateDefinition, i.e. needs to be in device folder and maybe also poll sub folder.
* @param {cecDevice|string} device - device
* @param {stateDefinition} stateDef - state definition of state
* @param {boolean} [poll] - true if in polling folder.
* @returns {string}
*/
function buildId(device, stateDef, poll = false) {
let name;
if (typeof device === 'string') {
name = device;
} else {
name = device.name;
}
if (typeof stateDef === 'string') {
stateDef = eventToStateDefinition[stateDef];
}
return name + '.' + (stateDef.idPrefix ? stateDef.idPrefix + '.' : '') + (poll ? 'poll.' : '') + stateDef.name;
}
/**
* Cleanup name to create ID from it. Also contains hack for FireTV devices.
* @param {string} name
* @returns {string}
*/
function cleanUpName(name) {
//hack, somehow FireTV reports different name, when off...
if (name === 'AFTR') {
return 'Amazon_FireTV';
}
let newName = name.replace(/ /g, '_');
newName = newName.replace(forbiddenCharacters, '');
return newName;
}
/**
* Get device part of ioBroker Id
* @param {string} id
* @returns {string}
*/
function getDeviceIdFromId(id) {
const parts = id.split('.');
return parts[2]; //0 == adapter, 1 == instance -> return 2.
}
/**
* Returns state part of ioBroker id (in device or poll folder)
* @param {string} id
* @returns {string}
*/
function getStateFromId(id) {
return id.substring(id.lastIndexOf('.') + 1);
}
/**
* Get a stateDefinition from ioBroker ID
* @param {string} id
* @returns {stateDefinition}
* @throws error if no stateDefinition found for ID (should never happen!)
*/
function stateDefinitionFromId(id) {
const stateName = getStateFromId(id);
for (const key of Object.keys(stateDefinitions)) {
/** @type {stateDefinition} */
const definition = stateDefinitions[key];
if (definition.name === stateName) {
return definition;
}
}
throw new Error('Could not find stateDefinition for ' + id);
}
/**
* @typedef cecDevice
* @type {object}
* @property {Array<string>} createdStates states created for this device
* @property {string} name name of device - cleaned up to be ID
* @property {number} logicalAddress logicalAddress on bus. Negative for invalid.
* @property {string} logicalAddressHex Hex version of logicalAddress
* @property {string} [physicalAddress] Physical Address of device in 0.0.0.0 format
* @property {number} [lastGetName] last time we asked for a name.
* @property {number} [getNameTries] how often we have tried to get a name.
* @property {number} [lastGetPhysAddr] last time we asked for a physical address
* @property {number} [getPhysAddrTries] how often we have tried to get physical address
* @property {boolean} [physicalAddressReallyChanged] true if physicalAddress really changed, i.e. device answered and name differs.
* @property {Record<String, boolean>} didPoll true if device did just poll this state ref so next update will be forced to iobroker.
*
* @property {boolean} [active] active state value
* @property {number} [lastSeen] last seen since value
* @property {boolean} [activeSource] activeSource state value
* @property {number} [volume] volume (only on global device)
* @property {boolean} [volumeUp] volumeUp state (only on global device)
* @property {boolean} [volumeDown] volumeDown state (only on global device)
* @property {boolean} [mute] mute state (only on global device)
* @property {boolean} [arc] arc state (only on global device)
* @property {boolean} [systemAudio] systemAudio state (only on global device)
* @property {Array<cecDevice>} [devices] Array of all devices (only on global device?)
* @property {number} [currentButtonPressTime] Time in milliseconds for the next button press to wait.
* @property {number} maxCECVersionSupported It seems Version 1.4 is not well-supported, yet. Try to emulate lower versions here. Number equals number in constants tried.
* @property {boolean} [tryingMaxCECVersion] are we currently trying max cec version?
*
* @property {boolean} created if device was created in ioBroker or not.
* @property {boolean} ignored if device is ignored (because no name & config setting)
*/
class CEC2 extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'cec2',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
// this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
this.cec = {};
/** @type {Record<string, NodeJS.Timeout>} */
this.timeouts = {};
/** @type {Record<number, cecDevice>} */
this.logicalAddressToDevice = {};
/** @type {Array<cecDevice>} */
this.devices = [];
/** @type {cecDevice} */
this.globalDevice = {
name: 'Global',
logicalAddress: CEC.LogicalAddress.BROADCAST,
get logicalAddressHex() { return Number(this.logicalAddress).toString(16); },
volume: 0,
volumeUp: false,
volumeDown: false,
mute: false,
arc: false,
systemAudio: false,
devices: this.devices,
created: true,
ignored: false,
createdStates: [],
didPoll: {},
maxCECVersionSupported: CEC.CECVersion.UNKNOWN
};
this.devices.push(this.globalDevice);
}
/**
* Poll PowerStates of cec devices (currently only TV is polled -> too much polling seems no good idea).
* @returns {Promise<void>}
*/
async pollPowerStates() {
if (this.timeouts.pollPowerStates) {
clearTimeout(this.timeouts.pollPowerStates); //prevent multiple executions.
}
try {
/** @type {event} */
const status = await this.cec.sendCommand(null, CEC.LogicalAddress.TV, CEC.Opcode.GIVE_DEVICE_POWER_STATUS, CECMonitor.EVENTS.REPORT_POWER_STATUS);
if (status && status.data) {
this.log.debug('TV Power is ' + status.data.str);
}
} catch (e) {
this.log.debug('TV did not answer to powerRequest: ' + e + ' - ' + e.stack);
}
this.timeouts.pollPowerStates = setTimeout(() => this.pollPowerStates(), this.config.pollInterval || 30000);
}
/**
* create a state in device based on state definition and set value.
* @param {cecDevice} device
* @param {stateDefinition} stateDefinition
* @returns {Promise<void>}
*/
async createStateInDevice(device, stateDefinition) {
if (device.createdStates.find(s => s === (stateDefinition.key ? stateDefinition.key : stateDefinition.name))) {
this.log.debug('State ' + stateDefinition.name + ' already created in ' + device.name);
return;
}
let states = undefined;
if (stateDefinition.valueList) {
states = {};
Object.keys(stateDefinition.valueList).forEach(key => {
if (stateDefinition.valueList && stateDefinition.valueList[key]) {
states[stateDefinition.valueList[key]] = key;
}
});
}
const id = buildId(device, stateDefinition);
if (id.includes('undefined')) {
this.log.error('Creating state undefined: ' + JSON.stringify(stateDefinition) + ' in device' + JSON.stringify(device) + ' id ' + id);
throw new Error('State undefined: ' + id);
}
await this.setObjectNotExistsAsync(id, {
type: 'state',
common: {
type: stateDefinition.type,
desc: stateDefinition.desc,
name: stateDefinition.name,
read: stateDefinition.read === undefined ? true : stateDefinition.read,
write: stateDefinition.write,
role: stateDefinition.role,
states: states
},
native: { def: stateDefinition.key || stateDefinition.name }
});
device.createdStates.push(stateDefinition.name);
//don't set val here, will set all values when adapter start. We do not really want that. And we do not need that here, do we?
//await this.setStateChangedAsync(id, val, true);
//create poll states:
if (stateDefinition.pollOpCode) {
const id = buildId(device, stateDefinition, true);
await this.setObjectNotExistsAsync(id, {
type: 'state',
common: {
type: 'boolean',
desc: 'poll ' + stateDefinition.name,
name: 'poll ' + stateDefinition.name,
role: 'button',
read: false,
write: true
},
native: { def: stateDefinition.key || stateDefinition.name, poll: true }
});
}
}
/**
* Get a device from our devices array by name.
* @param {string} name
* @returns {cecDevice|undefined}
*/
getDeviceByName(name) {
if (name) {
name = cleanUpName(name);
return this.devices.find(d => d.name === name);
}
return undefined;
}
/**
* Make a device active / inactive. Sets all necessary states.
* @param {cecDevice} device
* @param {boolean} active
* @param {number} logicalAddress - new logical Address
* @returns {Promise<void>}
*/
async setDeviceActive(device, active, logicalAddress) {
device.active = active;
device.logicalAddress = logicalAddress;
if (device.name !== 'Global') {
await this.setStateAsync(buildId(device, stateDefinitions.active), active, true);
await this.setStateAsync(buildId(device, stateDefinitions.logicalAddress), device.logicalAddress, true);
await this.setStateAsync(buildId(device, stateDefinitions.logicalAddressHex), device.logicalAddressHex, true);
}
}
/**
* Creates default states in device, ie states all devices should have.
* @param {cecDevice} device
* @returns {Promise<void>}
*/
async createDefaultDeviceStates(device) {
//set physical address:
await this.createStateInDevice(device, stateDefinitions.name);
//set logical address:
await this.createStateInDevice(device, stateDefinitions.logicalAddress);
await this.createStateInDevice(device, stateDefinitions.logicalAddressHex);
//set active:
await this.createStateInDevice(device, stateDefinitions.active);
//last seen:
await this.createStateInDevice(device, stateDefinitions.lastSeen);
//menu status:
await this.createStateInDevice(device, stateDefinitions.menuStatus);
//power state:
await this.createStateInDevice(device, stateDefinitions.powerState);
//active source state:
await this.createStateInDevice(device, stateDefinitions.activeSource);
//create buttons button
await this.createStateInDevice(device, stateDefinitions.createButtons);
if (device.logicalAddress === 0) { //TV always has 0.0.0.0, but does not necessarily report that.
device.physicalAddress = '0.0.0.0';
await this.createStateInDevice(device, stateDefinitions.physicalAddress);
}
switch (device.logicalAddress) {
/*case CEC.LogicalAddress.PLAYBACKDEVICE1:
case CEC.LogicalAddress.PLAYBACKDEVICE2:
case CEC.LogicalAddress.PLAYBACKDEVICE3:
this.createStateInDevice(device, stateDefinitions.deck);
break;
case CEC.LogicalAddress.TUNER1:
case CEC.LogicalAddress.TUNER2:
case CEC.LogicalAddress.TUNER3:
case CEC.LogicalAddress.TUNER4:
this.createStateInDevice(device, stateDefinitions.deck);
this.createStateInDevice(device, stateDefinitions.tuner);
break;*/
case CEC.LogicalAddress.RECORDINGDEVICE1:
case CEC.LogicalAddress.RECORDINGDEVICE2:
case CEC.LogicalAddress.RECORDINGDEVICE3:
await this.createStateInDevice(device, stateDefinitions.recording);
break;
}
}
/**
* Create ioBroker Device for detected CEC device. Might return without creating if no name yet.
* @param {number} logicalAddress of detected device
* @param {event} data - incoming CEC message
* @returns {Promise<cecDevice>}
*/
async createCECDevice(logicalAddress, data) {
this.log.debug('============================ Creating device: ' + logicalAddress + ': ' + JSON.stringify(data));
//do we have a name already?
let name = (data && data.opcode === CEC.Opcode.SET_OSD_NAME && data.data) ? cleanUpName(data.data.str) : '';
if (!name && logicalAddress === 0) {
name = 'TV'; //TV does not really need to implement OSD Name... not nice. :-(
}
//do we know the device already?
let device = this.getDeviceByName(name);
if (device && !this.logicalAddressToDevice[logicalAddress]) {
this.logicalAddressToDevice[logicalAddress] = device; //we do not fill this from existing devices in ioBroker, do that here.
if(!device.active) {
await this.setDeviceActive(device, true, logicalAddress);
}
}
//do we have a device for the logicalAddress?
if (!device) {
device = this.logicalAddressToDevice[logicalAddress];
}
if (!device) {
this.log.debug('Creating dummy device for ' + logicalAddress + ' to use during device creation.');
/** @type {cecDevice} */
device = {
created: false,
ignored: false,
lastGetName: 0,
getNameTries: 0,
lastGetPhysAddr: 0,
getPhysAddrTries: 0,
logicalAddress: logicalAddress,
name: name ? cleanUpName(name) : '',
get logicalAddressHex() { return Number(this.logicalAddress).toString(16); },
createdStates: [],
didPoll: {},
maxCECVersionSupported: CEC.CECVersion.UNKNOWN
};
this.logicalAddressToDevice[logicalAddress] = device;
}
if (!name) {
name = device.name;
}
if (device.created) { //make sure we do the following only once:
this.log.info('Device for ' + logicalAddress + ' already created.');
return device;
}
if(!this.cec.ready) {
this.log.debug('CEC not yet ready, delay sending messages.');
return device;
}
//ask for name, if we don't have it
if (!name) {
//no device can not be undefined here... :-(
// @ts-ignore
if (device.getNameTries < 11) { //try to get name, if tried too often, continue with physicalAddress.
// @ts-ignore
if (Date.now() - device.lastGetName > 3000) {
this.log.info('No name for logicalAddress ' + logicalAddress + ', requesting it.');
try {
// @ts-ignore
device.getNameTries += 1;
device.lastGetName = Date.now();
await this.cec.sendMessage(null, logicalAddress, CEC.Opcode.GIVE_OSD_NAME);
clearTimeout(this.timeouts['createTimeout' + logicalAddress]);
this.timeouts['createTimeout' + logicalAddress] = setTimeout(() => {
this.createCECDevice(logicalAddress, data);
}, 10000);
} catch (e) {
this.log.error(`Could not get name: ${e} - ${e.stack}`);
}
}
return device; //exit and retry later.
}
}
if (!name && this.config.preventUnnamedDevices) {
device.ignored = true;
this.log.info('Ignoring device ' + device.logicalAddressHex + ' because did not get a name.');
return device;
}
//if we can not get name, but have physicalAddress already, use it.
if (!name && device.physicalAddress) {
device.name = device.physicalAddress.replace(/\./g, '');
name = device.name;
}
//ask for physicalAddress if we do not have it and it did not happen already / too fast / too many times. Exit and retry later.
if (!name) {
//no device can not be undefined here... :-(
// @ts-ignore
if (device.getPhysAddrTries < 11) { //try to get physicalAddress, if tried to often continue without it.
// @ts-ignore
if (Date.now() - device.lastGetPhysAddr > 60000) {
this.log.debug('Requesting name failed, try to get physical address for ' + logicalAddress);
try {
// @ts-ignore
device.getPhysAddrTries += 1;
device.lastGetPhysAddr = Date.now();
await this.cec.sendMessage(null, logicalAddress, CEC.Opcode.GIVE_PHYSICAL_ADDRESS);
clearTimeout(this.timeouts['createTimeout' + logicalAddress]);
this.timeouts['createTimeout' + logicalAddress] = setTimeout(() => {
this.createCECDevice(logicalAddress, data);
}, 10000);
} catch (e) {
this.log.error('Could not get physical address: ' + e + ' - ' + e.stack);
}
}
return device; //exit and retry later.
}
}
//all failed, we can not get a name... use Logical Address.
if (!name) {
this.log.warn('Could not find a name for device ' + logicalAddress);
name = 'Unknown_' + Number(logicalAddress).toString((16)).toUpperCase();
}
name = cleanUpName(name);
this.log.info('Device with logicalAddress ' + logicalAddress + ' seen. Has name ' + name);
device.name = name; //make sure we store clean name in device!
//got a name, let's check if we know that device already.
const existingDevice = this.devices.find(d => d.name === name);
if (!existingDevice) {
//ok, no existing device, let's create it.
device.active = true;
device.lastSeen = Date.now();
device.created = true;
device.logicalAddress = logicalAddress;
this.logicalAddressToDevice[logicalAddress] = device;
this.devices.push(device);
//create device in objectDB:
await this.createDeviceAsync(name);
await this.createDefaultDeviceStates(device);
} else {
this.logicalAddressToDevice[logicalAddress] = existingDevice;
existingDevice.created = true;
await this.setDeviceActive(device, true, logicalAddress);
//copy data from old device:
this.log.info('Already knew device ' + name + '. Update values.');
}
//set all fields in ioBroker, might have some stuff that was received before CEC Ready.
for (const key of Object.keys(device)) {
if (device[key] !== undefined && device[key] !== null) {
const stateDef = stateDefinitions[key];
if (stateDef) {
await this.processEvent({source: logicalAddress, stateDef: stateDef, parsedData: device[key]});
} else {
if (key !== 'created' && key !== 'physicalAddressReallyChanged' && key !== 'createdStates' &&
key !== 'lastGetName' && key !== 'getNameTries' && key !== 'lastGetPhysAddr' && key !== 'getPhysAddrTries' &&
key !== 'didPoll' && key !== 'ignored') {
this.log.warn('No state definition for ' + key);
}
}
}
}
//poll some more:
await this.cec.sendMessage(null, logicalAddress, stateDefinitions.deck.pollOpCode, stateDefinitions.deck.pollArgument);
await this.cec.sendMessage(null, logicalAddress, stateDefinitions.tuner.pollOpCode, stateDefinitions.tuner.pollArgument);
await this.cec.sendMessage(null, logicalAddress, stateDefinitions.menuStatus.pollOpCode, stateDefinitions.menuStatus.pollArgument);
await this.cec.sendMessage(null, logicalAddress, stateDefinitions.powerState.pollOpCode);
this.log.info('Creation of device ' + device.name + ' finished.');
return existingDevice || device;
}
/**
* @typedef event
* @type {object}
* @property {number} source
* not parsed:
* @property {string} [type]
* @property {string} [number]
* @property {"OUT"|"IN"} [flow]
* @property {number} [target]
* @property {number} [opcode]
* @property {Array<number>} [args]
* @property {string} [event]
* @property {{val: number, str: string}} [data]
* parsed:
* @property {stateDefinition} [stateDef]
* @property {any} [parsedData]
*
* Process CEC Event
* @param {event} data - CEC event
* @returns {Promise<undefined|*>}
*/
async processEvent(data) {
try {
//REPORT_PHYSICAL_ADDRESS: {"type":"TRAFFIC","number":"17707","flow":"OUT","source":1,"target":15,"opcode":132,"args":[48,0,1],"event":"REPORT_PHYSICAL_ADDRESS","data":{"val":12288,"str":"3.0.0.0"}}
//DEVICE_VENDOR_ID: {"type":"TRAFFIC","number":"57985","flow":"IN","source":11,"target":15,"opcode":135,"args":[0,0,0],"event":"DEVICE_VENDOR_ID","data":{"val":0,"str":"UNKNOWN"}}
//ignore stuff we send.
if (data.flow === 'OUT') {
return;
}
this.log.debug('============================ Processing Event: ' + data.event + ': ' + JSON.stringify(data));
let stateDef = data.stateDef;
if (!stateDef) {
//either event or opcode are always defined.
//@ts-ignore
stateDef = eventToStateDefinition[data.event || data.opcode];
}
if (!stateDef) {
if (data.opcode !== CEC.Opcode.SET_MENU_LANGUAGE && data.opcode !== CEC.Opcode.ROUTING_CHANGE && data.opcode !== CEC.Opcode.ROUTING_INFORMATION) {
this.log.warn('No stateDef for ' + JSON.stringify(data));
}
return;
}
let device = this.logicalAddressToDevice[data.source];
if (stateDef.isGlobal) {
this.log.debug('State ' + stateDef.name + ' is global, use global device.');
device = this.globalDevice;
}
if (device && device.ignored) {
this.log.debug('Ignoring message from ignored device.');
return;
}
if (!device || !device.created) {
this.log.debug('No device for ' + data.source + ' start device creation');
await this.createCECDevice(data.source, data);
device = this.logicalAddressToDevice[data.source];
}
if (stateDef.name === stateDefinitions.name.name) {
if (data && data.data && data.data.str) {
data.data.str = cleanUpName(data.data.str);
}
if (device.created && data.data && data.data.str && data.data.str !== device.name) {
this.log.warn('New device with name ' + data.data.str + ' for logicalAddress ' + device.logicalAddressHex);
//deactivate old device:
await this.setDeviceActive(device, false, CEC.LogicalAddress.UNKNOWN);
delete this.logicalAddressToDevice[data.source];
//rerun method:
return this.processEvent(data);
}
}
if (stateDef.name === stateDefinitions.physicalAddress.name) {
if (data && data.data && data.data.str) {
if (device.created && device.physicalAddress !== data.data.str && !device.physicalAddressReallyChanged) {
this.log.info('Device with unexpected physical address came online on logical address ' + device.logicalAddressHex);
if (device.active) {
await this.setDeviceActive(device, false, CEC.LogicalAddress.UNKNOWN);
delete this.logicalAddressToDevice[data.source];
}
device.physicalAddressReallyChanged = true; //prevent endless loop, if physical address really changed.
//this should create the new device:
await this.cec.sendCommand(null, data.source, CEC.Opcode.GIVE_OSD_NAME, CECMonitor.EVENTS.SET_OSD_NAME);
//add physical address to device:
return this.processEvent(data);
}
}
}
let value = data.parsedData;
if (value === undefined) {
this.log.debug('Parsing data...');
if (data.data) {
value = !!data.data.val;
}
if (stateDef.parse) {
value = stateDef.parse(data);
} else if (stateDef.type === 'string' && data.data) {
value = data.data.str;
}
}
//store value in device:
if (device.created && device[stateDef.key || stateDef.name] === undefined) {
await this.createStateInDevice(device, stateDef);
}
if (!stateDef.readOnly) {
device[stateDef.key || stateDef.name] = value;
}
if (device.created) {
if(!device.active) {
await this.setDeviceActive(device, true, data.source);
}
if (device.name !== 'Global') {
await this.setStateAsync(buildId(device, stateDefinitions.active), true, true);
await this.setStateAsync(buildId(device, stateDefinitions.lastSeen), Date.now(), true);
}
const id = buildId(device, stateDef);
this.log.debug('Updating ' + id + ' to ' + value);
await this.createStateInDevice(device, stateDef);
if (device.didPoll[stateDef.name]) {
await this.setStateAsync(id, value, true);
device.didPoll[stateDef.name] = false;
} else {
await this.setStateAsync(id, value, true);
}
//set global active source here:
if (stateDef.name === stateDefinitions.activeSource.name && data.data && data.data.str) {
this.log.debug('Setting activeSource to ' + data.data.str);
await this.setStateAsync(buildId(this.globalDevice, stateDefinitions['active-source']), data.data.str, true);
for (const otherDevice of this.devices) {
if (otherDevice.name !== 'Global' && otherDevice.activeSource && otherDevice.name !== device.name) {
await this.setStateAsync(buildId(device, stateDef), false, true);
}
}
}
if (stateDef.name === stateDefinitions.volume.name) {
await this.setStateAsync(buildId(this.globalDevice, stateDefinitions.volume), value, true);
}
if (stateDef.name === stateDefinitions.maxCecVersionSupported.name) {
if (device.maxCECVersionSupported === CEC.CECVersion.UNKNOWN && !device.tryingMaxCECVersion) {
device.tryingMaxCECVersion = true;
device.maxCECVersionSupported = CEC.CECVersion.VERSION_1_4 + 1; //start with trying 1_4
}
if (device.tryingMaxCECVersion) {
device.maxCECVersionSupported -= 1;
if (device.maxCECVersionSupported > 0) {
await this.cec.sendMessage(null, device.logicalAddress, CEC.Opcode.CEC_VERSION, device.maxCECVersionSupported);
await this.setStateChangedAsync(buildId(device, stateDefinitions.maxCecVersionSupported), device.maxCECVersionSupported, true);
}
}
}
}
} catch (e) {
console.log('Error: ', e);
this.log.error('Error during processing event: ' + e + ' ' + JSON.stringify(data) + ' - ' + e.stack);
}
}
/**
* initializes cec monitor
* @param {ioBroker.AdapterConfig} config
*/
async setupCECMonitor(config) {
try {
//let's make sure we can access vchiq, needed for cec-client:
this.log.debug('Testing access.');
const result = await fs.access('/dev/vchiq', fsConstants.R_OK);
this.log.debug('Access resulted in: ' + result);
} catch (e) {
if (e.code === 'EACCES') {
this.log.error("Can not access HDMI-CEC, please make sure iobroker user can access /dev/vchiq. On Raspian run this command: 'sudo usermod -a -G video iobroker'");
} else {
this.log.error('Can not access HDMI. Please read requirements part of readme. Error: ' + e + ' - ' + e.stack);
}
}
try {
this.log.debug('Starting CEC Monitor.');
this.cec = new CECMonitor(config.osdName, {
debug: true, //config.cecDebug,
//hdmiPort: config.hdmiPort,
//processManaged: false, // if false -> will catch uncaught exceptions and exit process. Hm.
type: config.type,
autoRestart: true, //allows auto restart of cec-client.
commandTimeout: 3
});
this.cec.on('_debug', d => this.log.debug(d));
this.cec.on('_traffic', d => this.log.debug(d));
this.cec.on('_stop', d => d ? this.log.error('CEC Monitor stopped: ' + d) : this.log.debug('CEC Monitor stopped gracefully.'));
this.cec.on('_error', e => {
if (e.code === 'ENOENT') {
this.log.error('cec-client not found. Please make sure cec-utils are installed and cec-client can be run by iobroker user.');
this.terminate(utils.EXIT_CODES.INVALID_DEPENDENCY_VERSION);
//can not do the rest of the stuff.
}
this.log.error('Error from CEC library: ' + e);
this.log.info('Trying to restart and correct the error.');
this.terminate(utils.EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);
});
//add listeners for device changes:
Object.keys(eventToStateDefinition).forEach(k => this.cec.on(k, d => this.processEvent(d)));
await this.cec.waitForReady();
await this.setStateChangedAsync('info.connection', true, true);
} catch (e) {
this.log.error('Could not start CEC adapter: ' + e + ' - ' + e.stack);
await this.setStateChangedAsync('info.connection', false, true);
if (e.code === 'ENOENT') {
this.log.error('cec-client not found. Please make sure cec-utils are installed and cec-client can be run by iobroker user.');
return; //can not do the rest of the stuff.
}
}
this.log.debug('CEC Monitor ready.');
this.timeouts.scan = setTimeout(() => this.cec.writeRawMessage('scan'), 10000);
if (config.pollPowerStates) {
await this.pollPowerStates();
}
//some global states:
await this.createDeviceAsync(this.globalDevice.name);
//raw command
await this.createStateInDevice(this.globalDevice, stateDefinitions['raw-command']);
//active-source:
await this.createStateInDevice(this.globalDevice, stateDefinitions['active-source']);
//osd:
await this.createStateInDevice(this.globalDevice, stateDefinitions['osd-message']);
await this.createStateInDevice(this.globalDevice, stateDefinitions['osd-message-clear']);
//volume:
await this.createStateInDevice(this.globalDevice, stateDefinitions.volume);
await this.createStateInDevice(this.globalDevice, stateDefinitions.volumeUp);
await this.createStateInDevice(this.globalDevice, stateDefinitions.volumeDown);
await this.createStateInDevice(this.globalDevice, stateDefinitions.mute);
await this.createStateInDevice(this.globalDevice, stateDefinitions.systemAudio);
await this.createStateInDevice(this.globalDevice, stateDefinitions.arc);
await this.createStateInDevice(this.globalDevice, stateDefinitions.standbyAll);
//poll audio stuff:
this.timeouts.pollAudio = setTimeout(async () => {
//volume, mute and so on
try {
await this.cec.sendMessage(null, CEC.LogicalAddress.AUDIOSYSTEM, CEC.Opcode.GIVE_AUDIO_STATUS);
} catch (e) {
this.log.info('Could not poll audio status: ' + e);
}
//do we use audio at all?
try {
await this.cec.sendMessage(null, CEC.LogicalAddress.AUDIOSYSTEM, CEC.Opcode.GIVE_SYSTEM_AUDIO_MODE_STATUS);
} catch (e) {
this.log.info('Could not poll audio system status: ' + e);
}
//who is active:
try {
await this.cec.sendMessage(null, CEC.LogicalAddress.BROADCAST, CEC.Opcode.REQUEST_ACTIVE_SOURCE);
} catch (e) {
this.log.info('Could not poll active source: ' + e);
}
}, 2000);
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
this.log.info('config osdName: ' + this.config.osdName);
this.log.info('config type: ' + this.config.type);
//setup devices:
const existingDevices = await this.getDevicesAsync();
for (const device of existingDevices) {
const id = device._id;
const existingDevice = {
/** @type {Array<string>} */
createdStates: [],
active: false,
name: '',
created: true,
ignored: false,
logicalAddress: CEC.LogicalAddress.UNKNOWN,
get logicalAddressHex() { return Number(this.logicalAddress).toString(16); },
didPoll: {},
maxCECVersionSupported: CEC.CECVersion.UNKNOWN
};
const states = await this.getStatesOfAsync(id);
for (const stateObject of states) {
if (!stateObject.native.poll) { //skipp poll states
const defString = /** @type {string} */ (stateObject.native.def);
/** @type {stateDefinition} */
const def = stateDefinitions[defString];
const state = await this.getStateAsync(stateObject._id);
if (state && def && !def.readOnly) { //unpack val
existingDevice[def.key || def.name] = state.val; //remember values
}
existingDevice.createdStates.push(defString);
}
}
if (device.common.name !== 'Global') {
let name = device.common.name;
if (typeof name !== 'string') {
//@ts-ignore - somehow types do not yet know "uk".
name = /** @type {string} */ (name.en || name.de || name.uk || name.es || name.ru || name.fr || name.it || name.nl || name.pl || name.pl || name['zh-cn']);
}
await this.setStateChangedAsync(buildId(name, stateDefinitions.active), false, true);
}
this.devices.push(existingDevice);
//make sure all states that should exist do exist.
if (existingDevice.name) {
await this.createDefaultDeviceStates(existingDevice);
}
}
//setup cec system
await this.setupCECMonitor(this.config);
// in this template all states changes inside the adapters namespace are subscribed
this.subscribeStates('*');
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {function} callback
*/
onUnload(callback) {
try {
this.cec.stop();
for (const key of Object.keys(this.timeouts)) {
clearTimeout(this.timeouts[key]);
}
this.log.debug('cleaned everything up...');
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
// The state was changed
if (!state.ack) {
try {
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
const isPoll = id.includes('.poll.');
const deviceName = getDeviceIdFromId(id);
const device = this.devices.find(d => d && d.name === deviceName);
if (!device) {
this.log.error('No device for name ' + deviceName + ' created.');
return;
}
if (isPoll) {
const stateDefinition = stateDefinitionFromId(id);
if (stateDefinition.pollOpCode) {
device.didPoll[stateDefinition.name] = true;
let target = null;
if (stateDefinition.pollTarget) {
target = stateDefinition.pollTarget;
} else if (!stateDefinition.isGlobal) {
target = device.logicalAddress;
}
await this.cec.sendMessage(null, target, stateDefinition.pollOpCode, stateDefinition.pollArgument);
} else {
this.log.error('Can not poll ' + stateDefinition.name + '. Please report error.');
}
} else if (id.includes(stateDefinitions.createButtons.name)) {
this.log.debug('Creating buttons for ' + device.name);
for (const key of Object.keys(CEC.UserControlCode)) {
await this.setObjectNotExistsAsync(`${device.name}.buttons.${key}`, {type: 'state', common: {name: key, write: true, read: false, role: 'button', type: 'boolean'}, native: {isButton: true}});
}
await this.setObjectNotExistsAsync(`${device.name}.buttons.time`, {type: 'state', common: {def: 500, name: 'Set time for next button press', unit: 'ms', write: true, read: false, role: 'level.timer', type: 'number'}, native: {isButton: true}});
} else if (id.includes('.buttons.time')) {
if (!state.val || Number(state.val) < 50) {
state.val = 50;
this.log.warn('Button presses below 50ms not supported. Increased time.');
}
device.currentButtonPressTime = Math.max(50, /** @type {number} */ (state.val));
} else if (id.includes('.buttons.')) {
const name = id.substring(id.lastIndexOf('.') + 1);
const code = CEC.UserControlCode[name];
if (code) {
await this.cec.sendMessage(null, device.logicalAddress, CEC.Opcode.USER_CONTROL_PRESSED, code);
setTimeout(async () => {
await this.cec.sendMessage(null, device.logicalAddress, CEC.Opcode.USER_CONTROL_RELEASE, code);
}, device.currentButtonPressTime);
}
} else {
const stateDefinition = stateDefinitionFromId(id);
if (typeof stateDefinition.command === 'function') {
this.log.debug('Sending ' + state.val + ' for id ' + id + ' to ' + deviceName);
await stateDefinition.command(state.val, device, this.cec, this.log);
} else {
this.log.warn('Can not write state ' + id + ' of type ' + stateDefinition.name + '. Please do not write read only states!');