/
gpmdp.py
324 lines (278 loc) · 11.2 KB
/
gpmdp.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
"""
Support for Google Play Music Desktop Player.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.gpmdp/
"""
import json
import logging
import socket
import time
import voluptuous as vol
from homeassistant.components.media_player import (
MEDIA_TYPE_MUSIC, PLATFORM_SCHEMA, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_VOLUME_SET,
MediaPlayerDevice)
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, STATE_OFF, STATE_PAUSED, STATE_PLAYING)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json
REQUIREMENTS = ['websocket-client==0.37.0']
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'GPM Desktop Player'
DEFAULT_PORT = 5672
GPMDP_CONFIG_FILE = 'gpmpd.conf'
SUPPORT_GPMDP = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | \
SUPPORT_SEEK | SUPPORT_VOLUME_SET | SUPPORT_PLAY
PLAYBACK_DICT = {'0': STATE_PAUSED, # Stopped
'1': STATE_PAUSED,
'2': STATE_PLAYING}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
})
def request_configuration(hass, config, url, add_entities_callback):
"""Request configuration steps from the user."""
configurator = hass.components.configurator
if 'gpmdp' in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING['gpmdp'], "Failed to register, please try again.")
return
from websocket import create_connection
websocket = create_connection((url), timeout=1)
websocket.send(json.dumps({
'namespace': 'connect',
'method': 'connect',
'arguments': ['Home Assistant']
}))
def gpmdp_configuration_callback(callback_data):
"""Handle configuration changes."""
while True:
from websocket import _exceptions
try:
msg = json.loads(websocket.recv())
except _exceptions.WebSocketConnectionClosedException:
continue
if msg['channel'] != 'connect':
continue
if msg['payload'] != "CODE_REQUIRED":
continue
pin = callback_data.get('pin')
websocket.send(json.dumps({'namespace': 'connect',
'method': 'connect',
'arguments': ['Home Assistant', pin]}))
tmpmsg = json.loads(websocket.recv())
if tmpmsg['channel'] == 'time':
_LOGGER.error("Error setting up GPMDP. Please pause "
"the desktop player and try again")
break
code = tmpmsg['payload']
if code == 'CODE_REQUIRED':
continue
setup_gpmdp(hass, config, code,
add_entities_callback)
save_json(hass.config.path(GPMDP_CONFIG_FILE), {"CODE": code})
websocket.send(json.dumps({'namespace': 'connect',
'method': 'connect',
'arguments': ['Home Assistant', code]}))
websocket.close()
break
_CONFIGURING['gpmdp'] = configurator.request_config(
DEFAULT_NAME, gpmdp_configuration_callback,
description=(
'Enter the pin that is displayed in the '
'Google Play Music Desktop Player.'),
submit_caption="Submit",
fields=[{'id': 'pin', 'name': 'Pin Code', 'type': 'number'}]
)
def setup_gpmdp(hass, config, code, add_entities):
"""Set up gpmdp."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = 'ws://{}:{}'.format(host, port)
if not code:
request_configuration(hass, config, url, add_entities)
return
if 'gpmdp' in _CONFIGURING:
configurator = hass.components.configurator
configurator.request_done(_CONFIGURING.pop('gpmdp'))
add_entities([GPMDP(name, url, code)], True)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the GPMDP platform."""
codeconfig = load_json(hass.config.path(GPMDP_CONFIG_FILE))
if codeconfig:
code = codeconfig.get('CODE')
elif discovery_info is not None:
if 'gpmdp' in _CONFIGURING:
return
code = None
else:
code = None
setup_gpmdp(hass, config, code, add_entities)
class GPMDP(MediaPlayerDevice):
"""Representation of a GPMDP."""
def __init__(self, name, url, code):
"""Initialize the media player."""
from websocket import create_connection
self._connection = create_connection
self._url = url
self._authorization_code = code
self._name = name
self._status = STATE_OFF
self._ws = None
self._title = None
self._artist = None
self._albumart = None
self._seek_position = None
self._duration = None
self._volume = None
self._request_id = 0
def get_ws(self):
"""Check if the websocket is setup and connected."""
if self._ws is None:
try:
self._ws = self._connection((self._url), timeout=1)
msg = json.dumps({'namespace': 'connect',
'method': 'connect',
'arguments': ['Home Assistant',
self._authorization_code]})
self._ws.send(msg)
except (socket.timeout, ConnectionRefusedError,
ConnectionResetError):
self._ws = None
return self._ws
def send_gpmdp_msg(self, namespace, method, with_id=True):
"""Send ws messages to GPMDP and verify request id in response."""
from websocket import _exceptions
try:
websocket = self.get_ws()
if websocket is None:
self._status = STATE_OFF
return
self._request_id += 1
websocket.send(json.dumps({'namespace': namespace,
'method': method,
'requestID': self._request_id}))
if not with_id:
return
while True:
msg = json.loads(websocket.recv())
if 'requestID' in msg:
if msg['requestID'] == self._request_id:
return msg
except (ConnectionRefusedError, ConnectionResetError,
_exceptions.WebSocketTimeoutException,
_exceptions.WebSocketProtocolException,
_exceptions.WebSocketPayloadException,
_exceptions.WebSocketConnectionClosedException):
self._ws = None
def update(self):
"""Get the latest details from the player."""
time.sleep(1)
playstate = self.send_gpmdp_msg('playback', 'getPlaybackState')
if playstate is None:
return
self._status = PLAYBACK_DICT[str(playstate['value'])]
time_data = self.send_gpmdp_msg('playback', 'getCurrentTime')
if time_data is not None:
self._seek_position = int(time_data['value'] / 1000)
track_data = self.send_gpmdp_msg('playback', 'getCurrentTrack')
if track_data is not None:
self._title = track_data['value']['title']
self._artist = track_data['value']['artist']
self._albumart = track_data['value']['albumArt']
self._duration = int(track_data['value']['duration'] / 1000)
volume_data = self.send_gpmdp_msg('volume', 'getVolume')
if volume_data is not None:
self._volume = volume_data['value'] / 100
@property
def media_content_type(self):
"""Content type of current playing media."""
return MEDIA_TYPE_MUSIC
@property
def state(self):
"""Return the state of the device."""
return self._status
@property
def media_title(self):
"""Title of current playing media."""
return self._title
@property
def media_artist(self):
"""Artist of current playing media (Music track only)."""
return self._artist
@property
def media_image_url(self):
"""Image url of current playing media."""
return self._albumart
@property
def media_seek_position(self):
"""Time in seconds of current seek position."""
return self._seek_position
@property
def media_duration(self):
"""Time in seconds of current song duration."""
return self._duration
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_GPMDP
def media_next_track(self):
"""Send media_next command to media player."""
self.send_gpmdp_msg('playback', 'forward', False)
def media_previous_track(self):
"""Send media_previous command to media player."""
self.send_gpmdp_msg('playback', 'rewind', False)
def media_play(self):
"""Send media_play command to media player."""
self.send_gpmdp_msg('playback', 'playPause', False)
self._status = STATE_PLAYING
self.schedule_update_ha_state()
def media_pause(self):
"""Send media_pause command to media player."""
self.send_gpmdp_msg('playback', 'playPause', False)
self._status = STATE_PAUSED
self.schedule_update_ha_state()
def media_seek(self, position):
"""Send media_seek command to media player."""
websocket = self.get_ws()
if websocket is None:
return
websocket.send(json.dumps({'namespace': 'playback',
'method': 'setCurrentTime',
'arguments': [position*1000]}))
self.schedule_update_ha_state()
def volume_up(self):
"""Send volume_up command to media player."""
websocket = self.get_ws()
if websocket is None:
return
websocket.send('{"namespace": "volume", "method": "increaseVolume"}')
self.schedule_update_ha_state()
def volume_down(self):
"""Send volume_down command to media player."""
websocket = self.get_ws()
if websocket is None:
return
websocket.send('{"namespace": "volume", "method": "decreaseVolume"}')
self.schedule_update_ha_state()
def set_volume_level(self, volume):
"""Set volume on media player, range(0..1)."""
websocket = self.get_ws()
if websocket is None:
return
websocket.send(json.dumps({'namespace': 'volume',
'method': 'setVolume',
'arguments': [volume*100]}))
self.schedule_update_ha_state()