Skip to content

Commit 33e0b74

Browse files
committed
Remove potential issues from init and remove Upnp printing
1 parent fb9c70c commit 33e0b74

File tree

3 files changed

+45
-67
lines changed

3 files changed

+45
-67
lines changed

aioheos/aioheoscontroller.py

+18-28
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@ def __init__(self,
9797
host=None,
9898
username=None,
9999
password=None,
100-
verbose=False,
101100
new_device_callback=None):
102101
self._host = host
103102
self._loop = loop
@@ -108,9 +107,8 @@ def __init__(self,
108107
self._players = None
109108
self._groups = None
110109

111-
self._verbose = verbose
112110
self._player_id = None
113-
self._upnp = aioheosupnp.AioHeosUpnp(loop=loop, verbose=verbose)
111+
self._upnp = None
114112
self._reader = None
115113
self._writer = None
116114
self._subscribtion_task = None
@@ -168,12 +166,13 @@ async def connect(self, host=None, port=HEOS_PORT, callback=None):
168166
self._host = host
169167
elif not self._host:
170168
# discover
169+
if not self._upnp:
170+
self._upnp = aioheosupnp.AioHeosUpnp(loop=self._loop)
171171
url = await self._upnp.discover()
172172
self._host = self._url_to_addr(url)
173173

174174
# connect
175-
if self._verbose:
176-
_LOGGER.debug('[I] Connecting to %s:%s', self._host, port)
175+
_LOGGER.debug('[I] Connecting to %s:%s', self._host, port)
177176
await self._connect(self._host, port)
178177

179178
# please, do not prettify json
@@ -211,8 +210,8 @@ async def _connect(self, host, port=HEOS_PORT):
211210
_LOGGER.warning('[W] Connection refused'
212211
', will try %s:%s again in %d seconds ...',
213212
host, port, wait)
214-
except Exception as e:
215-
_LOGGER.error('[E] %s', e)
213+
except Exception as exc: # pylint: disable=broad-except
214+
_LOGGER.error('[E] %s', exc)
216215

217216
await asyncio.sleep(wait)
218217

@@ -225,8 +224,7 @@ def send_command(self, command, message=None):
225224
msg += '?' + '&'.join("{}={}".format(key, val)
226225
for (key, val) in message.items())
227226
msg += '\r\n'
228-
if self._verbose:
229-
_LOGGER.debug(msg)
227+
_LOGGER.debug(msg)
230228
self._writer.write(msg.encode('ascii'))
231229

232230
@staticmethod
@@ -257,10 +255,8 @@ def _handle_error(self, message):
257255

258256
def _dispatcher(self, command, message, payload):
259257
"""Call parser functions."""
260-
# if self._verbose:
261-
if self._verbose:
262-
_LOGGER.debug('DISPATCHER')
263-
_LOGGER.debug('[D] %s %s %s', command, message, payload)
258+
_LOGGER.debug('DISPATCHER')
259+
_LOGGER.debug('[D] %s %s %s', command, message, payload)
264260
callbacks = {
265261
GET_PLAYERS:
266262
self._parse_players,
@@ -310,8 +306,7 @@ def _dispatcher(self, command, message, payload):
310306
if command in callbacks:
311307
callbacks[command](payload, message)
312308
elif command in commands_ignored:
313-
if self._verbose:
314-
_LOGGER.debug('[D] command "%s" is ignored.', command)
309+
_LOGGER.debug('[D] command "%s" is ignored.', command)
315310
else:
316311
_LOGGER.debug('[D] command "%s" is not handled.', command)
317312

@@ -374,25 +369,21 @@ async def _async_subscribe(self, callback=None):
374369
return
375370
except Exception as exc: # pylint: disable=broad-except
376371
_LOGGER.error('[E] Ignoring', exc)
377-
if self._verbose:
378-
_LOGGER.debug(msg.decode())
372+
_LOGGER.debug(msg.decode())
379373
# simplejson doesnt need to decode from byte to ascii
380374
data = json.loads(msg.decode())
381-
if self._verbose:
382-
_LOGGER.debug('DATA:')
383-
_LOGGER.debug(data)
375+
_LOGGER.debug('DATA:')
376+
_LOGGER.debug(data)
384377
try:
385378
self._parse_command(data)
386379
except AioHeosException as exc:
387380
_LOGGER.error('[E]', exc)
388-
if self._verbose:
389-
_LOGGER.debug('MSG', msg)
390-
_LOGGER.debug('MSG decoded', msg.decode())
391-
_LOGGER.debug('MSG json', data)
381+
_LOGGER.debug('MSG', msg)
382+
_LOGGER.debug('MSG decoded', msg.decode())
383+
_LOGGER.debug('MSG json', data)
392384
continue
393385
if callback:
394-
if self._verbose:
395-
_LOGGER.debug('TRIGGER CALLBACK')
386+
_LOGGER.debug('TRIGGER CALLBACK')
396387
self._loop.create_task(self._callback_wrapper(callback))
397388

398389
def new_device_callback(self, callback):
@@ -581,8 +572,7 @@ def _parse_now_playing_media(self, payload, message):
581572

582573
player.qid = payload.get('qid')
583574

584-
if self._verbose:
585-
_LOGGER.debug("[D] _parse_now_playing_media %s", vars(player))
575+
_LOGGER.debug("[D] _parse_now_playing_media %s", vars(player))
586576

587577
def get_favourites(self):
588578
""" get duration """

aioheos/aioheosupnp.py

+26-38
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@
99
"""
1010

1111
import asyncio
12+
import logging
1213
import socket
13-
from pprint import pprint
1414
from time import gmtime, strftime
15+
1516
import aiohttp
1617
import lxml.etree
1718

@@ -23,6 +24,8 @@
2324
MEDIA_DEVICE = 'urn:schemas-upnp-org:device:MediaRenderer:1'
2425
AVTRANSPORT_SERVICE = 'urn:schemas-upnp-org:service:AVTransport:1'
2526

27+
_LOGGER = logging.getLogger(__name__)
28+
2629

2730
def _get_ipaddress():
2831
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -138,12 +141,7 @@ class Upnp():
138141
" Upnp class "
139142

140143
# pylint: disable=redefined-outer-name
141-
def __init__(self,
142-
loop,
143-
ssdp_host=SSDP_HOST,
144-
ssdp_port=SSDP_PORT,
145-
verbose=False):
146-
self._verbose = verbose
144+
def __init__(self, loop, ssdp_host=SSDP_HOST, ssdp_port=SSDP_PORT):
147145
self._loop = loop
148146
self._ssdp_host = ssdp_host
149147
self._ssdp_port = ssdp_port
@@ -157,17 +155,15 @@ def __init__(self,
157155
class DiscoverProtocol:
158156
""" Discovery Protocol """
159157

160-
def __init__(self, upnp, future, search_target, verbose=False):
158+
def __init__(self, upnp, future, search_target):
161159
self._upnp = upnp
162160
self._future = future
163161
self._search_target = search_target
164162
self._transport = None
165-
self._verbose = verbose
166163

167164
def connection_made(self, transport):
168165
""" Protocol connection made """
169-
if self._verbose:
170-
print('Connection made')
166+
_LOGGER.debug('Connection made')
171167
self._transport = transport
172168
sock = self._transport.get_extra_info('socket')
173169
# sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
@@ -182,7 +178,7 @@ def connection_made(self, transport):
182178
str(self._upnp.ssdp_port),
183179
'Man: "ssdp:discover"',
184180
'ST: {}'.format(self._search_target),
185-
# 'ST: ssdp:all',
181+
# 'ST: ssdp:all',
186182
'MX: 3',
187183
'',
188184
'')
@@ -204,21 +200,19 @@ def datagram_received(self, data, _):
204200
for k, v in
205201
[item.split(': ') for item in content if ": " in item]
206202
}
207-
if self._verbose:
208-
print(reply['st'])
203+
_LOGGER.debug(reply['st'])
209204
if reply['st'] == self._search_target:
210205
url = reply['location']
211206
self._future.set_result(url)
212207
self._transport.close()
213208

214209
def error_received(self, exc): # pylint: disable=no-self-use
215210
""" error received """
216-
print('[E] Error received:', exc)
211+
_LOGGER.error('[E] Error received: ', exc)
217212

218213
def connection_lost(self, _):
219214
""" connection lost """
220-
if self._verbose:
221-
print("[I] Connection lost.")
215+
_LOGGER.warning("[I] Connection lost.")
222216
self._transport.close()
223217

224218
async def discover(self, search_target, _addr=None):
@@ -227,7 +221,7 @@ async def discover(self, search_target, _addr=None):
227221
self._asyncio_ensure_future(
228222
self._loop.create_datagram_endpoint(
229223
lambda: Upnp.DiscoverProtocol(
230-
self, future, search_target, self._verbose
224+
self, future, search_target
231225
),
232226
family=socket.AF_INET,
233227
proto=socket.IPPROTO_UDP))
@@ -264,8 +258,7 @@ async def _soapaction(self, service, action, url=None, body=None):
264258
content = await response.read()
265259
await response.release()
266260

267-
if self._verbose:
268-
print(content)
261+
_LOGGER.debug(content)
269262
return content
270263

271264
async def query_renderer(self, service, url=None):
@@ -310,8 +303,7 @@ async def set_avtransport_uri(self, uri, url=None):
310303
'</s:Envelope>').format(
311304
service=service, uri=uri)
312305
response_xml = await self._soapaction(service, action, url, body)
313-
if self._verbose:
314-
pprint(response_xml)
306+
_LOGGER.debug(response_xml)
315307

316308
async def set_play(self, url=None):
317309
" play "
@@ -328,8 +320,7 @@ async def set_play(self, url=None):
328320
'</s:Body>'
329321
'</s:Envelope>').format(service)
330322
response_xml = await self._soapaction(service, "Play", url, body)
331-
if self._verbose:
332-
pprint(response_xml)
323+
_LOGGER.debug(response_xml)
333324

334325
@property
335326
def ssdp_host(self):
@@ -345,19 +336,17 @@ def ssdp_port(self):
345336
class PlayContentServer(asyncio.Protocol):
346337
""" Play Content Server """
347338

348-
def __init__(self, content, content_type, verbose=False):
339+
def __init__(self, content, content_type):
349340
self._content = content
350341
self._content_type = content_type
351342
self._transport = None
352-
self._verbose = verbose
353343

354344
def connection_made(self, transport):
355345
self._transport = transport
356346

357347
def data_received(self, data):
358348
# dont care of request, sent data anyway...
359-
if self._verbose:
360-
pprint(data)
349+
_LOGGER.debug(data)
361350

362351
response = HttpResponse(200)
363352
# response.add_header('Content-Length', content.getbuffer().nbytes)
@@ -371,22 +360,23 @@ def data_received(self, data):
371360
class AioHeosUpnp():
372361
" Heos version of Upnp "
373362

374-
def __init__(self, loop, verbose=False):
375-
self._verbose = verbose
376-
self._upnp = Upnp(loop=loop, verbose=verbose)
363+
def __init__(self, loop):
377364
self._loop = loop
365+
self._upnp = None
378366
self._url = None
379367
self._path = None
380368
self._renderer_uri = None
381369

382370
async def discover(self):
383371
" discover "
372+
if not self._upnp:
373+
self._upnp = Upnp(loop=self._loop)
384374
self._url = await self._upnp.discover(DENON_DEVICE)
385375
return self._url
386376

387377
async def query_renderer(self):
388378
" query renderer "
389-
if not self._url:
379+
if not self._url or not self._upnp:
390380
return
391381
self._path = await self._upnp.query_renderer(
392382
AVTRANSPORT_SERVICE, self._url)
@@ -415,8 +405,7 @@ async def play_content(self, content, content_type='audio/mpeg', port=0):
415405

416406
# http server
417407
http_server = self._loop.create_server(
418-
lambda: PlayContentServer(content, content_type,
419-
verbose=self._verbose),
408+
lambda: PlayContentServer(content, content_type),
420409
sock=sock
421410
)
422411

@@ -428,12 +417,11 @@ async def play_content(self, content, content_type='audio/mpeg', port=0):
428417

429418
async def main(aioloop): # pylint: disable=redefined-outer-name
430419
" main "
420+
from pprint import pprint
431421

432-
_verbose = True
433-
upnp = AioHeosUpnp(loop=aioloop, verbose=_verbose)
422+
upnp = AioHeosUpnp(loop=aioloop)
434423
url = await upnp.discover()
435-
if _verbose:
436-
pprint(url)
424+
pprint(url)
437425

438426
print('Query renderer')
439427
await upnp.query_renderer()

aioheos/version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
" version "
2-
__version__ = '0.3.1'
2+
__version__ = '0.3.2'

0 commit comments

Comments
 (0)