-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.js
2191 lines (1997 loc) · 77.3 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
/**
* ioBroker Sonos Adapter
* Copyright (c) 12'2013-2021 Bluefox <[email protected]>
* MIT License
*
* derived from https://github.com/jishi/node-sonos-web-controller by Jimmy Shimizu
*/
'use strict';
const fs = require('fs');
const http = require('http');
const crypto = require('crypto');
const adapterName = require('./package.json').name.split('.').pop();
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const SonosDiscovery = require('sonos-discovery');
const TTS = require('./lib/tts');
const path = require('path');
const aliveIds = [];
let channels = {};
let lastCover = null;
let socketServer;
const DEFAULT_IMAGE = `${__dirname}/img/no-cover.png`;
let adapter;
function startAdapter(options) {
options = options || {};
options.name = adapterName;
options.error = err => {
// Identify unhandled errors originating from callbacks in scripts
// These are not caught by wrapping the execution code in try-catch
if (err) {
const errStr = err.toString();
if (errStr.includes('EHOSTUNREACH') || errStr.includes('ECONNRESET') || errStr.includes('EAI_AGAIN')) {
return true;
}
}
return false;
};
adapter = new utils.Adapter(options);
// {'val': state, 'ack':false, 'ts':1408294295, 'from':'admin.0', 'lc':1408294295}
// id = sonos.0.192_168_1_55.state
adapter.on('stateChange', (_id, state) => {
if (!state || state.ack) {
return;
}
adapter.log.info(`try to control id ${_id} with ${JSON.stringify(state)}`);
// Try to find the object
const id = adapter.idToDCS(_id);
if (id && id.channel && channels[id.channel]) {
if (state.val === 'false') {
state.val = false;
}
if (state.val === 'true') {
state.val = true;
}
if (parseInt(state.val) === state.val) {
state.val = parseInt(state.val);
}
let player = channels[id.channel].player;
if (!player) {
player = discovery.getPlayerByUUID(channels[id.channel].uuid);
channels[id.channel].player = player;
}
let promise;
if (player) {
if (id.state === 'state_simple') {
if (!state.val) {
promise = player.pause();
} else {
promise = player.play();
}
} else if (id.state === 'current_track_number') {
promise = player.trackSeek(state.val);
} else if (id.state === 'shuffle') {
promise = player.shuffle(!!state.val);
} else if (id.state === 'crossfade') {
promise = player.crossfade(!!state.val);
} else if (id.state === 'repeat') {
if (state.val === 0 || state.val === '0') {
promise = player.repeat('none');
} else if (state.val === 1 || state.val === '1') {
promise = player.repeat('all');
} else if (state.val === 2 || state.val === '2') {
promise = player.repeat('one');
} else {
promise = player.repeat(state.val);
}
} else if (id.state === 'play') {
if (state.val) {
promise = player.play(); // !! is toBoolean()
}
} else if (id.state === 'stop') {
if (state.val) {
promise = player.pause(); // !! is toBoolean()
}
} else if (id.state === 'pause') {
if (state.val) {
promise = player.pause(); // !! is toBoolean()
}
} else if (id.state === 'next') {
if (state.val) {
promise = player.nextTrack(); // !! is toBoolean()
}
} else if (id.state === 'prev') {
if (state.val) {
promise = player.previousTrack(); // !! is toBoolean()
}
} else if (id.state === 'seek') {
state.val = parseFloat(state.val);
if (state.val < 0) {
state.val = 0;
}
if (state.val > 100) {
state.val = 100;
}
promise = player.timeSeek(Math.round((channels[id.channel].duration * state.val) / 100));
} else if (id.state === 'current_elapsed') {
state.val = parseInt(state.val, 10);
promise = player.timeSeek(state.val);
} else if (id.state === 'current_elapsed_s') {
const parts = state.val.toString().split(':');
let seconds;
if (parts.length === 3) {
seconds = parseInt(parts[0]) * 3600;
seconds += parseInt(parts[1]) * 60;
seconds = parseInt(parts[2]);
} else if (parts.length === 2) {
seconds = parseInt(parts[0]) * 60;
seconds += parseInt(parts[1]);
} else if (parts.length === 1) {
seconds = parseInt(parts[0]);
} else {
return adapter.log.error(`Invalid elapsed time: ${state.val}`);
}
promise = player.timeSeek(seconds);
} else if (id.state === 'muted') {
if (state.val) {
promise = player.mute(); // !! is toBoolean()
} else {
promise = player.unMute(); // !! is toBoolean()
}
} else if (id.state === 'volume') {
promise = player.setVolume(state.val);
} else if (id.state === 'treble') {
promise = player.setTreble(state.val);
} else if (id.state === 'bass') {
promise = player.setBass(state.val);
} else if (id.state === 'state') {
//stop,play,pause,next,previous,mute,unmute
if (state.val && typeof state.val === 'string') {
state.val = state.val.toLowerCase();
switch (state.val) {
case 'stop':
promise = player.pause();
break;
case 'play':
promise = player.play();
break;
case 'pause':
promise = player.pause();
break;
case 'next':
promise = player.nextTrack();
break;
case 'previous':
promise = player.previousTrack();
break;
case 'mute':
promise = player.mute();
break;
case 'unmute':
promise = player.unMute();
break;
default:
adapter.log.warn(`Unknown state: ${state.val}`);
break;
}
} else {
adapter.log.warn(`Invalid state: ${state.val}`);
}
} else if (id.state === 'favorites_set') {
promise = player
.replaceWithFavorite(state.val)
.then(() => player.play())
.then(() => {
adapter.setState(
{ device: 'root', channel: id.channel, state: 'current_album' },
{ val: state.val, ack: true }
);
adapter.setState(
{
device: 'root',
channel: id.channel,
state: 'current_artist'
},
{ val: state.val, ack: true }
);
})
.catch(error => adapter.log.error(`Cannot replaceWithFavorite: ${error}`));
} else if (id.state === 'playlist_set') {
promise = player
.replaceWithPlaylist(state.val)
.then(() => player.play())
.then(() => {
adapter.setState(
{ device: 'root', channel: id.channel, state: 'current_album' },
{ val: state.val, ack: true }
);
adapter.setState(
{
device: 'root',
channel: id.channel,
state: 'current_artist'
},
{ val: state.val, ack: true }
);
})
.catch(error => adapter.log.error(`Cannot replaceWithPlaylist: ${error}`));
} else if (id.state === 'tts') {
adapter.log.debug(`Play TTS file ${state.val} on ${id.channel}`);
text2speech(state.val, id.channel);
} else if (id.state === 'add_to_group') {
promise = addToGroup(state.val, player); // xxxx
} else if (id.state === 'remove_from_group') {
promise = removeFromGroup(state.val, player);
} else if (id.state === 'coordinator') {
if (state.val === id.channel) {
promise = player.becomeCoordinatorOfStandaloneGroup();
} else {
promise = attachTo(player, getPlayerByName(state.val));
}
} else if (id.state === 'group_volume') {
try {
promise = player.setGroupVolume(state.val);
} catch (err) {
adapter.log.warn(`Cannot set group volume: ${err}`);
}
} else if (id.state === 'group_muted') {
if (state.val) {
promise = player.muteGroup(); // !! is toBoolean()
} else {
promise = player.unMuteGroup(); // !! is toBoolean()
}
} else {
adapter.log.warn(`try to control unknown id ${JSON.stringify(id)}`);
}
promise && promise.then(() => adapter.log.debug('command done')).catch(e => adapter.log.error(e));
} else {
adapter.log.warn(`SONOS "${id.channel}"/"${channels[id.channel].uuid}" not found`);
discovery.players.forEach(player =>
adapter.log.debug(`UUID: ${player.uuid} in ${player.roomName} / ${player.baseUrl}`)
);
}
}
});
adapter.on('install', () => adapter.createDevice('root', {}));
adapter.on('unload', callback => {
try {
if (adapter) {
adapter.setState && aliveIds.forEach(id => adapter.setState(id, false, true));
channels &&
Object.keys(channels).forEach(ip => {
if (channels[ip] && channels[ip].elapsedTimer) {
clearInterval(channels[ip].elapsedTimer);
channels[ip].elapsedTimer = null;
}
if (channels[ip] && channels[ip].timerVolume) {
clearTimeout(channels[ip].timerVolume);
channels[ip].timerVolume = null;
}
});
adapter.log && adapter.log.info && adapter.log.info('terminating');
}
if (discovery) {
if (discovery.players) {
for (let i = 0; i < discovery.players.length; i++) {
if (discovery.players[i] && discovery.players[i].tts) {
discovery.players[i].tts.destroy();
discovery.players[i].tts = null;
}
}
}
discovery.dispose();
discovery = null;
}
callback();
} catch {
callback();
}
});
adapter.on('ready', async () => {
try {
await clearLegacyBinaryStates();
} catch (e) {
adapter.log.warn(`Could not clear legacy binary states: ${e.message}`);
}
adapter.getObject(`${adapter.namespace}.root`, (err, obj) => {
if (!obj || !obj.common || !obj.common.name) {
adapter.createDevice('root', {}, () => main());
} else {
main();
}
});
});
// New message arrived. obj is array with current messages
adapter.on('message', obj => {
let wait = false;
if (obj) {
switch (obj.command) {
case 'send':
obj.message && text2speech(obj.message);
break;
case 'browse':
if (obj.callback) {
browse(async list => {
// get all rooms
const rooms = await adapter.getObjectViewAsync('system', 'enum', {
startkey: 'enum.rooms.',
endkey: 'enum.rooms.\u9999'
});
// merge data together
if (obj.message) {
if (typeof obj.message !== 'object') {
try {
obj.message = JSON.parse(obj.message);
} catch {
// ignore
obj.message = { devices: [] };
}
}
} else {
obj.message = { devices: [] };
}
const devices = obj.message.devices;
// merge devices
list.forEach(item => {
if (!devices.find(it => it.ip === item.ip)) {
devices.push({
name: item.roomName,
room: enumName2Id(rooms.rows, item.roomName),
ip: item.ip
});
}
});
adapter.sendTo(obj.from, obj.command, { native: { devices } }, obj.callback);
});
wait = true;
}
break;
/*case 'del':
case 'delete':
wait = true;
if (obj.message) {
adapter.deleteChannel('root', obj.message, function (err) {
sonosInit();
if (obj.callback) adapter.sendTo(obj.from, obj.command, err, obj.callback);
});
} else {
if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Invalid IP address: ' + obj.message, obj.callback);
}
break;
*/
default:
adapter.log.warn(`Unknown command: ${obj.command}`);
break;
}
}
if (!wait && obj.callback) {
adapter.sendTo(obj.from, obj.command, obj.message, obj.callback);
}
return true;
});
return adapter;
}
function toFormattedTime(time) {
let hours = Math.floor(time / 3600);
hours = hours ? `${hours}:` : '';
let min = Math.floor(time / 60) % 60;
if (min < 10) {
min = `0${min}`;
}
let sec = time % 60;
if (sec < 10) {
sec = `0${sec}`;
}
return `${hours + min}:${sec}`;
}
function enumName2Id(enums, name) {
name = name.toLowerCase();
for (let e = 0; e < enums.length; e++) {
if (enums[e] && enums[e].value && enums[e].value.common && enums[e].value.common.name) {
if (typeof enums[e].value.common.name === 'object') {
for (const lang in enums[e].value.common.name) {
if (
enums[e].value.common.name.hasOwnProperty(lang) &&
enums[e].value.common.name[lang].toLowerCase() === name
) {
return enums[e].id;
}
}
} else {
if (enums[e].value.common.name && enums[e].value.common.name.toLowerCase() === name) {
return enums[e].id;
}
}
}
if (enums[e].value && enums[e].value.name) {
if (typeof enums[e].value.name === 'object') {
for (const lang in enums[e].value.name) {
if (enums[e].value.name.hasOwnProperty(lang) && enums[e].value.name[lang].toLowerCase() === name) {
return enums[e].id;
}
}
} else {
if (enums[e].value.name.toLowerCase() === name) {
return enums[e].id;
}
}
}
}
return '';
}
const newGroupStates = {
add_to_group: {
def: '',
type: 'string',
read: false,
write: true,
role: 'media',
desc: 'Add a Player to a Group (Player to remove, Coordinator)'
},
remove_from_group: {
def: '',
type: 'string',
read: false,
write: true,
role: 'media',
desc: 'Remove a Player to a Group (Player to remove, Coordinator)'
},
coordinator: {
// master of group
def: '',
type: 'string',
read: true,
write: true,
role: 'media.coordinator',
desc: 'Indicates coordinator of group'
},
group_volume: {
type: 'number',
read: true,
write: true,
role: 'level.volume.group',
min: 0,
max: 100,
desc: 'State and control of group volume'
},
group_muted: {
def: false,
type: 'boolean',
read: true,
write: true,
role: 'media.mute.group',
desc: 'Group is muted'
},
members: {
// indicator.reachable - if player alive (read only)
type: 'string',
read: true,
write: false,
role: 'indicator.members',
desc: 'Group members'
},
membersChannels: {
// indicator.reachable - if player alive (read only)
type: 'string',
read: true,
write: false,
role: 'indicator.members',
desc: 'Group members Channels'
},
playlist_set: {
// media.playlist.set - select Sonos playlist (write only)
def: '',
type: 'string',
read: false,
write: true,
role: 'media.playlist.set',
desc: 'Set Sonos playlist to play',
name: 'Playlist set'
}
};
async function createChannel(name, ip, room) {
const states = {
state_simple: {
// media.state - Text state of player: stop, play, pause (read, write)
def: false,
type: 'boolean',
read: true,
write: true,
role: 'media.state',
desc: 'Play or pause',
name: 'Binary play/pause state'
},
play: {
// play command
type: 'boolean',
read: false,
write: true,
role: 'button.play',
desc: 'play',
name: 'Play button'
},
stop: {
// stop command
type: 'boolean',
read: false,
write: true,
role: 'button.stop',
desc: 'stop',
name: 'Stop button'
},
pause: {
// pause command
type: 'boolean',
read: false,
write: true,
role: 'button.pause',
desc: 'pause',
name: 'Pause button'
},
prev: {
// prev command
type: 'boolean',
read: false,
write: true,
role: 'button.prev',
desc: 'prev',
name: 'Previous button'
},
next: {
// next command
type: 'boolean',
read: false,
write: true,
role: 'button.next',
desc: 'next',
name: 'Next button'
},
seek: {
// seek command and indication
type: 'number',
read: true,
write: true,
unit: '%',
min: 0,
max: 100,
role: 'media.seek',
desc: 'Seek position in percent',
name: 'Seek position'
},
state: {
// media.state - Text state of player: stop, play, pause (read, write)
def: 'stop',
type: 'string',
read: true,
write: true,
values: 'stop,play,pause,next,previous,mute,unmute',
role: 'media.state',
desc: 'Play, stop, or pause, next, previous, mute, unmute',
name: 'String state'
},
volume: {
// level.volume - volume level (read, write)
type: 'number',
read: true,
write: true,
role: 'level.volume',
min: 0,
max: 100,
desc: 'State and control of volume',
name: 'Player volume'
},
treble: {
// level.treble - treble level (only write)
type: 'number',
read: false,
write: true,
role: 'level.treble',
min: -10,
max: 10,
desc: 'State and control of treble',
name: 'Player treble'
},
bass: {
// level.bass - bass level (only write)
type: 'number',
read: false,
write: true,
role: 'level.bass',
min: -10,
max: 10,
desc: 'State and control of bass',
name: 'Player bass'
},
muted: {
// media.muted - is muted (read only)
def: false,
type: 'boolean',
read: true,
write: true,
role: 'media.mute',
desc: 'Is muted',
name: 'Player mute'
},
current_title: {
// media.current.title - current title (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.title',
desc: 'Title of current played song',
name: 'Current title'
},
current_artist: {
// media.current.artist - current artist (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.artist',
desc: 'Artist of current played song',
name: 'Current artist'
},
current_album: {
// media.current.album - current album (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.album',
desc: 'Album of current played song',
name: 'Current album'
},
current_cover: {
// media.current.cover - current url to album cover (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.cover',
desc: 'Cover image of current played song',
name: 'Current cover URL'
},
current_duration: {
// media.current.duration - duration as HH:MM:SS (read only)
def: 0,
type: 'number',
read: true,
write: false,
unit: 'seconds',
role: 'media.duration',
desc: 'Duration of current played song in seconds',
name: 'Current song duration'
},
current_duration_s: {
// media.current.duration - duration in seconds (read only)
def: '00:00',
type: 'string',
read: true,
write: false,
unit: 'interval',
role: 'media.duration.text',
desc: 'Duration of current played song as HH:MM:SS',
name: 'Current duration'
},
current_type: {
// media.type - type of stream (read only)
def: 0,
type: 'number',
read: true,
write: false,
role: 'media.type',
states: { 0: 'track', 1: 'radio', 2: 'line_in' },
desc: 'Type of Stream (0 = track, 1 = radio, 2 = line_in)',
name: 'Current stream type'
},
current_station: {
// media.current.station - current station (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.station',
desc: 'Radio station currently played',
name: 'Current radio station'
},
current_track_number: {
// media.trackNo - current track number
def: 1,
type: 'number',
read: true,
write: true,
role: 'media.trackNo',
desc: 'Current track number',
name: 'Current track number'
},
alive: {
// indicator.reachable - if player alive (read only)
type: 'boolean',
read: true,
write: false,
role: 'indicator.reachable',
desc: 'If sonos alive or not',
name: 'Connection status'
},
current_elapsed: {
// media.current.elapsed - elapsed time in seconds
def: 0,
type: 'number',
read: true,
write: true,
unit: 'seconds',
role: 'media.elapsed',
desc: 'Elapsed time of current played song in seconds',
name: 'Elapsed time in seconds'
},
current_elapsed_s: {
// media.current.elapsed - elapsed time in HH:MM:SS
def: '00:00',
type: 'string',
read: true,
write: true,
unit: 'interval',
role: 'media.elapsed.text',
desc: 'Elapsed time of current played song as HH:MM:SS',
name: 'Elapsed time as text'
},
favorites_list: {
// media.favorites.list - list of favorites channel (read only)
def: '',
type: 'string',
read: true,
write: false,
role: 'media.favorites.list',
desc: 'List of favorites song or stations, divided by comma',
name: 'Favorites list'
},
favorites_list_array: {
// media.favorites.array - list of favorite channels in JSON format (read only)
def: '',
type: 'array',
read: true,
write: false,
role: 'media.favorites.array',
desc: 'Array of favorites song or stations',
name: 'Favorites Array'
},
favorites_list_html: {
// favorites html list
def: '',
type: 'string',
read: true,
write: false,
role: 'state',
desc: 'List of favorites song or stations as html table',
name: 'Favorites list html'
},
favorites_set: {
// media.favorites.set - select favorites from list (write only)
def: '',
type: 'string',
read: false,
write: true,
role: 'media.favorites.set',
desc: 'Set favorite from the list to play',
name: 'Favorites set'
},
tts: {
// play text to speech mp3 file
def: '',
type: 'string',
read: false,
write: true,
role: 'media.tts',
desc: 'Set text2speech mp3 file to play',
name: 'Text to speech'
},
shuffle: {
// Shuffle mode: true or false
def: false,
type: 'boolean',
read: true,
write: true,
role: 'media.mode.shuffle',
desc: 'Shuffle mode',
name: 'Shuffle'
},
repeat: {
// repeat mode: true or false
def: 0,
type: 'number',
read: true,
write: true,
role: 'media.mode.repeat',
states: { 0: 'none', 1: 'all', 2: 'one' },
desc: 'Repeat mode',
name: 'Repeat'
},
crossfade: {
// crossfade mode: true or false
def: false,
type: 'boolean',
read: true,
write: true,
role: 'media.mode.crossfade',
desc: 'Crossfade mode',
name: 'Crossfade'
},
queue: {
// queue
def: '',
type: 'string',
read: true,
write: false,
role: 'state',
name: 'Play queue'
},
queue_html: {
// queue html table
def: '',
type: 'string',
read: true,
write: false,
role: 'state',
name: 'Play queue html'
}
};
for (const g in newGroupStates) {
states[g] = newGroupStates[g];
}
const statesList = [];
for (const state in states) {
statesList.push(state);
}
const id = ip.replace(/[.\s]+/g, '_');
const obj = await adapter.createChannelAsync(
'root',
id,
{
role: 'media.music',
name: name || ip
},
{
ip
}
);
if (room) {
await adapter.addChannelToEnumAsync('room', room, 'root', id);
}
for (let j = 0; j < statesList.length; j++) {
await adapter.createStateAsync('root', id, statesList[j], states[statesList[j]]);
}
return obj;
}
function browse(callback) {
const result = [];
if (discovery) {
for (let i = 0; i < discovery.players.length; i++) {
result.push({
roomName: discovery.players[i].roomName,
ip: getIp(discovery.players[i], true)
});
}
}
callback && callback(result);
}
let currentFileNum = 0;
async function text2speech(fileName, sonosIp, callback) {
// Extract volume
let volume = null;
const pos = fileName.indexOf(';');
if (pos !== -1) {
volume = fileName.substring(0, pos);
fileName = fileName.substring(pos + 1);
}
fileName = fileName.trim();
// play http/https urls directly on sonos device
if (fileName && fileName.match(/^https?:\/\//)) {
if (sonosIp) {
sonosIp = sonosIp.replace(/[.\s]+/g, '_');
}
if (discovery) {
// Play on all players
for (let i = 0; i < discovery.players.length; i++) {
discovery.players[i]._address = discovery.players[i]._address || getIp(discovery.players[i]);
const ip = discovery.players[i]._address;
if (sonosIp && ip !== sonosIp) {
continue;
}
setTimeout(() => playOnSonos(fileName, discovery.players[i].uuid, volume), 100);
}
}
callback && callback();
} else if (fileName) {
if (!adapter.config.webServer) {
return adapter.log.warn('Web server must be enabled to play local TTS files');
}
const parts = fileName.split('.');
const dest = `tts${currentFileNum++}.${parts.pop()}`;
if (currentFileNum > 10) {
currentFileNum = 0;
}
// Upload this file to objects DB
try {
const data = fs.readFileSync(fileName);
const id = `/TTS/${adapter.namespace}/${dest}`;
try {
await adapter.writeFile(adapter.name, id, data);
const obj = await adapter.getForeignObject(adapter.config.webServer);
if (obj && obj.native && discovery) {
fileName = `http${obj.native.secure ? 's' : ''}://${discovery.localEndpoint}:${
obj.native.port
}/files/${adapter.name}${id}`;
if (sonosIp) {
sonosIp = sonosIp.replace(/[.\s]+/g, '_');
}
// Play on all players
for (let i = 0; i < discovery.players.length; i++) {
if (!discovery.players[i]._address) {
discovery.players[i]._address = getIp(discovery.players[i]);
}
const ip = discovery.players[i]._address;
if (sonosIp && ip !== sonosIp) {
continue;
}
setTimeout(() => playOnSonos(fileName, discovery.players[i].uuid, volume), 100);
}
}
} catch (err) {
adapter.log.error(`Cannot upload ${id}: ${err}`);
return callback && callback(err);
}