forked from nfarina/homebridge-sonos
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
1395 lines (1174 loc) · 44.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
var sonos = require('sonos');
var Sonos = require('sonos').Sonos;
var Listener = require('sonos/lib/events/listener');
var xml2js = require('xml2js');
var _ = require('underscore');
var inherits = require('util').inherits;
var url = require('url');
var PlatformAccessory, Service, Characteristic, UUIDGen, VolumeCharacteristic;
module.exports = function (homebridge) {
PlatformAccessory = homebridge.platformAccessory;
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
// we can only do this after we receive the homebridge API object
makeVolumeCharacteristic();
// Dynamically create accessories
homebridge.registerPlatform('homebridge-sonos', 'Sonos', SonosPlatform, true);
};
// SonosPlatform handles device discovery and various events
function SonosPlatform(log, config, api) {
this.log = log;
this.config = _.extend({
port: 50200,
suffix: ' Speaker',
spotify_rincon_id: '2311',
scenes: {}
}, config);
this.api = api;
this.unregisterCachedAccessories = [];
// {zone: accessory}
this.accessories = new Map();
// {host: device}
this.devices = new Map();
// {group: coordinatorDevice}
this.groups = new Map();
// {group: {host: device}}
this.groupMembers = new Map();
// {name: accessory}
this.sceneAccessories = new Map();
// {zone: {name: accessory}}
this.zoneSceneAccessories = new Map();
this.api.on('didFinishLaunching', this._didFinishLaunching.bind(this));
}
// Homebridge has finished launching and restoring cached accessories, start
// discovery processes
SonosPlatform.prototype._didFinishLaunching = function() {
// Global listener we receive notifications from Sonos devices on
this.listener = new Listener(undefined, {port: this.config.port});
this.listener.listen(function (listenErr) {
if (listenErr) {
throw new Error('Failed to initialise event listener for homebridge-sonos');
}
this.listener.on('serviceEvent', this._processEvent.bind(this));
// Don't start searching until listener is ready for event registrations
this.log('Searching for Sonos devices');
sonos.search({port: this.config.port}, this._processDiscovery.bind(this));
}.bind(this));
// Remove unwanted cached accessories
if (this.unregisterCachedAccessories.length !== 0) {
this.api.unregisterPlatformAccessories('homebridge-sonos', 'Sonos', this.unregisterCachedAccessories);
this.unregisterCachedAccessories = [];
}
// Do we have any missing scene accessories?
for (var name in this.config.scenes) {
var sceneAccessory = this.sceneAccessories.get(name);
if (sceneAccessory) {
continue;
}
new SonosSceneAccessory(
this,
this._createLogger('Scene:' + name),
name,
this.config.scenes[name]
);
}
// TODO: Handle devices that are REMOVED from the network and cleanup structures
};
// Configure a cached accessory
SonosPlatform.prototype.configureAccessory = function (platformAccessory) {
if (platformAccessory.context.type == 'SonosSceneAccessory') {
var sceneConfig = this.config.scenes[platformAccessory.context.name];
if (!sceneConfig) {
this.unregisterCachedAccessories.push(platformAccessory);
return;
}
new SonosSceneAccessory(
this,
this._createLogger('Scene:' + platformAccessory.context.name),
platformAccessory.context.name,
sceneConfig,
platformAccessory
);
return;
}
if (platformAccessory.context.type == 'SonosAccessory') {
new SonosAccessory(
this,
this._createLogger(platformAccessory.context.name),
platformAccessory.context.name,
platformAccessory.context.zone,
platformAccessory
);
return;
}
// Unknown accessory type
this.unregisterCachedAccessories.push(platformAccessory);
};
// Update reachability of an accessory that we found and any associated scene
// accessories
SonosPlatform.prototype._updateReachability = function (accessory, value) {
if (value === accessory.platformAccessory.reachable) {
return;
}
if (value) {
accessory.log('Accessory is now reachable');
} else {
accessory.log('Accessory is no longer reachable');
}
accessory.platformAccessory.updateReachability(value);
// Process scene accessories
var sceneList = this.zoneSceneAccessories.get(accessory.zone);
if (!sceneList) {
return;
}
sceneList.forEach(function (sceneAccessory) {
if (value === sceneAccessory.platformAccessory.reachable) {
return;
}
if (value) {
sceneAccessory.log('Accessory is now reachable');
sceneAccessory.platformAccessory.updateReachability(true);
return;
}
// Before removing reachability - check if any other zones are available
this._updateSceneUnreachability(sceneAccessory, accessory.zone);
}.bind(this));
};
// Check that there is still a reachable zone in the scene, removing reachability
// if there is not
SonosPlatform.prototype._updateSceneUnreachability = function (sceneAccessory, unreachableZone) {
var isReachable = false;
for (var i in sceneAccessory.sceneConfig.zones) {
var zone = sceneAccessory.sceneConfig.zones[i];
if (zone == unreachableZone) {
continue;
}
var zoneAccessory = this.accessories.get(zone);
if (!zoneAccessory || !zoneAccessory.device) {
continue;
}
isReachable = true;
break;
}
if (isReachable) {
return;
}
sceneAccessory.log('Accessory is no longer reachable');
sceneAccessory.platformAccessory.updateReachability(false);
};
// Create a logger for an accessory
SonosPlatform.prototype._createLogger = function (prefix) {
var log = this.log;
return function () {
var args = Array.from(arguments);
args[0] = '[' + prefix + '] ' + args[0];
log.apply(null, args);
};
};
// Logging helper - will log device messages under its accessory if it has one
SonosPlatform.prototype._log = function (deviceData) {
var args = Array.from(arguments).slice(1);
if (deviceData.accessory) {
deviceData.accessory.log.apply(deviceData.accessory.log, args);
return;
}
this.log.apply(null, args);
};
// Search for devices on the local network
SonosPlatform.prototype._processDiscovery = function (device, model) {
this.log('Found device at %s', device.host);
if (this.devices.get(device.host)) {
// We know this device already
return;
}
// Process this new device's topology, adding all other devices from it and
// registering event handlers
this.updateTopology(device);
};
// Process group management events that occur when group changes happen
SonosPlatform.prototype._processEvent = function (endpoint, sid, eventData, device) {
if (endpoint == '/GroupManagement/Event') {
// A group management event occurred - check for topology changes
// TODO: We receive events multiple times, once from each device -
// an optimisation would be to track which devices know each other
// (would that be ALL on the network?) and only register for
// group events one time
this.updateTopology(device);
return;
}
var deviceData = this.devices.get(device.host);
if (!deviceData) {
this.log('Event received from undiscovered device at %s', device.host);
return;
} else if (!deviceData.accessory) {
this.log('Event received from device without accessory at %s', device.host);
return;
}
this._parseEvent(eventData, function (err, eventStruct) {
if (err) {
this._log(deviceData, 'Invalid event received: %s', err);
return;
}
if (endpoint == '/MediaRenderer/AVTransport/Event') {
// Ignore if not coordinator - probably means this device just left the
// group and is now coordinating another group. So let's let the topology
// update happen which will request another event by re-registering
if (deviceData.coordinator !== 'true') {
this._log(deviceData, 'Ignoring AV event from non-coordinator device');
return;
}
// Play state change event occurred
this._processAVEvent(deviceData, eventStruct);
return;
}
if (endpoint == '/MediaRenderer/RenderingControl/Event') {
// Volume change event occurred
this._processRenderingEvent(deviceData, eventStruct);
return;
}
}.bind(this));
};
// Process an event structure and parse the XML
SonosPlatform.prototype._parseEvent = function (eventData, callback) {
// Validate the event structure
if (!eventData.LastChange) {
callback(new Error('Invalid event structure received'));
return;
}
// Parse XML
(new xml2js.Parser()).parseString(eventData.LastChange, function (err, didl) {
if (err) {
callback(err);
return;
}
callback(null, didl.Event.InstanceID[0]);
});
};
// Process topology data for a device
SonosPlatform.prototype.updateTopology = function (device, callback) {
this.log('Starting topology update from device at %s', device.host);
device.getTopology(function (err, topology) {
if (err || !topology) {
this.log('Topology update from device at %s failed: %s', device.host, err);
callback(err ? err : new Error('Invalid topology data'));
return;
}
// For each zone, register the device or update the name, group and coordinator
// and for new devices setup event handlers
topology.zones.forEach(function (topologyZone) {
var urlObj = url.parse(topologyZone.location),
host = urlObj.hostname,
port = urlObj.port,
deviceData = this.devices.get(host);
if (!deviceData) {
// New device, setup initial data, the rest will be updated below
deviceData = {
host: host,
port: port,
sonos: new Sonos(host, port),
// The following are stubs that document the available data
name: undefined,
coordinator: undefined,
queueUri: '',
trackUri: '',
group: undefined,
uuid: undefined,
updateTimeout: undefined
};
// Register for events and store the new device
this.listener.addService('/GroupManagement/Event', function () {}, deviceData.sonos);
this.listener.addService('/MediaRenderer/AVTransport/Event', function () {}, deviceData.sonos);
this.listener.addService('/MediaRenderer/RenderingControl/Event', function () {}, deviceData.sonos);
this.devices.set(host, deviceData);
this.log('Registered new device at %s:%s', host, port);
}
this._log(deviceData, 'Processing topology for device at %s', host);
// Set/update zone name for this device and associated accessory
if (topologyZone.name !== deviceData.name) {
var accessory = this.accessories.get(topologyZone.name);
if (deviceData.accessory) {
deviceData.accessory.log('Associated device has been renamed to zone %s - accessory is now unavailable', topologyZone.name);
deviceData.accessory.setDeviceData(undefined);
this._updateReachability(deviceData.accessory, false);
}
if (accessory) {
this._updateReachability(accessory, true);
} else {
accessory = new SonosAccessory(
this,
this._createLogger(topologyZone.name),
topologyZone.name + this.config.suffix,
topologyZone.name
);
}
deviceData.name = topologyZone.name;
deviceData.accessory = accessory;
if (accessory.device) {
accessory.log('Associated device has changed from %s to %s', accessory.device.host, host);
accessory.device.accessory = undefined;
} else {
accessory.log('Associated device discovered at %s', host);
}
accessory.setDeviceData(deviceData);
}
// Set/update the group information - and the group map that locates coordinators
if (topologyZone.coordinator !== deviceData.coordinator) {
if (deviceData.coordinator === 'true') {
this._log(deviceData, 'Device in zone %s is no longer the coordinator of group %s', deviceData.name, deviceData.group);
this.groups.delete(deviceData.group);
deviceData.queueUri = '';
}
deviceData.coordinator = topologyZone.coordinator;
if (deviceData.coordinator === 'true') {
var previousCoordinator = this.groups.get(topologyZone.group);
if (previousCoordinator) {
// Ensure we lose the coordinator flag on the previous coordinator as
// otherwise if we encounter the flag change after this we'll corrupt indexes
this._log(previousCoordinator, 'Device in zone %s is no longer coordinator of group %s', previousCoordinator.name, topologyZone.group);
previousCoordinator.coordinator = 'false';
} else {
this._log(deviceData, 'Device in zone %s is now coordinator of group %s', deviceData.name, topologyZone.group);
}
this.groups.set(topologyZone.group, deviceData);
}
}
if (topologyZone.group !== deviceData.group) {
var groupList,
coordinator = this.groups.get(topologyZone.group);
if (deviceData.group) {
groupList = this.groupMembers.get(deviceData.group);
this._log(deviceData, 'Device in zone %s is no longer a member of group %s', deviceData.name, deviceData.group);
if (groupList) {
groupList.delete(deviceData.host);
if (groupList.size === 0) {
this.groupMembers.delete(deviceData.group);
}
}
var previousGroupCoordinator = this.groups.get(deviceData.group);
if (previousGroupCoordinator) {
// If the old coordinator is the same as this one - move it
if (previousGroupCoordinator.host == deviceData.host) {
this.groups.delete(deviceData.group);
this.groups.set(topologyZone.group, deviceData);
coordinator = previousGroupCoordinator;
} else {
// Request a new AV event for the previous group's coordinator as possibly
// some of the playlist accessories need turning on if the topology now matches
this.listener.addService('/MediaRenderer/AVTransport/Event', function () {}, previousGroupCoordinator.sonos);
}
}
}
deviceData.group = topologyZone.group;
groupList = this.groupMembers.get(deviceData.group);
if (!groupList) {
groupList = new Map();
this.groupMembers.set(deviceData.group, groupList);
}
groupList.set(deviceData.host, deviceData);
if (!coordinator) {
this._log(deviceData, 'Device in zone %s is now a member of group %s with no known coordinator', deviceData.name, deviceData.group);
} else {
this._log(deviceData, 'Device in zone %s is now a member of group %s with coordinator in zone %s', deviceData.name, deviceData.group, coordinator.name);
// Trigger a fresh event from the coordinator so we update power states of this device
// correctly as it may have sent its AV event before we updated topology, and it would
// have been dropped due to it not being a coordinator
this.listener.addService('/MediaRenderer/AVTransport/Event', function () {}, coordinator.sonos);
}
}
if (topologyZone.uuid != deviceData.uuid) {
deviceData.uuid = topologyZone.uuid;
this._log(deviceData, 'Device in zone %s is now UUID %s', deviceData.name, deviceData.uuid);
}
}.bind(this));
// In some cases there is a race where we see a snapshot of the topology
// in flex due to early group change events, but won't see another group
// change event, and we then end up with a cache of an invalid topology
// To prevent this, verify that we have a coordinator for everything, and
// request another topology update in a few seconds
// Furthermore, update topology frequently just in case
topology.zones.forEach(function (topologyZone) {
var coordinator = this.groups.get(topologyZone.group);
if (!coordinator) {
var firstDevice = this.groupMembers.get(topologyZone.group).values().next().value;
if (firstDevice.updateTimeout) {
clearTimeout(firstDevice.updateTimeout);
}
firstDevice.updateTimeout = setTimeout(function () {
this.log('Retrying topology update for missing coordinator of group %s', topologyZone.group);
this.updateTopology(firstDevice.sonos, function () {});
}.bind(this), 3000);
} else {
if (coordinator.updateTimeout) {
clearTimeout(coordinator.updateTimeout);
}
coordinator.updateTimeout = setTimeout(function () {
this.log('Running scheduled topology update for %s', coordinator.name);
this.updateTopology(coordinator.sonos, function () {});
}.bind(this), 600000);
}
}.bind(this));
this.log('Topology update from device %s completed', device.host);
if (callback) {
callback(null);
}
}.bind(this));
};
// Process a state change event
SonosPlatform.prototype._processAVEvent = function (deviceData, eventStruct) {
var value, queueUri;
if (!eventStruct.TransportState) {
value = false;
textValue = 'FAILED';
} else if (eventStruct.TransportState[0].$.val == "PLAYING") {
value = true;
textValue = 'PLAYING';
} else {
value = false;
textValue = eventStruct.TransportState[0].$.val;
}
if (eventStruct['r:EnqueuedTransportURI']) {
queueUri = eventStruct['r:EnqueuedTransportURI'][0].$.val;
} else {
queueUri = '';
}
if (eventStruct.CurrentTrackURI) {
trackUri = eventStruct.CurrentTrackURI[0].$.val;
} else {
trackUri = '';
}
deviceData.queueUri = queueUri;
deviceData.trackUri = trackUri;
this._log(deviceData, 'State is now %s (%s), track URI is now "%s" and queue URI is now "%s"', textValue, value, trackUri, queueUri);
var groupList = this.groupMembers.get(deviceData.group);
if (!groupList) {
return;
}
// Update power state of all group members
groupList.forEach(function (memberDeviceData) {
if (!deviceData.accessory) {
return;
}
memberDeviceData.accessory.updateOn(value);
}.bind(this));
// Process scene accessories involving this zone
var sceneList = this.zoneSceneAccessories.get(deviceData.name);
if (sceneList) {
sceneList.forEach(function (sceneAccessory, name) {
var powerState = value;
// If turning something on - check if we should turn on the scene switch
if (powerState) {
powerState = this._calculateScenePowerState(sceneAccessory, deviceData);
}
sceneAccessory.updateOn(powerState);
}.bind(this));
}
};
SonosPlatform.prototype._calculateScenePowerState = function (sceneAccessory, deviceData) {
// Check playlist matches before allowing it to turn on
if (!sceneAccessory.isDevicePlayingSceneUri(deviceData)) {
return false;
}
// Check the topology is correct
if (!sceneAccessory.validateTopology(deviceData)) {
return false;
}
return true;
};
SonosPlatform.prototype._processRenderingEvent = function (deviceData, eventStruct) {
var value = 0;
if (eventStruct.Volume) {
eventStruct.Volume.forEach(function (item) {
if (item.$.channel == 'Master') {
value = item.$.val;
}
});
}
this._log(deviceData, 'Updating volume characteristic to %s for device in zone %s', value, deviceData.name);
deviceData.accessory.service.getCharacteristic(VolumeCharacteristic).setValue(value, null, '_internal');
};
//
// Transition utilities
//
// Get a transition status from the transition table
function _utilGetTransition(characteristic) {
if (!this.transitions) {
this.transitions = new Map();
}
var transition = this.transitions.get(characteristic.UUID);
if (!transition) {
transition = {};
this.transitions.set(characteristic.UUID, transition);
}
return transition;
}
// Handle an internal update, checking for active transitions
function _utilUpdateInternal(characteristic, value, quiet) {
var transition = _utilGetTransition.call(this, characteristic),
characteristicObj = this.service.getCharacteristic(characteristic);
// Are we transitioning?
if (!transition.isRunning) {
// Compare with the existing value so we avoid unnecessary changes and logging
// This is valid as HAP-NodeJS documents cacheable value as accessible directly
// We don't call getValue as it triggers our listeners
if (characteristicObj.value == value) {
return;
}
// Log only if we're not a 'noisy' event (like power usage that happens every second)
if (!quiet) {
this.log('Updating %s characteristic to %s', characteristicObj.displayName, value);
}
// Set the value with internal context so our listeners ignores it but so we
// still trigger change events to propogate to remote listeners (accessing
// the cached value propertly directly doesn't do this)
characteristicObj.setValue(value, null, '_internal');
return;
}
this.log('Deferring %s characteristic update to %s as it is currently transitioning', characteristicObj.displayName, value);
transition.deferred = value;
}
// Get the internal cached value
function _utilGetInternal(characteristic) {
var characteristicObj = this.service.getCharacteristic(characteristic);
// Return the cached value directly, don't use getValue which will use
// registered event handlers to get latest value which is not what we want
return characteristicObj.value;
}
// Begin transition of a characteristic
// Prevents internal updates from taking effect until a second after the
// transition completes, to prevent flicking of states while status converges
function _utilBeginTransition(characteristic, callback) {
var transition = _utilGetTransition.call(this, characteristic);
transition.isRunning = true;
// If we have a deferred timeout running already, clear it
if (transition.deferredTimeout !== undefined) {
clearTimeout(transition.deferredTimeout);
transition.deferredTimeout = undefined;
}
return function (err) {
// Set a timer to update to any deferred value after a small timeout that
// will hopefully be long enough for events to converge on the desired state
transition.deferredTimeout = setTimeout(function () {
transition.isRunning = false;
if (transition.deferred === undefined) {
return;
}
this._updateInternal(characteristic, transition.deferred);
transition.deferred = undefined;
}.bind(this), 2000);
callback(err);
}.bind(this);
}
//
// Sonos Scene Accessory
//
function SonosSceneAccessory(platform, log, name, sceneConfig, platformAccessory) {
this.platform = platform;
this.log = log;
this.name = name;
this.sceneConfig = sceneConfig;
if (platformAccessory) {
this.log('Restoring cached scene platform accessory with name %s', name);
this.platformAccessory = platformAccessory;
this.infoService = platformAccessory.getService(Service.AccessoryInformation);
this.service = platformAccessory.getService(Service.Switch);
} else {
this.log('Creating new scene platform accessory with name %s', name);
platformAccessory = new PlatformAccessory(name, UUIDGen.generate(name));
platformAccessory.context.type = 'SonosSceneAccessory';
platformAccessory.context.name = name;
this.infoService = platformAccessory.getService(Service.AccessoryInformation);
this.service = platformAccessory.addService(Service.Switch);
}
this.infoService
.setCharacteristic(Characteristic.Name, name)
.setCharacteristic(Characteristic.Manufacturer, 'homebridge-sonos')
.setCharacteristic(Characteristic.Model, 'Scene Accessory')
.setCharacteristic(Characteristic.SerialNumber, 'N/A');
this.service
.getCharacteristic(Characteristic.On)
.on('set', this.setOn.bind(this));
// Index for quick lookup
platform.sceneAccessories.set(name, this);
sceneConfig.zones.forEach(function (zone) {
var sceneList = platform.zoneSceneAccessories.get(zone);
if (!sceneList) {
sceneList = new Map();
platform.zoneSceneAccessories.set(zone, sceneList);
}
sceneList.set(name, this);
}.bind(this));
if (!this.platformAccessory) {
this.platformAccessory = platformAccessory;
this.platform.api.registerPlatformAccessories('homebridge-sonos', 'Sonos', [platformAccessory]);
}
}
// Common utils
SonosSceneAccessory.prototype._updateInternal = _utilUpdateInternal;
SonosSceneAccessory.prototype._getInternal = _utilGetInternal;
SonosSceneAccessory.prototype._beginTransition = _utilBeginTransition;
// Update current power state
SonosSceneAccessory.prototype.updateOn = function (on) {
this._updateInternal(Characteristic.On, on);
};
// Fetch the coordinator device associated with this scene, or the first one
// listed
SonosSceneAccessory.prototype._getCoordinator = function () {
var firstAccessoryDevice = false;
for (var i in this.sceneConfig.zones) {
var zone = this.sceneConfig.zones[i];
accessory = this.platform.accessories.get(zone);
if (firstAccessoryDevice === false && accessory) {
firstAccessoryDevice = accessory.device;
}
if (accessory.device && accessory.device.coordinator === 'true') {
return accessory.device;
}
}
return firstAccessoryDevice;
};
// Handle power state
SonosSceneAccessory.prototype.setOn = function (on, callback, context) {
if (context == '_internal') {
// An internal status update - don't do anything
callback(null);
return;
}
var device = this._getCoordinator();
if (!device) {
this.log('Ignoring request; Sonos devices have not yet been discovered.');
callback(new Error('Sonos has not been discovered yet.'));
return;
}
// Flag that a transition is happening so we can prevent status updates until
// we complete
callback = this._beginTransition(Characteristic.On, callback);
if (!on) {
this.log('Pausing coordinator');
device.sonos.pause(function (err) {
if (err) {
this.log('Pause request failed: %s', err);
callback(err);
return;
}
this.log('Pause request successful');
callback(null);
}.bind(this));
return;
}
// Validate the group is correct
if (this.validateTopology(device)) {
this.log('Starting scene request with existing group coordinator: %s', device.name);
if (this.isDevicePlayingSceneUri(device)) {
if (this.sceneConfig.volume) {
this._configureVolume(device, callback);
return;
}
this._play(device, callback);
return;
}
this._configurePlaylist(device, callback);
return;
}
this.log('Starting scene request by forming new group with new coordinator: %s', device.name);
// Group is wrong - take the current device as the coordinator and configure
// the others
device.sonos.becomeCoordinatorOfStandaloneGroup(function (err) {
if (err) {
this.log('Standalone group request failed: %s', err);
callback(err);
return;
}
if (this.sceneConfig.zones.length == 1) {
this._configurePlaylist(device, callback);
return;
}
this.log('New coordinator in %s is now configured', device.name);
this.platform.updateTopology(device.sonos, function (err) {
if (err) {
this.log('Topology update failed: %s', err);
callback(err);
return;
}
this._configureTopology(device, callback);
}.bind(this));
}.bind(this));
};
// Validate that the topology of the group containing the given device matches
// what we need for this scene
SonosSceneAccessory.prototype.validateTopology = function (device) {
// Grab the device list for this zone
var groupList = this.platform.groupMembers.get(device.group);
if (!groupList) {
return false;
}
// Compare the list with our zone list, ignoring unavailable zones
var missingList = new Map(groupList);
for (var i in this.sceneConfig.zones) {
var zone = this.sceneConfig.zones[i],
zoneAccessory = this.platform.accessories.get(zone);
if (!zoneAccessory || !zoneAccessory.device) {
// Unavailable zone, ignore it so we can still use the switch
continue;
}
// Is the required zone in the group?
if (!missingList.get(zoneAccessory.device.host)) {
// We have a missing zone and need to recreate the group
return false;
}
missingList.delete(zoneAccessory.device.host);
}
if (missingList.size !== 0) {
// Not valid - need to create new group
return false;
}
return true;
};
// Returns true if the given device is currently playing the requested URI
SonosSceneAccessory.prototype.isDevicePlayingSceneUri = function (device) {
if (this.sceneConfig.playlist.startsWith('audioinput:')) {
// Should be no queue, but the track should be the audio input
var audioStreamUri = this._getAudioInputUri();
return audioStreamUri && device.trackUri === audioStreamUri;
}
return device.queueUri === this._getPlaylistUri();
};
// Get audio input URI for the coordinator
SonosSceneAccessory.prototype._getAudioInputUri = function () {
var zone = this.sceneConfig.playlist.split(':', 2)[1],
zoneAccessory = this.platform.accessories.get(zone),
audioStreamUri;
if (!zoneAccessory) {
return '';
}
return 'x-rincon-stream:' + zoneAccessory.device.uuid;
};
// Get a playlist URI
SonosSceneAccessory.prototype._getPlaylistUri = function () {
return 'x-rincon-cpcontainer:' + this._getPlaylistId();
};
// Get a playlist ID
SonosSceneAccessory.prototype._getPlaylistId = function () {
return '10062a6c' + this.sceneConfig.playlist.replace(/:/g, '%3a');
};
// Configure the other devices in the scene configuration to use our coordinator
SonosSceneAccessory.prototype._configureTopology = function (device, callback) {
var topologyUpdateStack = [],
stagedCallback = function (zone, err) {
if (err) {
this.log('Topology change request for %s failed: %s', zone, err);
callback(err);
return;
}
this.log('New topology with coordinator %s now includes %s', device.name, zone);
var next = topologyUpdateStack.shift();
if (next) {
next();
return;
}
this.log('Topology configuration has completed');
this._configurePlaylist(device, callback);
};
this.sceneConfig.zones.forEach(function (zone) {
if (zone == device.name) {
return;
}
// Skip unavailable zones so we can function partially
var zoneAccessory = this.platform.accessories.get(zone);
if (!zoneAccessory || !zoneAccessory.device) {
this.log('Skipping configuration of zone %s as it is unreachable', zone);
return;
}
topologyUpdateStack.push(function () {
zoneAccessory.device.sonos.queueNext('x-rincon:' + device.uuid, stagedCallback.bind(this, zone));
}.bind(this));
}.bind(this));
// Begin updating the topology one by one
// Never do this in parallel as it confuses Sonos if any of the target zones
// are grouped as when we remove one zone from a group the other members begin
// to re-elect a coordinator for that group and if we try to change their
// membership while that happens - they'll pretty much just ignore us
topologyUpdateStack.shift()();
};
// Process the queue URI and play the playlist
SonosSceneAccessory.prototype._configurePlaylist = function (device, callback) {
if (this.sceneConfig.playlist.startsWith('audioinput:')) {
this._configurePlaylistAudioInput(device, callback);
} else {
this._configurePlaylistQueue(device, callback);
}
};
// Process playlist from audio input
SonosSceneAccessory.prototype._configurePlaylistAudioInput = function (device, callback) {
// Flick over to the requested audio input source
var audioStreamUri = this._getAudioInputUri();
if (!audioStreamUri) {
this.log('The required Sonos audio input device is not available');
callback(new Error('The required Sonos audio input device is not available'));
return;
}
device.sonos.queueNext({
uri: audioStreamUri
}, function (err) {
if (err) {
this.log('Queue next request failed: %s', err);
callback(err);
return;
}
this._configurePlaylistCompleted(device, callback);
}.bind(this));
};
// Process playlist from queue
SonosSceneAccessory.prototype._configurePlaylistQueue = function (device, callback) {
device.sonos.flush(function (err) {
if (err) {
this.log('Queue flush request failed: %s', err);
callback(err);
return;
}
device.sonos.queue({
uri: this._getPlaylistUri(),
metadata: '<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">' +
'<item id="' + this._getPlaylistId() + '" restricted="true"><dc:title>Playlist</dc:title><upnp:class>object.container.playlistContainer</upnp:class><desc id="cdudn" nameSpace="urn:schemas-rinconnetworks-com:metadata-1-0/">SA_RINCON' + this.platform.config.spotify_rincon_id + '_X_#Svc' + this.platform.config.spotify_rincon_id + '-0-Token</desc></item></DIDL-Lite>'
}, function (err) {
if (err) {
this.log('Playlist queue request failed: %s', err);
callback(err);
return;
}
device.sonos.selectQueue(function (err) {
if (err) {
this.log('Playlist selectQueue request failed: %s', err);
callback(err);
return;