forked from Limych/media_player.linkplay
-
Notifications
You must be signed in to change notification settings - Fork 29
/
media_player.py
2207 lines (1916 loc) · 86.5 KB
/
media_player.py
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
"""
Support for Linkplay based devices.
For more details about this platform, please refer to the documentation at
https://github.com/nagyrobi/home-assistant-custom-components-linkplay
"""
import binascii
import json
from json import loads, dumps
import upnpclient
import netdisco.ssdp
import logging
import urllib.request
import xml.etree.ElementTree as ET
import time
from datetime import timedelta
import socket
import requests
import string
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.util.dt import utcnow
from homeassistant.components import media_source
#from homeassistant.auth.models import RefreshToken
#from homeassistant.components.http.auth import async_sign_path
from homeassistant.util import Throttle
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_DEVICE_CLASS,
CONF_HOST,
CONF_NAME,
STATE_PAUSED,
STATE_PLAYING,
STATE_IDLE,
STATE_UNKNOWN,
STATE_UNAVAILABLE,
)
from homeassistant.components.media_player import (
DEVICE_CLASS_SPEAKER,
BrowseMedia,
MediaPlayerEntity,
)
from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC,
MEDIA_TYPE_URL,
MEDIA_TYPE_TRACK,
MEDIA_CLASS_DIRECTORY,
MEDIA_CLASS_MUSIC,
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_PLAY,
SUPPORT_PLAY_MEDIA,
SUPPORT_PREVIOUS_TRACK,
SUPPORT_SEEK,
SUPPORT_BROWSE_MEDIA,
SUPPORT_SELECT_SOUND_MODE,
SUPPORT_SELECT_SOURCE,
SUPPORT_SHUFFLE_SET,
SUPPORT_REPEAT_SET,
SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_SET,
SUPPORT_STOP,
REPEAT_MODE_ALL,
REPEAT_MODE_OFF,
REPEAT_MODE_ONE,
)
from homeassistant.components.media_player.errors import BrowseError
from . import DOMAIN, ATTR_MASTER
_LOGGER = logging.getLogger(__name__)
ATTR_SLAVE = 'slave'
ATTR_LINKPLAY_GROUP = 'linkplay_group'
ATTR_FWVER = 'firmware'
ATTR_TRCNT = 'track_count'
ATTR_TRCRT = 'track_current'
ATTR_DEBUG = 'debug_info'
PARALLEL_UPDATES = 0
ICON_DEFAULT = 'mdi:speaker'
ICON_PLAYING = 'mdi:speaker-wireless'
ICON_MUTED = 'mdi:speaker-off'
ICON_MULTIROOM = 'mdi:speaker-multiple'
ICON_BLUETOOTH = 'mdi:speaker-bluetooth'
ICON_PUSHSTREAM = 'mdi:cast-audio'
CONF_NAME = 'name'
CONF_LASTFM_API_KEY = 'lastfm_api_key'
CONF_SOURCES = 'sources'
CONF_ICECAST_METADATA = 'icecast_metadata'
CONF_MULTIROOM_WIFIDIRECT = 'multiroom_wifidirect'
LASTFM_API_BASE = 'http://ws.audioscrobbler.com/2.0/?method='
MAX_VOL = 100
FW_MROOM_RTR_MIN = '4.2.8020'
UPNP_TIMEOUT = 2
TCPPORT = 8899
ICE_THROTTLE = timedelta(seconds=60)
UNA_THROTTLE = timedelta(seconds=120)
MROOM_UJWDIR = timedelta(seconds=20)
MROOM_UJWROU = timedelta(seconds=3)
ROOTDIR_USB = '/media/sda1/'
DEFAULT_ICECAST_UPDATE = 'StationName'
DEFAULT_MULTIROOM_WIFIDIRECT = False
PLATFORM_SCHEMA = vol.All(cv.PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_ICECAST_METADATA, default=DEFAULT_ICECAST_UPDATE): vol.In(['Off', 'StationName', 'StationNameSongTitle']),
vol.Optional(CONF_MULTIROOM_WIFIDIRECT, default=DEFAULT_MULTIROOM_WIFIDIRECT): cv.boolean,
vol.Optional(CONF_SOURCES): cv.ensure_list,
vol.Optional(CONF_LASTFM_API_KEY): cv.string,
}))
SOUND_MODES = {'0': 'Normal', '1': 'Classic', '2': 'Pop', '3': 'Jazz', '4': 'Vocal'}
SOURCES = {'bluetooth': 'Bluetooth',
'line-in': 'Line-in',
'line-in2': 'Line-in 2',
'optical': 'Optical',
'co-axial': 'Coaxial',
'HDMI': 'HDMI',
'udisk': 'USB disk',
'TFcard': 'SD card',
'RCA': 'RCA',
'XLR': 'XLR',
'FM': 'FM',
'cd': 'CD'}
SOURCES_MAP = {'-1': 'Idle',
'0': 'Idle',
'1': 'Airplay',
'2': 'DLNA',
'3': 'QPlay',
'10': 'Network',
'11': 'udisk',
'16': 'TFcard',
'20': 'API',
'21': 'udisk',
'30': 'Alarm',
'31': 'Spotify',
'40': 'line-in',
'41': 'bluetooth',
'43': 'optical',
'44': 'RCA',
'45': 'co-axial',
'46': 'FM',
'47': 'line-in2',
'48': 'XLR',
'49': 'HDMI',
'50': 'cd',
'52': 'TFcard',
'60': 'Talk',
'99': 'Idle'}
SOURCES_LIVEIN = ['-1', '0', '40', '41', '43', '44', '45', '46', '47', '48', '49', '50', '99']
SOURCES_STREAM = ['1', '2', '3', '10', '30']
SOURCES_LOCALF = ['11', '16', '20', '21', '52', '60']
class LinkPlayData:
"""Storage class for platform global data."""
def __init__(self):
"""Initialize the data."""
self.entities = []
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Linkplay device."""
if DOMAIN not in hass.data:
hass.data[DOMAIN] = LinkPlayData()
linkplay = LinkPlayDevice(config.get(CONF_HOST),
config.get(CONF_NAME),
config.get(CONF_SOURCES),
config.get(CONF_ICECAST_METADATA),
config.get(CONF_MULTIROOM_WIFIDIRECT),
config.get(CONF_LASTFM_API_KEY))
add_entities([linkplay])
class LinkPlayDevice(MediaPlayerEntity):
"""Representation of a Linkplay device."""
def __init__(self,
host,
name,
sources,
icecast_meta,
multiroom_wifidierct,
lfm_api_key=None
):
"""Initialize the Linkplay device."""
self._fw_ver = '1.0.0'
self._uuid = ''
self._features = None
self._preset_key = 4
self._name = name
self._host = host
self._icon = ICON_DEFAULT
self._state = STATE_UNAVAILABLE
self._volume = 0
self._fadevol = False
self._source = None
self._prev_source = None
if sources is not None and sources != {}:
self._source_list = loads(dumps(sources).strip('[]'))
else:
self._source_list = SOURCES.copy()
self._sound_mode = None
self._muted = False
self._playhead_position = 0
self._duration = 0
self._position_updated_at = None
self._shuffle = False
self._repeat = REPEAT_MODE_OFF
self._media_album = None
self._media_artist = None
self._media_prev_artist = None
self._media_title = None
self._media_prev_title = None
self._lpapi = LinkPlayRestData(self._host)
self._tcpapi = LinkPlayTcpUartData(self._host)
self._media_image_url = None
self._media_uri = None
self._first_update = True
if lfm_api_key is not None:
self._lfmapi = LastFMRestData(lfm_api_key)
else:
self._lfmapi = None
self._upnp_device = None
self._slave_mode = False
self._slave_ip = None
self._trackq = []
self._trackc = None
self._master = None
self._is_master = False
self._wifi_channel = None
self._ssid = None
self._playing_localfile = True
self._playing_stream = False
self._playing_liveinput = False
self._playing_spotify = False
self._playing_webplaylist = False
self._playing_tts = False
self._slave_list = None
self._multiroom_wifidirect = False
self._multiroom_group = []
self._multiroom_prevsrc = None
self._multiroom_unjoinat = None
self._wait_for_mcu = 0
self._new_song = True
self._unav_throttle = False
self._icecast_name = None
self._icecast_meta = icecast_meta
self._ice_skip_throt = False
self._snapshot_active = False
self._snap_source = None
self._snap_state = STATE_UNKNOWN
self._snap_volume = 0
self._snap_spotify = False
async def async_added_to_hass(self):
"""Record entity."""
self.hass.data[DOMAIN].entities.append(self)
@property
def name(self):
"""Return the name of the device."""
if self._slave_mode:
for dev in self._multiroom_group:
for device in self.hass.data[DOMAIN].entities:
if device._is_master:
return self._name + ' [' + device._name + ']'
else:
return self._name
@property
def icon(self):
"""Return the icon of the device."""
if self._muted or self._state in [STATE_PAUSED, STATE_UNAVAILABLE]:
return ICON_MUTED
if self._slave_mode or self._is_master:
return ICON_MULTIROOM
if self._source == "Bluetooth":
return ICON_BLUETOOTH
if self._source == "DLNA" or self._source == "Airplay":
return ICON_PUSHSTREAM
if self._state == STATE_PLAYING:
return ICON_PLAYING
return ICON_DEFAULT
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
return int(self._volume) / MAX_VOL
@property
def is_volume_muted(self):
"""Return boolean if volume is currently muted."""
return self._muted
@property
def source(self):
"""Return the current input source."""
if self._source not in ['Idle', 'Network']:
return self._source
else:
return None
@property
def source_list(self):
"""Return the list of available input sources. If only one source exists, don't show it, as it's one and only one - WiFi shouldn't be listed."""
source_list = self._source_list.copy()
if 'wifi' in source_list:
del source_list['wifi']
if len(self._source_list) > 0:
return list(source_list.values())
else:
return None
@property
def sound_mode(self):
"""Return the current sound mode."""
return self._sound_mode
@property
def sound_mode_list(self):
"""Return the available sound modes."""
return sorted(list(SOUND_MODES.values()))
@property
def supported_features(self):
"""Flag media player features that are supported."""
if self._slave_mode and self._features:
return self._features
if self._playing_localfile or self._playing_spotify or self._playing_webplaylist:
if self._state in [STATE_PLAYING, STATE_PAUSED]:
self._features = \
SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE | SUPPORT_PLAY_MEDIA | \
SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_STOP | SUPPORT_PLAY | SUPPORT_PAUSE | \
SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_SHUFFLE_SET | SUPPORT_REPEAT_SET | SUPPORT_SEEK
else:
self._features = \
SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE | SUPPORT_PLAY_MEDIA | \
SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_STOP | SUPPORT_PLAY | SUPPORT_PAUSE | \
SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_SHUFFLE_SET | SUPPORT_REPEAT_SET
elif self._playing_stream:
self._features = \
SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE | SUPPORT_PLAY_MEDIA | \
SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_STOP | SUPPORT_PLAY | SUPPORT_PAUSE
elif self._playing_liveinput:
self._features = \
SUPPORT_SELECT_SOURCE | SUPPORT_SELECT_SOUND_MODE | SUPPORT_PLAY_MEDIA | \
SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \
SUPPORT_STOP
if "udisk" in self._source_list:
self._features |= SUPPORT_BROWSE_MEDIA
return self._features
@property
def media_position(self):
"""Time in seconds of current playback head position."""
if self._playing_localfile or self._playing_spotify or self._slave_mode:
return self._playhead_position
else:
return None
@property
def media_duration(self):
"""Time in seconds of current song duration."""
if self._playing_localfile or self._playing_spotify or self._slave_mode:
return self._duration
else:
return None
@property
def media_position_updated_at(self):
"""When the seek position was last updated."""
if not self._playing_liveinput:
return self._position_updated_at
else:
return None
@property
def shuffle(self):
"""Return True if shuffle mode is enabled."""
return self._shuffle
@property
def repeat(self):
"""Return repeat mode."""
return self._repeat
@property
def media_title(self):
"""Return title of the current track."""
return self._media_title
@property
def media_artist(self):
"""Return name of the current track artist."""
return self._media_artist
@property
def media_album_name(self):
"""Return name of the current track album."""
return self._media_album
@property
def media_image_url(self):
"""Return name the image for the current track."""
return self._media_image_url
@property
def media_content_type(self):
"""Content type of current playing media."""
if self._playing_stream:
return MEDIA_TYPE_URL
else:
return MEDIA_TYPE_MUSIC
@property
def ssid(self):
"""SSID to use for multiroom configuration."""
return self._ssid
@property
def wifi_channel(self):
"""Wifi channel to use for multiroom configuration."""
return self._wifi_channel
@property
def slave_ip(self):
"""Ip used in multiroom configuration."""
return self._slave_ip
@property
def slave(self):
"""Return true if it is a slave."""
return self._slave_mode
@property
def master(self):
"""master's entity id used in multiroom configuration."""
return self._master
@property
def is_master(self):
"""Return true if it is a master."""
return self._is_master
@property
def device_class(self):
"""Return the device class of this entity, if any."""
return DEVICE_CLASS_SPEAKER
@property
def device_state_attributes(self):
"""List members in group and set master and slave state."""
attributes = {}
if self._multiroom_group is not None:
attributes = {ATTR_LINKPLAY_GROUP: self._multiroom_group}
attributes[ATTR_MASTER] = self._is_master
attributes[ATTR_SLAVE] = self._slave_mode
attributes[ATTR_FWVER] = self._fw_ver
if len(self._trackq) > 0:
attributes[ATTR_TRCNT] = len(self._trackq) - 1
attributes[ATTR_TRCRT] = self._trackc
if self._upnp_device is None:
attributes[ATTR_DEBUG] = "UPnP not detected"
else:
attributes[ATTR_DEBUG] = "UPnP detected"
# if self._playing_localfile:
# attributes[ATTR_DEBUG] = "_playing_localfile"
# elif self._playing_spotify:
# attributes[ATTR_DEBUG] = "_playing_spotify"
# elif self._playing_webplaylist:
# attributes[ATTR_DEBUG] = "_playing_webplaylist"
# elif self._playing_stream:
# attributes[ATTR_DEBUG] = "_playing_stream"
# elif self._playing_liveinput:
# attributes[ATTR_DEBUG] = "_playing_liveinput"
return attributes
@property
def host(self):
"""Self ip."""
return self._host
@property
def track_count(self):
"""List of tracks present on the device."""
if len(self._trackq) > 0:
return len(self._trackq) - 1
else:
return 0
@property
def fw_ver(self):
"""Return the firmware version number of the device."""
return self._fw_ver
@property
def lpapi(self):
"""Device API."""
return self._lpapi
def set_volume_level(self, volume):
"""Set volume level, input range 0..1, linkplay device 0..100."""
volume = str(round(int(volume * MAX_VOL)))
if not (self._slave_mode and self._multiroom_wifidirect):
if self._fadevol:
voldiff = int(self._volume) - int(volume)
steps = 1
if voldiff < 33:
steps = 2
elif voldiff >= 33 and voldiff < 66:
steps = 4
elif voldiff > 66:
steps = 6
volstep = int(round(voldiff / steps))
voltemp = int(self._volume)
# self._wait_for_mcu = 1 # set delay in update routine for the fade to finish
for v in (range(0, steps - 1)):
voltemp = voltemp - volstep
self._lpapi.call('GET', 'setPlayerCmd:vol:{0}'.format(str(voltemp)))
time.sleep(0.6 / steps)
if self._is_master:
self._lpapi.call('GET', 'setPlayerCmd:slave_vol:{0}'.format(str(volume)))
else:
self._lpapi.call('GET', 'setPlayerCmd:vol:{0}'.format(str(volume)))
value = self._lpapi.data
if value == "OK":
self._volume = volume
else:
_LOGGER.warning("Failed to set volume. Device: %s, Got response: %s", self.entity_id, value)
else:
if self._snapshot_active:
return
self._master.lpapi.call('GET', 'multiroom:SlaveVolume:{0}:{1}'.format(self._slave_ip, str(volume)))
value = self._master.lpapi.data
if value == "OK":
self._volume = volume
else:
_LOGGER.warning("Failed to set volume. Device: %s, Got response: %s", self.entity_id, value)
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
if not (self._slave_mode and self._multiroom_wifidirect):
if self._is_master:
self._lpapi.call('GET', 'setPlayerCmd:slave_mute:{0}'.format(str(int(mute))))
else:
self._lpapi.call('GET', 'setPlayerCmd:mute:{0}'.format(str(int(mute))))
value = self._lpapi.data
if value == "OK":
self._muted = bool(int(mute))
else:
_LOGGER.warning("Failed mute/unmute volume. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.lpapi.call('GET', 'multiroom:SlaveMute:{0}:{1}'.format(self._slave_ip, str(int(mute))))
value = self._master.lpapi.data
if value == "OK":
self._muted = bool(int(mute))
else:
_LOGGER.warning("Failed mute/unmute volume. Device: %s, Got response: %s", self.entity_id, value)
def media_play(self):
"""Send play command."""
if not self._slave_mode:
if self._state == STATE_PAUSED:
self._lpapi.call('GET', 'setPlayerCmd:resume')
value = self._lpapi.data
elif self._prev_source != None:
temp_source = next((k for k in self._source_list if self._source_list[k] == self._prev_source), None)
if temp_source == None:
return
if temp_source.find('http') == 0 or temp_source == 'udisk' or temp_source == 'TFcard':
self.select_source(self._prev_source)
if self._source != None:
self._source = None
value = "OK"
else:
self._lpapi.call('GET', 'setPlayerCmd:play')
value = self._lpapi.data
else:
self._lpapi.call('GET', 'setPlayerCmd:play')
value = self._lpapi.data
if value == "OK":
self._unav_throttle = False
self._playing_tts = False
self._state = STATE_PLAYING
self._position_updated_at = utcnow()
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_state(self._state)
slave.set_position_updated_at(self.media_position_updated_at)
else:
_LOGGER.warning("Failed to start or resume playback. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_play()
def media_pause(self):
"""Send pause command."""
if not self._slave_mode:
if self._playing_stream:
# Pausing a live stream will cause a buffer overrun in hardware. Stop is the correct procedure in this case.
# If the stream is configured as an input source, when pressing Play after this, it will be started again (using self._prev_source).
self.media_stop()
return
self._lpapi.call('GET', 'setPlayerCmd:pause')
value = self._lpapi.data
if value == "OK":
self._position_updated_at = utcnow()
self._state = STATE_PAUSED
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_state(self._state)
slave.set_position_updated_at(self.media_position_updated_at)
else:
_LOGGER.warning("Failed to pause playback. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_pause()
def media_stop(self):
"""Send stop command."""
if not self._slave_mode:
if self._playing_spotify or self._playing_liveinput:
self._lpapi.call('GET', 'setPlayerCmd:switchmode:wifi')
self._wait_for_mcu = 1.2
self._lpapi.call('GET', 'setPlayerCmd:stop')
value = self._lpapi.data
if value == "OK":
self._state = STATE_IDLE
self._playhead_position = 0
self._duration = 0
self._media_title = None
self._prev_source = self._source
self._source = None
self._media_artist = None
self._media_album = None
self._icecast_name = None
self._media_uri = None
self._trackc = None
self._media_image_url = None
self._position_updated_at = utcnow()
self.schedule_update_ha_state(True)
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_state(self._state)
slave.set_position_updated_at(self.media_position_updated_at)
else:
_LOGGER.warning("Failed to stop playback. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_stop()
def media_next_track(self):
"""Send next track command."""
if not self._slave_mode:
self._lpapi.call('GET', 'setPlayerCmd:next')
value = self._lpapi.data
self._playhead_position = 0
self._duration = 0
self._position_updated_at = utcnow()
self._trackc = None
self._wait_for_mcu = 2
if value != "OK":
_LOGGER.warning("Failed skip to next track. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_next_track()
def media_previous_track(self):
"""Send previous track command."""
if not self._slave_mode:
self._lpapi.call('GET', 'setPlayerCmd:prev')
value = self._lpapi.data
self._playhead_position = 0
self._duration = 0
self._position_updated_at = utcnow()
self._trackc = None
self._wait_for_mcu = 2
if value != "OK":
_LOGGER.warning("Failed to skip to previous track." " Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_previous_track()
def media_seek(self, position):
"""Send media_seek command to media player."""
if not self._slave_mode and position < self._duration:
self._lpapi.call('GET', 'setPlayerCmd:seek:{0}'.format(str(position)))
value = self._lpapi.data
self._position_updated_at = utcnow()
self._wait_for_mcu = 0.1
if value != "OK":
_LOGGER.warning("Failed to seek. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.media_seek(position)
def clear_playlist(self):
"""Clear players playlist."""
pass
def play_media(self, media_type, media_id, **kwargs):
"""Play media from a URL or localfile."""
_LOGGER.debug("Trying to play media. Device: %s, Media_type: %s, Media_id: %s", self.entity_id, media_type, media_id)
if not self._slave_mode:
if not media_type in [MEDIA_TYPE_MUSIC, MEDIA_TYPE_URL, MEDIA_TYPE_TRACK]:
_LOGGER.warning("For %s Invalid media type %s. Only %s and %s is supported", self._name, media_type, MEDIA_TYPE_MUSIC, MEDIA_TYPE_URL)
return
if media_id.find('http') == 0:
media_type = MEDIA_TYPE_URL
if media_type == MEDIA_TYPE_URL:
self._lpapi.call('GET', 'setPlayerCmd:play:{0}'.format(media_id))
value = self._lpapi.data
if value != "OK":
_LOGGER.warning("Failed to play media type URL. Device: %s, Got response: %s, Media_Id: %s", self.entity_id, value, media_id)
return False
if media_type in [MEDIA_TYPE_MUSIC, MEDIA_TYPE_TRACK]:
self._lpapi.call('GET', 'setPlayerCmd:playLocalList:{0}'.format(media_id))
value = self._lpapi.data
if value != "OK":
_LOGGER.warning("Failed to play media type music. Device: %s, Got response: %s, Media_Id: %s", self.entity_id, value, media_id)
return False
if media_id.find('tts_proxy') != -1:
self._playing_tts = True
else:
self._playing_tts = False
self._state = STATE_PLAYING
self._media_title = None
self._media_artist = None
self._media_album = None
self._icecast_name = None
self._playhead_position = 0
self._duration = 0
self._trackc = None
self._position_updated_at = utcnow()
self._media_image_url = None
self._ice_skip_throt = True
self._unav_throttle = False
if media_type == MEDIA_TYPE_URL:
self._media_uri = media_id
elif media_type == MEDIA_TYPE_MUSIC:
self._media_uri = None
self._wait_for_mcu = 0.4
return True
else:
if not self._snapshot_active:
self._master.play_media(media_type, media_id)
def select_source(self, source):
"""Select input source."""
if not self._slave_mode:
temp_source = next((k for k in self._source_list if self._source_list[k] == source), None)
if temp_source == None:
return
if temp_source == "udisk":
self._tracklist_via_upnp("USB")
if len(self._source_list) > 0:
prev_source = next((k for k in self._source_list if self._source_list[k] == self._source), None)
if prev_source and prev_source.find('http') == 0 and temp_source in ['line-in', 'line-in2', 'optical', 'bluetooth', 'co-axial', 'HDMI', 'cd', 'udisk', 'RCA']:
self._wait_for_mcu = 1
self._unav_throttle = False
if temp_source.find('http') == 0:
self._lpapi.call('GET', 'setPlayerCmd:play:{0}'.format(temp_source))
value = self._lpapi.data
if value == "OK":
if prev_source and prev_source.find('http') == -1:
self._wait_for_mcu = 2 # switching from live to stream input -> time to report correct volume value at update
else:
self._wait_for_mcu = 0.5
self._playing_tts = False
self._source = source
self._media_uri = temp_source
self._state = STATE_PLAYING
self._playhead_position = 0
self._duration = 0
self._trackc = None
self._position_updated_at = utcnow()
self._media_title = None
self._media_artist = None
self._media_album = None
self._icecast_name = None
self._media_image_url = None
self._ice_skip_throt = True
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_source(source)
else:
_LOGGER.warning("Failed to select http source and play. Device: %s, Got response: %s", self.entity_id, value)
else:
self._lpapi.call('GET', 'setPlayerCmd:switchmode:{0}'.format(temp_source))
value = self._lpapi.data
if value == "OK":
if temp_source and temp_source in ['udisk', 'TFcard']:
self._wait_for_mcu = 2 # switching to locally stored files -> time to report correct volume value at update
else:
self._wait_for_mcu = 0.6 # switching to a physical input -> time to report correct volume value at update
self._source = source
self._media_uri = None
self._state = STATE_PLAYING
self._playhead_position = 0
self._duration = 0
self._trackc = None
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_source(source)
else:
_LOGGER.warning("Failed to select source. Device: %s, Got response: %s", self.entity_id, value)
self.schedule_update_ha_state(True)
else:
self._master.select_source(source)
def select_sound_mode(self, sound_mode):
"""Set Sound Mode for device."""
if not self._slave_mode:
mode = list(SOUND_MODES.keys())[list(
SOUND_MODES.values()).index(sound_mode)]
self._lpapi.call('GET', 'setPlayerCmd:equalizer:{0}'.format(mode))
value = self._lpapi.data
if value == "OK":
self._sound_mode = sound_mode
if self._slave_list is not None:
for slave in self._slave_list:
slave.set_sound_mode(sound_mode)
else:
_LOGGER.warning("Failed to set sound mode. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.select_sound_mode(sound_mode)
def set_shuffle(self, shuffle):
"""Change the shuffle mode."""
if not self._slave_mode:
if shuffle:
self._shuffle = shuffle
mode = '2'
else:
if self._repeat == REPEAT_MODE_OFF:
mode = '0'
elif self._repeat == REPEAT_MODE_ALL:
mode = '3'
elif self._repeat == REPEAT_MODE_ONE:
mode = '1'
self._lpapi.call('GET', 'setPlayerCmd:loopmode:{0}'.format(mode))
value = self._lpapi.data
if value != "OK":
_LOGGER.warning("Failed to change shuffle mode. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.set_shuffle(shuffle)
def set_repeat(self, repeat):
"""Change the repeat mode."""
if not self._slave_mode:
self._repeat = repeat
if repeat == REPEAT_MODE_OFF:
mode = '0'
elif repeat == REPEAT_MODE_ALL:
mode = '2' if self._shuffle else '3'
elif repeat == REPEAT_MODE_ONE:
mode = '1'
self._lpapi.call('GET', 'setPlayerCmd:loopmode:{0}'.format(mode))
value = self._lpapi.data
if value != "OK":
_LOGGER.warning("Failed to change repeat mode. Device: %s, Got response: %s", self.entity_id, value)
else:
self._master.set_repeat(repeat)
def preset_button(self, preset):
"""Simulate pressing a physical preset button."""
if self._preset_key != None and preset != None:
if not self._slave_mode:
if int(preset) > 0 and int(preset) <= self._preset_key:
self._lpapi.call('GET', 'MCUKeyShortClick:{0}'.format(str(preset)))
value = self._lpapi.data
self._wait_for_mcu = 2
self.schedule_update_ha_state(True)
if value != "OK":
_LOGGER.warning("Failed to recall preset %s. " "Device: %s, Got response: %s", self.entity_id, preset, value)
else:
_LOGGER.warning("Wrong preset number %s. Device: %s, has to be integer between 1 and %s", self.entity_id, preset, self._preset_key)
else:
self._master.preset_button(preset)
def join(self, slaves):
"""Add selected slaves to multiroom configuration."""
if self._state == STATE_UNAVAILABLE:
return
if self.entity_id not in self._multiroom_group:
self._multiroom_group.append(self.entity_id)
self._is_master = True
self._wait_for_mcu = 2
for slave in slaves:
if slave._is_master:
_LOGGER.debug("Multiroom: slave has master flag set. Unjoining it from where it is. Master: %s, Slave: %s", self.entity_id, slave.entity_id)
slave.unjoin_all()
if slave.entity_id not in self._multiroom_group:
if slave._slave_mode:
_LOGGER.debug("Multiroom: slave already has slave flag set. Unjoining it from where it is. Master: %s, Slave: %s", self.entity_id, slave.entity_id)
slave.unjoin_me()
slave.set_previous_source(True)
if self._multiroom_wifidirect:
_LOGGER.debug("Multiroom: Join in WiFi drect mode. Master: %s, Slave: %s", self.entity_id, slave.entity_id)
cmd = "ConnectMasterAp:ssid={0}:ch={1}:auth=OPEN:".format(self._ssid, self._wifi_channel) + "encry=NONE:pwd=:chext=0"
else:
_LOGGER.debug("Multiroom: Join in multiroom mode. Master: %s, Slave: %s", self.entity_id, slave.entity_id)
cmd = 'ConnectMasterAp:JoinGroupMaster:eth{0}:wifi0.0.0.0'.format(self._host)
slave._lpapi.call('GET', cmd)
value = slave._lpapi.data
_LOGGER.debug("Multiroom: command result: %s Master: %s, Slave: %s", value, self.entity_id, slave.entity_id)
if value == "OK":
# slave.set_volume(self._volume)
# slave.set_volume_level(self._volume)
slave.set_master(self)
slave.set_is_master(False)
slave.set_slave_mode(True)
slave.set_media_title(self._media_title)
slave.set_media_artist(self._media_artist)
# slave.set_muted(self._muted)
slave.set_state(self.state)
slave.set_slave_ip(self._host)
slave.set_media_image_url(self._media_image_url)
slave.set_playhead_position(self.media_position)
slave.set_duration(self.media_duration)
slave.set_source(self._source)
slave.set_sound_mode(self._sound_mode)
slave.set_features(self._features)
self._multiroom_group.append(slave.entity_id)
else:
slave.set_previous_source(False)
_LOGGER.warning("Failed to join multiroom. command result: %s Master: %s, Slave: %s", value, self.entity_id, slave.entity_id)
for slave in slaves:
if slave.entity_id in self._multiroom_group:
slave.set_multiroom_group(self._multiroom_group)
## slave.set_position_updated_at(utcnow())
## slave.trigger_schedule_update(True)
self._position_updated_at = utcnow()
self.schedule_update_ha_state(True)
def unjoin_all(self):
"""Disconnect everybody from the multiroom configuration because i'm the master."""
if self._state == STATE_UNAVAILABLE:
return
cmd = "multiroom:Ungroup"
self._lpapi.call('GET', cmd)
value = self._lpapi.data
if value == "OK":
self._is_master = False