-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
673 lines (562 loc) · 16.8 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
const { exec, spawn } = require('child_process');
const { EventEmitter } = require('events');
const readline = require('readline');
const debug = require('debug');
const keymap = require('./keymap');
const ctl_debug = debug('cec-controller');
const client_debug = debug('cec-client');
module.exports = class Client
{
constructor(opts)
{
if(typeof opts !== 'object') opts = {};
this.osdString = (typeof opts.osdString === 'string'
&& opts.osdString.length < 13) ? opts.osdString : 'CEC-Control';
this.type = (typeof opts.type === 'string') ? opts.type.charAt(0) : 'p';
this.hdmiPorts = (opts.hdmiPorts > 0) ? opts.hdmiPorts : 3;
this.broadcast = (opts.broadcast === false) ? false : true;
this.controlledDevice = 'dev0';
this.sourceNumber = 0;
this.keyReleaseTimeout = null;
this.togglingPower = false;
this.runningCheckStatus = false;
this.enabled = true;
this.cec = new EventEmitter();
this.cec.closeClient = () => this._closeClient();
this.myDevice = null;
this.devices = {};
this._scanDevices();
return this.cec;
}
_closeClient()
{
return new Promise((resolve, reject) =>
{
this.enabled = false;
if(this.client) this.client.kill();
this.cec.removeAllListeners();
this.cec = null;
resolve(true);
});
}
_scanDevices()
{
ctl_debug('Performing initial devices scan...');
exec(`echo scan | cec-client -s -t ${this.type} -o ${this.osdString} -d 1`,
{ maxBuffer: 5 * 1024 * 1024, windowsHide: true }, (error, stdout, stderr) =>
{
if(error)
{
ctl_debug(error);
return this.cec.emit('error', new Error('App cec-client had an error!'));
}
ctl_debug('Devices scan finished successfully');
this.devices = this._parseScanOutput(String(stdout));
const scannedKeys = Object.keys(this.devices);
if(scannedKeys.length === 0)
{
const scanErr = new Error('CEC scan did not find any devices!');
ctl_debug(scanErr);
return this.cec.emit('error', scanErr);
}
this.myDevice = this._getMyDevice(this.devices);
if(!this.myDevice)
{
const myDeviceErr = new Error(`Could not obtain this CEC adapter info!`);
ctl_debug(myDeviceErr);
return this.cec.emit('error', myDeviceErr);
}
for(var deviceId in this.devices)
this.devices[deviceId] = { ...this.devices[deviceId], ...this._getDeviceFunctions(deviceId) };
this.devices = { ...this.devices, ...this._getGlobalFunctions() };
ctl_debug('Finished controller object assembly');
ctl_debug(this.devices);
this._createClient();
});
}
_parseScanOutput(outStr)
{
var devicesObject = {};
var outArray = outStr.split('device #');
if(outArray.length > 1)
{
outArray.shift();
outArray.forEach(device =>
{
var devName = device.substring(device.indexOf(':') + 2, device.indexOf('\n'));
var devId = device.substring(0, device.indexOf(':'));
if(!devName || !devId) return;
devicesObject['dev' + devId] = { name: devName, logicalAddress: devId };
var data = device.split('\n');
for(var i = 1; i < data.length; i++)
{
var params = data[i].split(':');
if(params.length !== 2) break;
var key = params[0].toLowerCase();
key = key.split(' ');
if(key.length > 1)
{
for(var j = 1; j < key.length; j++)
{
key[j] = key[j].charAt(0).toUpperCase() + key[j].slice(1);
}
}
key = key.toString().replace(/,/g, '');
var value = params[1].trimLeft();
devicesObject['dev' + devId][key] = value;
}
});
}
return devicesObject;
}
_getMyDevice(devices)
{
var keys = Object.keys(devices);
for(var key of keys)
{
var currObj = devices[key];
if(typeof currObj !== 'object')
continue;
if(currObj.hasOwnProperty('osdString') && currObj.osdString === this.osdString)
{
ctl_debug(`Detected this device as: ${key}`);
return key;
}
}
ctl_debug('Could not detect this device!');
return null;
}
_createClient()
{
this.doneInit = false;
this.client = spawn('cec-client',
['-t', this.type, '-o', this.osdString, '-d', 8],
{ stdio: ['pipe', 'pipe', 'ignore'] });
this.client.stdin.setEncoding('utf8');
this.client.stdout.once('data', () =>
ctl_debug('cec-client background process started')
);
this.client.once('close', (code) =>
{
this.client = null;
ctl_debug(`cec-client exited with code: ${code}`);
if(this.doneInit && this.enabled) this._createClient();
else if(this.enabled) this.cec.emit('error', new Error(`App cec-client exited with code: ${code}`));
});
const rl = readline.createInterface({
input: this.client.stdout,
crlfDelay: Infinity
});
rl.on('line', this._parseClientOutput);
rl.once('close', () => rl.removeListener('line', this._parseClientOutput));
}
_parseClientOutput(line)
{
if(line.length < 5) return;
if(!line.startsWith(`power status:`))
client_debug(line);
if(!this.doneInit)
{
if(this.myDevice && line.includes('waiting for input'))
{
this.doneInit = true;
ctl_debug('cec-client init successful');
this.cec.emit('ready', this.devices);
}
return;
}
if(line.startsWith(`power status:`))
{
var logicalAddress = this.devices[this.controlledDevice].logicalAddress;
var value = this._getLineValue(line);
if(this.devices[this.controlledDevice].powerStatus !== value)
{
this.devices[this.controlledDevice].powerStatus = value;
ctl_debug(`Updated dev${logicalAddress} powerStatus using stdout to: ${value}`);
}
this.cec.emit(`${logicalAddress}:powerStatus`, value);
}
else if(this.devices.hasOwnProperty('dev0') && line.startsWith('TRAFFIC:'))
{
if(line.includes('>>'))
{
var destAddress = this.devices[this.myDevice].logicalAddress;
var value = this._getLineValue(line).toUpperCase();
if(line.includes(`>> 0${destAddress}:44:`))
{
var keyName = keymap.getName(value);
this.cec.emit('keypress', keyName);
if(!this.keyReleaseTimeout)
this.cec.emit('keydown', keyName);
}
else if(line.includes(`>> 0${destAddress}:8b:`))
{
if(this.keyReleaseTimeout)
clearTimeout(this.keyReleaseTimeout);
this.keyReleaseTimeout = setTimeout(() =>
{
this.cec.emit('keyup', keymap.getName(value));
this.keyReleaseTimeout = null;
}, 600);
}
else if(line.includes('>> 0f:36'))
{
ctl_debug('Received standby request on broadcast');
ctl_debug('Checking devices powerStatus....');
this._checkDevicesStatus(null, 'standby');
}
else if(line.includes('f:84:'))
{
var logicalAddress = line.substring(line.indexOf('>> ') + 3, line.indexOf('f:84:'));
if(logicalAddress && logicalAddress.length === 1)
{
ctl_debug('Received report address request on broadcast');
var lineCmd = line.split('>> ')[1];
if(
this.devices.hasOwnProperty('dev' + logicalAddress)
&& this.devices['dev' + logicalAddress].address === 'f.f.f.f'
&& lineCmd.endsWith(`:0${logicalAddress}`)
) {
var addArr = lineCmd.substring(
lineCmd.indexOf('f:84:') + 5, lineCmd.indexOf(`:0${logicalAddress}`)
).split(':');
if(addArr.length === 2)
{
var newAddr = addArr[0].charAt(0) + '.' + addArr[0].charAt(1) +
'.' + addArr[1].charAt(0) + '.' + addArr[1].charAt(1);
this.devices['dev' + logicalAddress].address = newAddr;
ctl_debug(`Updated dev${logicalAddress} address to: ${newAddr}`);
}
}
if(line.includes(`>> ${logicalAddress}f:84:`))
this._checkDevicesStatus(`dev${logicalAddress}`);
}
}
else if(line.includes('f:82:'))
{
var addArr = line.substring(line.indexOf('f:82:') + 5).split(':');
if(addArr.length === 2)
{
var detAddr = addArr[0].charAt(0) + '.' + addArr[0].charAt(1) +
'.' + addArr[1].charAt(0) + '.' + addArr[1].charAt(1);
for(var key in this.devices)
{
if(
typeof this.devices[key] === 'object'
&& this.devices[key].hasOwnProperty('activeSource')
&& this.devices[key].hasOwnProperty('address')
) {
if(
this.devices[key].address !== detAddr
&& this.devices[key].activeSource === 'yes'
) {
this.devices[key].activeSource = 'no';
ctl_debug(`Changed ${key} activeSource to: no`);
}
else if(
this.devices[key].address === detAddr
&& this.devices[key].activeSource === 'no'
) {
this.devices[key].activeSource = 'yes';
ctl_debug(`Changed ${key} activeSource to: yes`);
}
}
}
}
}
}
else if(line.includes('<<') && !this.togglingPower)
{
var srcAddress = this.devices[this.myDevice].logicalAddress;
var destAddress = this.devices[this.controlledDevice].logicalAddress;
if(line.includes(`<< ${srcAddress}0:04`))
{
for(var key in this.devices)
{
if(
typeof this.devices[key] === 'object'
&& this.devices[key].hasOwnProperty('activeSource')
&& this.devices[key].activeSource === 'yes'
) {
this.devices[key].activeSource = 'no';
ctl_debug(`Changed ${key} activeSource to: no`);
break;
}
}
if(this.devices[this.myDevice].activeSource !== 'yes')
ctl_debug(`Updated dev${srcAddress} activeSource using stdout to: yes`);
this.devices[this.myDevice].activeSource = 'yes';
this.cec.emit(`${srcAddress}:activeSource`, 'yes');
}
else if(line.includes(`<< ${srcAddress}0:9d`))
{
if(this.devices[this.myDevice].activeSource !== 'no')
ctl_debug(`Updated dev${srcAddress} activeSource using stdout to: no`);
this.devices[this.myDevice].activeSource = 'no';
this.cec.emit(`${srcAddress}:activeSource`, 'no');
}
else if(line.includes(`<< ${srcAddress}${destAddress}:44`))
{
var value = this._getLineValue(line).toUpperCase();
var keyName = keymap.getName(value);
ctl_debug(`Send "${keyName}" key to dev${destAddress}`);
this.cec.emit('sendKey', keyName);
}
}
}
}
_getLineValue(line)
{
var lineArray = line.split(':');
return lineArray[lineArray.length - 1].trim();
}
_getDeviceFunctions(deviceId)
{
var func = {
turnOn: this.changePower.bind(this, deviceId, 'on'),
turnOff: this.changePower.bind(this, deviceId, 'standby'),
togglePower: this.togglePower.bind(this, deviceId)
};
if(this.devices[deviceId].name === 'TV')
{
func.changeSource = (number) =>
{
if(isNaN(number) || number < 0)
{
this.sourceNumber = (this.sourceNumber < this.hdmiPorts) ? this.sourceNumber + 1 : 0;
number = this.sourceNumber;
}
var srcAddress = this.devices[this.myDevice].logicalAddress;
var destAddress = (this.broadcast === false) ? this.devices[deviceId].logicalAddress : 'F';
return this.command(`tx ${srcAddress}${destAddress}:82:${number}0:00`, null);
}
}
if(this.devices[deviceId] !== this.devices[this.myDevice])
{
func.sendKey = (keyName) =>
{
this.controlledDevice = deviceId;
var srcAddress = this.devices[this.myDevice].logicalAddress;
var destAddress = this.devices[deviceId].logicalAddress;
return new Promise((resolve, reject) =>
{
var keyHex = keymap.getHex(keyName);
if(!keyHex)
{
ctl_debug(`Unknown key name: ${keyName}`);
resolve(null);
}
else
{
var sendKeyTimeout = setTimeout(() =>
{
sendKeyTimeout = null;
ctl_debug(`dev${destAddress} send key timed out!`);
sendKeyHandler(null);
}, 1000);
var sendKeyHandler = (value) =>
{
if(value === keyName || value === null)
{
if(sendKeyTimeout)
clearTimeout(sendKeyTimeout);
this.cec.removeListener('sendKey', sendKeyHandler);
if(!value)
{
ctl_debug(`dev${destAddress} could not receive key!`);
resolve(null);
}
else
resolve(true);
}
}
this.cec.on('sendKey', sendKeyHandler);
var sendCmd = `tx ${srcAddress}${destAddress}:44:${keyHex}`;
ctl_debug(`Command: ${sendCmd}`);
this.command(sendCmd, null);
}
});
}
}
return func;
}
_getGlobalFunctions()
{
return {
setActive: this.changeActive.bind(this, 'yes'),
setInactive: this.changeActive.bind(this, 'no'),
volumeUp: this.command.bind(this, 'volup', null),
volumeDown: this.command.bind(this, 'voldown', null),
mute: this.command.bind(this, 'mute', null),
getKeyNames: keymap.getNamesArray.bind(this),
command: (args) => { return this.command(args, null); }
}
}
command(action, logicalAddress)
{
return new Promise((resolve, reject) =>
{
if(!action || typeof action !== 'string') resolve(null);
else
{
var cmd = '';
if(logicalAddress) cmd = `${action} ${logicalAddress}`;
else cmd = action;
if(!this.togglingPower)
ctl_debug(`Running command: ${cmd}`);
this.client.stdin.write(cmd);
this.client.stdout.once('data', () => resolve(true));
}
});
}
changePower(deviceId, powerStatus)
{
this.controlledDevice = deviceId;
return new Promise((resolve, reject) =>
{
this.getStatus(deviceId).then(value =>
{
if(value === null) resolve(null);
else if(value === powerStatus)
{
ctl_debug(`${deviceId} powerStatus is already in desired state`);
resolve(powerStatus);
}
else
{
this.command(powerStatus, this.devices[deviceId].logicalAddress);
var timedOut = false;
var actionTimeout = setTimeout(() => timedOut = true, 40000);
var waitPower = () =>
{
this.getStatus(deviceId).then(value =>
{
if(powerStatus === 'standby' && value === 'unknown')
{
ctl_debug(`Could not detect ${deviceId} powerStatus!`);
}
else if(value !== powerStatus && !timedOut)
{
return waitPower();
}
clearTimeout(actionTimeout);
this.togglingPower = false;
if(timedOut)
{
ctl_debug(`${deviceId} powerStatus change timed out!`);
resolve(null);
}
else
{
ctl_debug(`${deviceId} powerStatus changed to: ${value}`);
resolve(value);
}
});
}
ctl_debug(`Waiting for ${deviceId} powerStatus change to: ${powerStatus}`);
this.togglingPower = true;
waitPower();
}
});
});
}
togglePower(deviceId)
{
return new Promise((resolve, reject) =>
{
this.getStatus(deviceId).then(value =>
{
var action = (value === 'on') ? 'standby'
: (value === 'standby') ? 'on' : null;
if(action)
this.changePower(deviceId, action).then(resolve);
else
resolve(null);
});
});
}
changeActive(isActiveSource)
{
return new Promise((resolve, reject) =>
{
var logicalAddress = this.devices[this.myDevice].logicalAddress;
var activeSource = (isActiveSource === 'yes' || isActiveSource === true) ? 'yes' : 'no';
if(this.devices[this.myDevice].activeSource === activeSource)
{
ctl_debug(`dev${logicalAddress} activeSource is already in desired state`);
resolve(activeSource);
}
else
{
var action = (activeSource === 'yes') ? 'as' : 'is';
var statusTimeout = setTimeout(() =>
{
ctl_debug(`dev${logicalAddress} activeSource change timed out!`);
this.devices[this.myDevice].activeSource = null;
this.cec.emit(`${logicalAddress}:activeSource`, null);
}, 5000);
this.cec.once(`${logicalAddress}:activeSource`, (value) =>
{
clearTimeout(statusTimeout);
ctl_debug(`dev${logicalAddress} activeSource changed to: ${value}`);
resolve(value);
});
this.command(action, null);
}
});
}
getStatus(deviceId)
{
this.controlledDevice = deviceId;
return new Promise((resolve, reject) =>
{
var logicalAddress = this.devices[deviceId].logicalAddress;
var statusTimeout = setTimeout(() =>
{
if(!this.togglingPower)
{
ctl_debug(`dev${logicalAddress} getStatus timed out!`);
this.devices[deviceId].powerStatus = null;
}
this.cec.emit(`${logicalAddress}:powerStatus`, null);
}, 6000);
this.cec.once(`${logicalAddress}:powerStatus`, (value) =>
{
clearTimeout(statusTimeout);
if(!this.togglingPower)
ctl_debug(`dev${logicalAddress} powerStatus is: ${value}`);
resolve(value);
});
this.command(`pow ${logicalAddress}`);
});
}
async _checkDevicesStatus(deviceId, wantedStatus)
{
if(this.runningCheckStatus) return;
this.runningCheckStatus = true;
var checkRequired = () =>
{
if(
typeof this.devices[deviceId] === 'object'
&& this.devices[deviceId].hasOwnProperty('powerStatus')
&& this.devices[deviceId].powerStatus !== wantedStatus
&& deviceId !== this.myDevice
)
return true;
return false;
}
if(deviceId && checkRequired())
{
await this.getStatus(deviceId);
}
else
{
for(var deviceId in this.devices)
{
if(checkRequired())
await this.getStatus(deviceId);
}
}
this.runningCheckStatus = false;
}
}