forked from SpaceMaster85/pioneer_vsx529
-
Notifications
You must be signed in to change notification settings - Fork 0
/
media_player.py
301 lines (234 loc) · 8.86 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
"""Support for Pioneer Network Receivers."""
import logging
import asyncio
import time
import voluptuous as vol
from homeassistant.components.media_player import MediaPlayerEntity, MediaPlayerEntityFeature, PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PORT,
CONF_TIMEOUT,
STATE_OFF,
STATE_ON,
EVENT_HOMEASSISTANT_STOP
)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_SOURCES = "sources"
DEFAULT_NAME = "Pioneer AVR"
DEFAULT_PORT = 8102 # telnet default. Some Pioneer AVRs use 8102
DEFAULT_TIMEOUT = None
DEFAULT_SOURCES = {}
DATA_PIONEER = 'pioneer'
#MAX_VOLUME = 150
MAX_VOLUME = 100
MAX_SOURCE_NUMBERS = 60
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.socket_timeout,
vol.Optional(CONF_SOURCES, default=DEFAULT_SOURCES): {cv.string: cv.string},
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Pioneer platform."""
pioneer = PioneerDevice(
hass,
config[CONF_NAME],
config[CONF_HOST],
config[CONF_PORT],
config[CONF_TIMEOUT],
config[CONF_SOURCES],
)
hass.loop.create_task(pioneer.readdata())
if DATA_PIONEER not in hass.data:
hass.data[DATA_PIONEER] = []
hass.data[DATA_PIONEER].append(pioneer)
_LOGGER.debug("adding pio entity")
async_add_entities([pioneer], update_before_add=False)
class PioneerDevice(MediaPlayerEntity):
"""Representation of a Pioneer device."""
_attr_supported_features = (
MediaPlayerEntityFeature.SELECT_SOURCE
| MediaPlayerEntityFeature.TURN_OFF
| MediaPlayerEntityFeature.TURN_ON
| MediaPlayerEntityFeature.VOLUME_MUTE
| MediaPlayerEntityFeature.VOLUME_SET
| MediaPlayerEntityFeature.VOLUME_STEP
)
def __init__(self, hass, name, host, port, timeout, sources):
"""Initialize the Pioneer device."""
self._name = name
self._host = host
self._port = port
self._timeout = timeout
self._volume = 0
self._muted = False
self._selected_source = ""
self._source_name_to_number = {"CD":"01", "DVD":"04", "BD":"25", "MHL":"48"}
self._source_number_to_name = {"01":"CD", "04":"DVD","25":"BD","48":"MHL"}
self._volume = None
self._muted = False
self._power = False
self._async_added = False
self._stop_listen = False
self.hasConnection = False
self.reader = None
self.writer = None
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, self.stop_pioneer)
def stop_pioneer(self, event):
_LOGGER.info("Shutting down Pioneer")
self._stop_listen = True
async def async_added_to_hass(self):
_LOGGER.debug("Async async_added_to_hass")
self._async_added = True
async def readdata(self):
_LOGGER.debug("Readdata")
while not self._stop_listen:
if not self.hasConnection:
try:
self.reader, self.writer = \
await asyncio.open_connection(self._host, self._port)
self.hasConnection = True
_LOGGER.info("Connected to %s:%d", self._host, self._port)
except:
_LOGGER.error("No connection to %s:%d, retry in 30s", \
self._host, self.port)
await asyncio.sleep(30)
continue
try:
data = await self.reader.readuntil(b'\n')
except:
self.hasConnection = False
_LOGGER.error("Lost connection!")
continue
if data.decode().strip() is None:
await asyncio.sleep(1)
_LOGGER.debug("none read")
continue
self.parseData(data.decode())
_LOGGER.debug("Finished Readdata")
return True
def parseData(self, data):
msg = ""
_LOGGER.debug("Parse data")
_LOGGER.debug(data)
# Selected input source
if data[:2] == "FN":
source_number = data[2:4]
_LOGGER.debug(source_number)
_LOGGER.debug(self._source_number_to_name)
if source_number:
self._selected_source = self._source_number_to_name.get(source_number)
_LOGGER.debug(self._selected_source)
else:
self._selected_source = None
# Power state
elif data[:3] == "PWR":
if (data[3] == "1") or (data[3] == "2"): # VSX-529 uses "2" for State off
self._power = False
else:
self._power = True
# Is muted
elif data[:3] == "MUT":
if data[3] == "1":
self._muted = False
else:
self._muted = True
# Volume level
elif data[:3] == "VOL":
self._volume = int(data[3:6]) / MAX_VOLUME
_LOGGER.debug("Volume: " + str(round(self._volume*100))+"%")
else:
print (data)
if self._async_added:
self.async_schedule_update_ha_state()
return msg
def telnet_command(self, command):
_LOGGER.debug("Command: " + command)
if self.hasConnection:
if not self.writer:
_LOGGER.error("No writer available")
self.hasConnection = False
return
try:
self.writer.write(command.encode("ASCII") + b"\r")
except (ConnectionRefusedError, OSError):
_LOGGER.error("Pioneer %s refused connection!", self._name)
self.hasConnection = False
return
except:
_LOGGER.error("Pioneer %s lost connection!", self._name)
self.hasConnection = False
return
async def async_update(self):
"""Get the latest details from the device."""
_LOGGER.debug("Update")
self.telnet_command("?P") # Power state?
if self._power:
self.telnet_command("?V") # Volume?
self.telnet_command("?M") # Muted?
self.telnet_command("?F") # Input source?
return True
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def state(self):
"""Return the state of the device."""
if self._power:
return STATE_ON
return STATE_OFF
@property
def volume_level(self):
"""Volume level of the media player (0..1)."""
return self._volume
@property
def is_volume_muted(self):
"""Boolean if volume is currently muted."""
return self._muted
@property
def supported_features(self):
"""Flag media player features that are supported."""
return self._attr_supported_features
@property
def source(self):
"""Return the current input source."""
return self._selected_source
@property
def source_list(self):
"""List of available input sources."""
return list(self._source_name_to_number.keys())
def turn_off(self):
"""Turn off media player."""
self.telnet_command("PF")
def volume_up(self):
"""Volume up media player."""
self.telnet_command("VU")
def volume_down(self):
"""Volume down media player."""
self.telnet_command("VD")
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
# 60dB max
# while (self._volume != volume)
_LOGGER.warning("Self: %f %f %d", self._volume, volume, (self._volume - volume)* MAX_VOLUME/2)
for x in range(abs(round((self._volume - volume)* MAX_VOLUME/2))):
if ((self._volume - volume)< 0):
self.volume_up()
if ((self._volume - volume)> 0):
self.volume_down()
time.sleep(.100)
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
self.telnet_command("MO" if mute else "MF")
def turn_on(self):
"""Turn the media player on."""
self.telnet_command("PO")
def select_source(self, source):
"""Select input source."""
self.telnet_command(self._source_name_to_number.get(source) + "FN")