-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
index.js
executable file
·1127 lines (1109 loc) · 39.7 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';
var http = require('http');
var url = require('url');
var base64 = require('base-64');
var wol = require('wake_on_lan');
var fs = require('fs');
const os = require('os');
var Service, Characteristic, Accessory, UUIDGen, STORAGE_PATH;
class BraviaPlatform {
constructor(log, config, api) {
if (!config || !api)
return;
this.log = log;
this.config = config;
this.api = api;
if (!config.tvs) {
log('Warning: Bravia plugin not configured.');
return;
}
this.devices = [];
const self = this;
api.on('didFinishLaunching', function () {
self.config.tvs.forEach(function (tv) {
if (self.devices.find(device => device.name === tv.name) == undefined) {
self.devices.push(new SonyTV(self, tv));
}
});
self.devices.forEach(device => device.start());
});
}
// called by homebridge when a device is restored from cache
configureAccessory(accessory) {
const self = this;
if (!this.config || !this.config.tvs) { // happens if plugin is disabled and still active accessories
return;
}
var existingConfig = this.config.tvs.find(tv => tv.name === accessory.context.config.name);
if (existingConfig === undefined) {
this.log('Removing TV ' + accessory.displayName + ' from HomeKit');
this.api.on('didFinishLaunching', function () {
if (!accessory.context.isexternal) {
self.api.unregisterPlatformAccessories('homebridge-bravia', 'BraviaPlatform', [accessory]);
} else {
// TODO: delete context file? not here, we're not called
}
});
} else {
this.log('Restoring ' + accessory.displayName + ' from HomeKit');
// TODO: reachable
accessory.reachable = true;
// if its restored its registered
self.devices.push(new SonyTV(this, existingConfig, accessory));
accessory.context.isRegisteredInHomeKit = true;
}
}
}
// TV accessory class
class SonyTV {
constructor(platform, config, accessory = null) {
this.platform = platform;
this.debug = config.debug;
this.log = platform.log;
this.config = config;
this.name = config.name;
this.ip = config.ip;
this.mac = config.mac || null;
this.woladdress = config.woladdress || '255.255.255.255';
this.port = config.port || '80';
this.tvsource = config.tvsource || null;
this.soundoutput = config.soundoutput || 'speaker';
this.updaterate = config.updaterate || 5000;
this.channelupdaterate = config.channelupdaterate === undefined ? 30000 : config.channelupdaterate;
this.starttimeout = config.starttimeout || 5000;
this.comp = config.compatibilitymode;
this.serverPort = config.serverPort || 8999;
this.sources = config.sources || ['extInput:hdmi', 'extInput:component', 'extInput:scart', 'extInput:cec', 'extInput:widi'];
this.useApps = (isNull(config.applications)) ? false : (config.applications instanceof Array == true ? config.applications.length > 0 : config.applications);
this.applications = (isNull(config.applications) || (config.applications instanceof Array != true)) ? [] : config.applications;
this.cookiepath = STORAGE_PATH + '/sonycookie_' + this.name;
this.cookie = null;
this.pwd = config.pwd || null;
this.registercheck = false;
this.authok = false;
this.appsLoaded = false;
if (!this.useApps)
this.appsLoaded = true;
this.power = false;
this.inputSourceList = [];
this.inputSourceMap = new Map();
this.currentUri = null;
this.currentMediaState = Characteristic.TargetMediaState.STOP; // TODO
this.uriToInputSource = new Map();
this.loadCookie();
this.services = [];
this.channelServices = [];
this.scannedChannels = [];
const contextPath = STORAGE_PATH + '/sonytv-context-' + this.name + '.json';
try {
if (accessory != null) {
// accessory was supplied - dynamic plugin with configureAccessory restore
this.accessory = accessory;
this.accessory.category = this.platform.api.hap.Categories.TELEVISION; // 31;
this.grabServices(accessory);
this.applyCallbacks();
} else if (this.config.externalaccessory && fs.existsSync(contextPath)) {
// try and restore external accessory
const rawdata = fs.readFileSync(contextPath);
const accessoryContext = JSON.parse(rawdata);
var uuid = UUIDGen.generate(this.name + '-SonyTV');
this.accessory = new Accessory(this.name, uuid, this.platform.api.hap.Categories.TELEVISION);
this.accessory.context.uuid = accessoryContext.uuid;
this.accessory.context.isexternal = true;
// not registered - needs to be added
// this.accessory.context.isRegisteredInHomeKit = accessoryContext.isRegisteredInHomeKit;
this.accessory.context.config = this.config;
this.log('Cached external accessory ' + this.name + ' found and restored');
this.createServices();
this.applyCallbacks();
this.loadChannelsFromFile();
} else {
// new accessory
var uuid = UUIDGen.generate(this.name + '-SonyTV');
this.log('Creating new accessory for ' + this.name);
this.accessory = new Accessory(this.name, uuid, this.platform.api.hap.Categories.TELEVISION);
this.accessory.context.config = config;
this.accessory.context.uuid = uuidv4();
this.log('New TV ' + this.name + ', will be queried for channels/apps and added to HomeKit');
this.accessory.context.isexternal = this.config.externalaccessory;
this.createServices();
this.applyCallbacks();
}
} catch (e) {
this.log(e);
}
}
// get free channel identifier
getFreeIdentifier() {
var id = 1;
var keys = [...this.inputSourceMap.keys()];
while (keys.includes(id)) {
id++;
}
return id;
}
// start checking for registration and start polling status
start() {
this.checkRegistration();
this.updateStatus();
}
// get the services (TV service, channels) from a restored HomeKit accessory
grabServices(accessory) {
const self = this;
// FIXME: Hack, using subtype to store URI for channel
accessory.services.forEach(service => {
if ((service.subtype !== undefined) && service.testCharacteristic(Characteristic.Identifier)) {
var identifier = service.getCharacteristic(Characteristic.Identifier).value;
self.inputSourceMap.set(identifier, service);
self.uriToInputSource.set(service.subtype, service);
self.channelServices.push(service);
}
});
this.services = [];
this.tvService = accessory.getService(Service.Television);
this.services.push(this.tvService);
this.speakerService = accessory.getService(Service.TelevisionSpeaker);
this.services.push(this.speakerService);
return this.services;
}
// create the television service for a new TV accessory
createServices() {
/// sony/system/
// ["getSystemInformation",[],["{\"product\":\"string\", \"region\":\"string\", \"language\":\"string\", \"model\":\"string\", \"serial\":\"string\", \"macAddr\":\"string\", \"name\":\"string\", \"generation\":\"string\", \"area\":\"string\", \"cid\":\"string\"}"],"1.0"]
this.tvService = new Service.Television(this.name);
this.services.push(this.tvService);
this.speakerService = new Service.TelevisionSpeaker();
this.services.push(this.speakerService);
// TODO: information services
// var informationService = new Service.AccessoryInformation();
// informationService
// .setCharacteristic(Characteristic.Manufacturer, "Sony")
// .setCharacteristic(Characteristic.Model, "Android TV")
// .setCharacteristic(Characteristic.SerialNumber, "12345");
// this.services.push(informationService);
return this.services;
}
// sets the callbacks for the homebridge services to call the functions of this TV instance
applyCallbacks() {
this.tvService.setCharacteristic(Characteristic.ConfiguredName, this.name);
this.tvService
.setCharacteristic(
Characteristic.SleepDiscoveryMode,
Characteristic.SleepDiscoveryMode.ALWAYS_DISCOVERABLE
);
this.tvService
.getCharacteristic(Characteristic.Active)
.on('set', this.setPowerState.bind(this))
this.tvService.setCharacteristic(Characteristic.ActiveIdentifier, 0);
this.tvService
.getCharacteristic(Characteristic.ActiveIdentifier)
.on('set', this.setActiveIdentifier.bind(this))
.on('get', this.getActiveIdentifier.bind(this));
this.tvService
.getCharacteristic(Characteristic.RemoteKey)
.on('set', this.setRemoteKey.bind(this));
this.speakerService
.setCharacteristic(Characteristic.Active, Characteristic.Active.ACTIVE);
this.speakerService
.setCharacteristic(Characteristic.Name, this.soundoutput);
this.speakerService
.setCharacteristic(Characteristic.VolumeControlType, Characteristic.VolumeControlType.ABSOLUTE);
this.speakerService
.getCharacteristic(Characteristic.VolumeSelector) // increase/decrease volume
.on('set', this.setVolumeSelector.bind(this));
this.speakerService
.getCharacteristic(Characteristic.Mute)
.on('get', this.getMuted.bind(this))
.on('set', this.setMuted.bind(this));
this.speakerService.getCharacteristic(Characteristic.Volume)
.on('get', this.getVolume.bind(this))
.on('set', this.setVolume.bind(this));
}
// Do TV status check every 5 seconds
updateStatus() {
var that = this;
setTimeout(function () {
that.getPowerState(null);
that.pollPlayContent();
that.updateStatus();
}, this.updaterate);
}
// Check if we already registered with the TV
checkRegistration() {
const self = this;
this.registercheck = true;
var clientId = 'HomeBridge-Bravia' + ':' + this.accessory.context.uuid;
var post_data = '{"id":8,"method":"actRegister","version":"1.0","params":[{"clientid":"' + clientId + '","nickname":"homebridge"},[{"clientid":"' + clientId + '","value":"yes","nickname":"homebridge","function":"WOL"}]]}';
var onError = function (err) {
self.log('Error: ', err);
return false;
};
var onSucces = function (chunk) {
if (chunk.indexOf('"error"') >= 0) {
if (self.debug)
self.log('Error? ', chunk);
}
if (chunk.indexOf('[]') < 0) {
self.log('Need to authenticate with TV!');
self.log('Please enter the PIN that appears on your TV at http://' + os.hostname() + ':' + self.serverPort);
self.server = http.createServer(function (req, res) {
var urlObject = url.parse(req.url, true, false);
if (urlObject.query.pin) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body>PIN ' + urlObject.query.pin + ' sent</body></html>');
self.pwd = urlObject.query.pin;
self.server.close();
self.checkRegistration();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><form action="/"><label for="pin">Enter PIN:</label><br><input type="text" id="pin" name="pin"><input type="submit" value="Submit"></form></body></html>');
res.end();
}
});
self.server.listen(self.serverPort, function () {
self.log('PIN entry web server listening');
});
self.server.on('error', function (err) {
self.log('PIN entry web server error:', err);
});
} else {
self.authok = true;
self.receiveSources(true);
}
};
self.makeHttpRequest(onError, onSucces, '/sony/accessControl/', post_data, false);
}
// creates homebridge service for TV input
addInputSource(name, uri, type, configuredName = null, identifier = null) {
// FIXME: Using subtype to store URI, hack!
if (identifier === null)
identifier = this.getFreeIdentifier();
if (configuredName === null)
configuredName = name;
var inputSource = new Service.InputSource(name, uri); // displayname, subtype?
inputSource.setCharacteristic(Characteristic.Identifier, identifier)
.setCharacteristic(Characteristic.ConfiguredName, configuredName)
.setCharacteristic(Characteristic.CurrentVisibilityState, Characteristic.CurrentVisibilityState.SHOWN)
.setCharacteristic(Characteristic.IsConfigured, Characteristic.IsConfigured.CONFIGURED)
.setCharacteristic(Characteristic.InputSourceType, type);
this.channelServices.push(inputSource);
this.tvService.addLinkedService(inputSource);
this.uriToInputSource.set(uri, inputSource);
this.inputSourceMap.set(identifier, inputSource);
this.accessory.addService(inputSource);
this.log('Added input ' + name); // +" with URI "+uri);
}
haveChannel(source) {
return this.scannedChannels.find(channel => (
(source.subtype == channel[1]) &&
(source.getCharacteristic(Characteristic.InputSourceType).value == channel[2])
)) !== undefined;
}
haveInputSource(name, uri, type) {
return this.channelServices.find(source => (
(source.subtype == uri) &&
(source.getCharacteristic(Characteristic.InputSourceType).value == type)
)) !== undefined;
}
// save channels to file for external accessories
saveChannelsToFile() {
const storeObject = [];
this.channelServices.forEach(service => {
storeObject.push({
identifier: service.getCharacteristic(Characteristic.Identifier).value,
name: service.getCharacteristic(Characteristic.Name).value,
configuredName: service.getCharacteristic(Characteristic.ConfiguredName).value,
uri: service.subtype,
type: service.getCharacteristic(Characteristic.InputSourceType).value
});
});
try {
const data = JSON.stringify(storeObject);
fs.writeFileSync(STORAGE_PATH + '/sonytv-channels-' + this.name + '.json', data);
if (this.debug)
this.log('Stored channels in external storage');
} catch (e) {
this.log(e);
}
}
// load channels from file for external accessories
loadChannelsFromFile() {
const self = this;
const channelsPath = STORAGE_PATH + '/sonytv-channels-' + this.name + '.json';
try {
if (fs.existsSync(channelsPath)) {
const rawdata = fs.readFileSync(channelsPath);
const storeObject = JSON.parse(rawdata);
storeObject.forEach(source => {
self.scannedChannels.push([source.name, source.uri, source.type]);
self.addInputSource(source.name, source.uri, source.type, source.configuredName, source.identifier);
});
if (this.debug)
this.log('Loaded channels from external storage');
}
} catch (e) {
this.log(e);
}
}
// syncs the channels and publishes/updates the TV accessory for HomeKit
syncAccessory() {
const self = this;
var changeDone = false;
// add new channels
this.scannedChannels.forEach(channel => {
if (!self.haveInputSource(channel[0], channel[1], channel[2])) {
self.addInputSource(channel[0], channel[1], channel[2]);
changeDone = true;
}
});
// remove old channels
this.channelServices.forEach((service, idx, obj) => {
if (!self.haveChannel(service)) {
// TODO: make this function?
self.tvService.removeLinkedService(service);
self.accessory.removeService(service);
self.inputSourceMap.delete(service.getCharacteristic(Characteristic.Identifier).value);
self.uriToInputSource.delete(service.subtype);
self.log('Removing nonexisting channel ' + service.getCharacteristic(Characteristic.ConfiguredName).value);
obj.splice(idx, 1);
changeDone = true;
}
});
if (!this.accessory.context.isRegisteredInHomeKit) {
// add base services that haven't been added yet
this.services.forEach(service => {
try {
if (!self.accessory.services.includes(service)) {
self.log('Adding base service to accessory');
self.accessory.addService(service);
changeDone = true;
}
} catch (e) {
self.log('Can\'t add service!');
self.log(e);
}
});
this.log('Registering HomeBridge Accessory for ' + this.name);
this.accessory.context.isRegisteredInHomeKit = true;
if (!this.accessory.context.isexternal) {
this.platform.api.registerPlatformAccessories('homebridge-bravia', 'BraviaPlatform', [this.accessory]);
} else {
try {
const data = JSON.stringify(this.accessory.context);
fs.writeFileSync(STORAGE_PATH + '/sonytv-context-' + this.accessory.context.config.name + '.json', data);
} catch (e) {
this.log(e);
}
this.platform.api.publishExternalAccessories('homebridge-bravia', [this.accessory]);
}
} else if (changeDone) {
this.log('Updating HomeBridge Accessory for ' + this.name);
this.platform.api.updatePlatformAccessories([this.accessory]);
}
if (this.accessory.context.isexternal) {
this.saveChannelsToFile();
}
this.receivingSources = false;
}
// initialize a scan for new sources
receiveSources(checkPower = null) {
if (checkPower === null)
checkPower = this.power;
if (!this.receivingSources && checkPower) {
const that = this;
this.inputSourceList = [];
this.sources.forEach(function (sourceName) {
that.inputSourceList.push(new InputSource(sourceName, getSourceType(sourceName)));
});
if (!isNull(this.tvsource)) {
this.inputSourceList.push(new InputSource(this.tvsource, getSourceType(this.tvsource)));
}
this.receivingSources = true;
this.scannedChannels = [];
this.receiveNextSources();
}
if (this.channelupdaterate)
setTimeout(this.receiveSources.bind(this), this.channelupdaterate);
}
// receive the next sources in the inputSourceList, register accessory if all have been received
receiveNextSources() {
if (this.inputSourceList.length == 0) {
if (this.useApps && !this.appsLoaded) {
this.receiveApplications();
} else {
this.syncAccessory();
}
return;
}
var source = this.inputSourceList.shift();
if (!isNull(source)) {
this.receiveSource(source.name, source.type);
}
}
// TV http call to receive input list for source
receiveSource(sourceName, sourceType) {
const that = this;
var onError = function (err) {
if (that.debug)
that.log('Error loading sources for ' + sourceName);
if (that.debug)
that.log(err);
that.receiveNextSources();
};
var onSucces = function (data) {
try {
if (data.indexOf('"error"') < 0) {
var jayons = JSON.parse(data);
var reslt = jayons.result[0];
reslt.forEach(function (source) {
that.scannedChannels.push([source.title, source.uri, sourceType]);
});
} else if (that.debug) {
that.log('Can\'t load sources for ' + sourceName);
that.log('TV response:');
that.log(data);
}
} catch (e) {
if (that.debug)
that.log(e);
}
that.receiveNextSources();
};
var post_data = '{"id":13,"method":"getContentList","version":"1.0","params":[{ "source":"' + sourceName + '","stIdx": 0}]}';
that.makeHttpRequest(onError, onSucces, '/sony/avContent', post_data, false);
}
// TV https call to receive application list
receiveApplications() {
const that = this;
var onError = function (err) {
if (that.debug)
that.log('Error loading applications:');
if (that.debug)
that.log(err);
that.syncAccessory();
};
var onSucces = function (data) {
try {
if (data.indexOf('"error"') < 0) {
var jayons = JSON.parse(data);
var reslt = jayons.result[0];
reslt.sort(source => source.title).forEach(function (source) {
if (that.applications.length == 0 || that.applications.map(app => app.title).filter(title => source.title.includes(title)).length > 0) {
that.scannedChannels.push([source.title, source.uri, Characteristic.InputSourceType.APPLICATION]);
} else {
// that.log('Ignoring application: ' + source.title);
}
});
} else if (that.debug) {
that.log('Can\'t load applications.');
that.log('TV response:');
that.log(data);
}
} catch (e) {
if (that.debug)
that.log(e);
}
that.syncAccessory();
};
var post_data = '{"id":13,"method":"getApplicationList","version":"1.0","params":[]}';
that.makeHttpRequest(onError, onSucces, '/sony/appControl', post_data, false);
}
// TV http call to poll play content
pollPlayContent() {
// TODO: check app list if no play content for currentUri
const that = this;
var post_data = '{"id":13,"method":"getPlayingContentInfo","version":"1.0","params":[]}';
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(that.currentUri)) {
that.currentUri = null;
that.tvService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(0);
}
};
var onSucces = function (chunk) {
if (chunk.indexOf('"error"') >= 0) {
// happens when TV display is off
if (!isNull(that.currentUri)) {
that.currentUri = null;
that.tvService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(0);
}
} else {
try {
var jason = JSON.parse(chunk);
if (!isNull(jason) && jason.result) {
var result = jason.result[0];
var uri = result.uri;
if (that.currentUri != uri) {
that.currentUri = uri;
var inputSource = that.uriToInputSource.get(uri);
if (inputSource) {
var id = inputSource.getCharacteristic(Characteristic.Identifier).value;
if (!isNull(inputSource)) {
that.tvService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(id);
}
}
}
}
} catch (e) {
if (!isNull(that.currentUri)) {
that.currentUri = null;
that.tvService.getCharacteristic(Characteristic.ActiveIdentifier).updateValue(0);
}
if (that.debug)
that.log('Can\'t poll play content', e);
}
}
};
that.makeHttpRequest(onError, onSucces, '/sony/avContent/', post_data, false);
}
// TV http call to set play content
setPlayContent(uri) {
const that = this;
var post_data = '{"id":13,"method":"setPlayContent","version":"1.0","params":[{ "uri": "' + uri + '" }]}';
var onError = function (err) {
that.log('Error setting play content: ', err);
};
var onSucces = function (chunk) {
};
that.makeHttpRequest(onError, onSucces, '/sony/avContent/', post_data, true);
}
// TV http call to set the active app
setActiveApp(uri) {
const that = this;
var post_data = '{"id":13,"method":"setActiveApp","version":"1.0","params":[{"uri":"' + uri + '"}]}';
var onError = function (err) {
that.log('Error setting active app: ', err);
};
var onSucces = function (data) {
};
that.makeHttpRequest(onError, onSucces, '/sony/appControl', post_data, true);
}
// homebridge callback to get current channel identifier
getActiveIdentifier(callback) {
var uri = this.currentUri;
if (!isNull(uri)) {
var inputSource = this.uriToInputSource.get(uri);
if (inputSource) {
var id = inputSource.getCharacteristic(Characteristic.Identifier).value;
if (!isNull(inputSource)) {
if (!isNull(callback))
callback(null, id);
return;
}
}
}
if (!isNull(callback))
callback(null, 0);
}
// homebridge callback to set current channel
setActiveIdentifier(identifier, callback) {
var inputSource = this.inputSourceMap.get(identifier);
if (inputSource && inputSource.testCharacteristic(Characteristic.InputSourceType)) {
if (inputSource.getCharacteristic(Characteristic.InputSourceType).value == Characteristic.InputSourceType.APPLICATION) {
this.setActiveApp(inputSource.subtype);
} else {
this.setPlayContent(inputSource.subtype);
}
}
if (!isNull(callback))
callback(null);
}
// homebridge callback to set volume via selector (up/down)
setVolumeSelector(key, callback) {
const that = this;
var value = '';
var onError = function (err) {
that.log(err);
if (!isNull(callback))
callback(null);
};
var onSucces = function (data) {
if (!isNull(callback))
callback(null);
};
switch (key) {
case Characteristic.VolumeSelector.INCREMENT: // Volume up
value = 'AAAAAQAAAAEAAAASAw==';
break;
case Characteristic.VolumeSelector.DECREMENT: // Volume down
value = 'AAAAAQAAAAEAAAATAw==';
break;
}
var post_data = that.createIRCC(value);
that.makeHttpRequest(onError, onSucces, '', post_data, false);
}
// homebridge callback to set pressed key
setRemoteKey(key, callback) {
var value = '';
var that = this;
var onError = function (err) {
that.log(err);
if (!isNull(callback))
callback(null);
};
var onSucces = function (data) {
if (!isNull(callback))
callback(null);
};
// https://gist.github.com/joshluongo/51dcfbe5a44ee723dd32
switch (key) {
case Characteristic.RemoteKey.REWIND:
value = 'AAAAAgAAAJcAAAAbAw==';
break;
case Characteristic.RemoteKey.FAST_FORWARD:
value = 'AAAAAgAAAJcAAAAcAw==';
break;
case Characteristic.RemoteKey.NEXT_TRACK:
value = 'AAAAAgAAAJcAAAA9Aw==';
break;
case Characteristic.RemoteKey.PREVIOUS_TRACK:
value = 'AAAAAgAAAJcAAAB5Aw==';
break;
case Characteristic.RemoteKey.ARROW_UP:
value = 'AAAAAQAAAAEAAAB0Aw==';
break;
case Characteristic.RemoteKey.ARROW_DOWN:
value = 'AAAAAQAAAAEAAAB1Aw==';
break;
case Characteristic.RemoteKey.ARROW_LEFT:
value = 'AAAAAQAAAAEAAAA0Aw==';
break;
case Characteristic.RemoteKey.ARROW_RIGHT:
value = 'AAAAAQAAAAEAAAAzAw==';
break;
case Characteristic.RemoteKey.SELECT:
value = 'AAAAAQAAAAEAAABlAw==';
break;
case Characteristic.RemoteKey.BACK:
value = 'AAAAAgAAAJcAAAAjAw==';
break;
case Characteristic.RemoteKey.EXIT:
value = 'AAAAAQAAAAEAAABjAw==';
break;
case Characteristic.RemoteKey.PLAY_PAUSE:
value = 'AAAAAgAAAJcAAAAaAw==';
break;
case Characteristic.RemoteKey.INFORMATION:
value = 'AAAAAQAAAAEAAAA6Aw==';
break;
}
var post_data = that.createIRCC(value);
that.makeHttpRequest(onError, onSucces, '', post_data, false);
}
// homebridge callback to get muted state
getMuted(callback) {
var that = this;
if (!that.power) {
if (!isNull(callback))
callback(null, 0);
return;
}
var post_data = '{"id":4,"method":"getVolumeInformation","version":"1.0","params":[]}';
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null, false);
};
var onSucces = function (chunk) {
if (chunk.indexOf('"error"') >= 0) {
if (that.debug)
that.log('Error? ', chunk);
if (!isNull(callback))
callback(null, false);
return;
}
var _json = null;
try {
_json = JSON.parse(chunk);
} catch (e) {
if (!isNull(callback))
callback(null, false);
return;
}
if (isNull(_json.result)) {
if (!isNull(callback))
callback(null, false);
return;
}
for (var i = 0; i < _json.result[0].length; i++) {
var volume = _json.result[0][i].volume;
var typ = _json.result[0][i].target;
if (typ === that.soundoutput) {
if (!isNull(callback))
callback(null, _json.result[0][i].mute);
return;
}
}
if (!isNull(callback))
callback(null, false);
};
that.makeHttpRequest(onError, onSucces, '/sony/audio/', post_data, false);
}
// homebridge callback to set muted state
setMuted(muted, callback) {
var that = this;
if (!that.power) {
if (!isNull(callback))
callback(null);
return;
}
var merterd = muted ? 'true' : 'false';
var post_data = '{"id":13,"method":"setAudioMute","version":"1.0","params":[{"status":' + merterd + '}]}';
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null);
};
var onSucces = function (chunk) {
if (chunk.indexOf('"error"') >= 0) {
if (that.debug)
that.log('Error? ', chunk);
}
if (!isNull(callback))
callback(null);
};
that.makeHttpRequest(onError, onSucces, '/sony/audio/', post_data, false);
}
// homebridge callback to get absoluet volume
getVolume(callback) {
var that = this;
if (!that.power) {
if (!isNull(callback))
callback(null, 0);
return;
}
var post_data = '{"id":4,"method":"getVolumeInformation","version":"1.0","params":[]}';
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null, 0);
};
var onSucces = function (chunk) {
if (chunk.indexOf('"error"') >= 0) {
if (that.debug)
that.log('Error? ', chunk);
if (!isNull(callback))
callback(null, 0);
return;
}
var _json = null;
try {
_json = JSON.parse(chunk);
} catch (e) {
if (!isNull(callback))
callback(null, 0);
return;
}
if (isNull(_json.result)) {
if (!isNull(callback))
callback(null, 0);
return;
}
for (var i = 0; i < _json.result[0].length; i++) {
var volume = _json.result[0][i].volume;
var typ = _json.result[0][i].target;
if (typ === that.soundoutput) {
if (!isNull(callback))
callback(null, volume);
return;
}
}
if (!isNull(callback))
callback(null, 0);
};
that.makeHttpRequest(onError, onSucces, '/sony/audio/', post_data, false);
}
// homebridge callback to set absolute volume
setVolume(volume, callback) {
var that = this;
if (!that.power) {
if (!isNull(callback))
callback(null);
return;
}
var post_data = '{"id":13,"method":"setAudioVolume","version":"1.0","params":[{"target":"' + that.soundoutput + '","volume":"' + volume + '"}]}';
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null);
};
var onSucces = function (chunk) {
if (!isNull(callback))
callback(null);
};
that.makeHttpRequest(onError, onSucces, '/sony/audio/', post_data, false);
}
// homebridge callback to get power state
getPowerState(callback) {
var that = this;
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null, false);
that.updatePowerState(false);
};
var onSucces = function (chunk) {
var _json = null;
try {
_json = JSON.parse(chunk);
if (!isNull(_json) && !isNull(_json.result[0]) && _json.result[0].status === 'active') {
that.updatePowerState(true);
if (!isNull(callback))
callback(null, true);
} else {
that.updatePowerState(false);
if (!isNull(callback))
callback(null, false);
}
} catch (e) {
if (that.debug)
console.log(e);
that.updatePowerState(false);
if (!isNull(callback))
callback(null, false);
}
};
try {
var post_data = '{"id":2,"method":"getPowerStatus","version":"1.0","params":[]}';
that.makeHttpRequest(onError, onSucces, '/sony/system/', post_data, false);
} catch (globalExcp) {
if (that.debug)
console.log(globalExcp);
that.updatePowerState(false);
if (!isNull(callback))
callback(null, false);
}
}
// homebridge callback to set power state
setPowerState(state, callback) {
var that = this;
var onError = function (err) {
if (that.debug)
that.log('Error: ', err);
if (!isNull(callback))
callback(null);
};
var onSucces = function (chunk) {
if (!isNull(callback))
callback(null);
};
var onWol = function (error) {
if (error)
that.log('Error when sending WOL packets', error);
if (!isNull(callback))
callback(null);
};
if (state) {
if (!isNull(this.mac)) {
wol.wake(this.mac, {address: this.woladdress}, onWol);
} else {
var post_data = '{"id":2,"method":"setPowerStatus","version":"1.0","params":[{"status":true}]}';
that.makeHttpRequest(onError, onSucces, '/sony/system/', post_data, false);
}
} else {
if (!isNull(this.mac)) {
var post_data = this.createIRCC('AAAAAQAAAAEAAAAvAw==');
this.makeHttpRequest(onError, onSucces, '', post_data, false);
} else {
var post_data = '{"id":2,"method":"setPowerStatus","version":"1.0","params":[{"status":false}]}';
that.makeHttpRequest(onError, onSucces, '/sony/system/', post_data, false);
}
}
}
// sends the current power state to homebridge
updatePowerState(state) {
if (this.power != state) {
this.power = state;
this.tvService.getCharacteristic(Characteristic.Active).updateValue(this.power);
}
}
// make http request to TV
makeHttpRequest(errcallback, resultcallback, url, post_data, canTurnTvOn) {
var that = this;
var data = '';
if (isNull(canTurnTvOn)) {canTurnTvOn = false;}
if (!that.power && canTurnTvOn) {
that.setPowerState(true, null);
var timeout = that.starttimeout;
setTimeout(function () {
that.makeHttpRequest(errcallback, resultcallback, url, post_data, false);
}, timeout);
return;
}
var post_options = that.getPostOptions(url);
var post_req = http.request(post_options, function (res) {
that.setCookie(res.headers);
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
if (!isNull(resultcallback)) {
resultcallback(data);
}
});
});
try {
post_req.on('error', function (err) {
if (!isNull(errcallback)) {
errcallback(err);
}
});
post_req.write(post_data);
post_req.end();
} catch (e) {
if (!isNull(errcallback)) {
errcallback(e);
}
}
}
// helper to create IRCC command string
createIRCC(command) {
return '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1"><IRCCCode>' + command + '</IRCCCode></u:X_SendIRCC></s:Body></s:Envelope>';
}
// helper to apply post options to http request
getPostOptions(url) {
var that = this;
if (url == '')
url = '/sony/IRCC';
var post_options = null;
if (that.comp == 'true') {
post_options = {
host: 'closure-compiler.appspot.com',
port: '80',
path: url,
method: 'POST',
headers: {}
};
} else {
post_options = {
host: that.ip,
port: that.port,
path: url,