From 33e0b74fe4f2faaffa6743a8cb3e5b86eb05259f Mon Sep 17 00:00:00 2001 From: Andreas Rydbrink Date: Wed, 13 Mar 2019 19:01:52 +0100 Subject: [PATCH] Remove potential issues from init and remove Upnp printing --- aioheos/aioheoscontroller.py | 46 ++++++++++---------------- aioheos/aioheosupnp.py | 64 +++++++++++++++--------------------- aioheos/version.py | 2 +- 3 files changed, 45 insertions(+), 67 deletions(-) diff --git a/aioheos/aioheoscontroller.py b/aioheos/aioheoscontroller.py index 815811e..3a57a56 100755 --- a/aioheos/aioheoscontroller.py +++ b/aioheos/aioheoscontroller.py @@ -97,7 +97,6 @@ def __init__(self, host=None, username=None, password=None, - verbose=False, new_device_callback=None): self._host = host self._loop = loop @@ -108,9 +107,8 @@ def __init__(self, self._players = None self._groups = None - self._verbose = verbose self._player_id = None - self._upnp = aioheosupnp.AioHeosUpnp(loop=loop, verbose=verbose) + self._upnp = None self._reader = None self._writer = None self._subscribtion_task = None @@ -168,12 +166,13 @@ async def connect(self, host=None, port=HEOS_PORT, callback=None): self._host = host elif not self._host: # discover + if not self._upnp: + self._upnp = aioheosupnp.AioHeosUpnp(loop=self._loop) url = await self._upnp.discover() self._host = self._url_to_addr(url) # connect - if self._verbose: - _LOGGER.debug('[I] Connecting to %s:%s', self._host, port) + _LOGGER.debug('[I] Connecting to %s:%s', self._host, port) await self._connect(self._host, port) # please, do not prettify json @@ -211,8 +210,8 @@ async def _connect(self, host, port=HEOS_PORT): _LOGGER.warning('[W] Connection refused' ', will try %s:%s again in %d seconds ...', host, port, wait) - except Exception as e: - _LOGGER.error('[E] %s', e) + except Exception as exc: # pylint: disable=broad-except + _LOGGER.error('[E] %s', exc) await asyncio.sleep(wait) @@ -225,8 +224,7 @@ def send_command(self, command, message=None): msg += '?' + '&'.join("{}={}".format(key, val) for (key, val) in message.items()) msg += '\r\n' - if self._verbose: - _LOGGER.debug(msg) + _LOGGER.debug(msg) self._writer.write(msg.encode('ascii')) @staticmethod @@ -257,10 +255,8 @@ def _handle_error(self, message): def _dispatcher(self, command, message, payload): """Call parser functions.""" - # if self._verbose: - if self._verbose: - _LOGGER.debug('DISPATCHER') - _LOGGER.debug('[D] %s %s %s', command, message, payload) + _LOGGER.debug('DISPATCHER') + _LOGGER.debug('[D] %s %s %s', command, message, payload) callbacks = { GET_PLAYERS: self._parse_players, @@ -310,8 +306,7 @@ def _dispatcher(self, command, message, payload): if command in callbacks: callbacks[command](payload, message) elif command in commands_ignored: - if self._verbose: - _LOGGER.debug('[D] command "%s" is ignored.', command) + _LOGGER.debug('[D] command "%s" is ignored.', command) else: _LOGGER.debug('[D] command "%s" is not handled.', command) @@ -374,25 +369,21 @@ async def _async_subscribe(self, callback=None): return except Exception as exc: # pylint: disable=broad-except _LOGGER.error('[E] Ignoring', exc) - if self._verbose: - _LOGGER.debug(msg.decode()) + _LOGGER.debug(msg.decode()) # simplejson doesnt need to decode from byte to ascii data = json.loads(msg.decode()) - if self._verbose: - _LOGGER.debug('DATA:') - _LOGGER.debug(data) + _LOGGER.debug('DATA:') + _LOGGER.debug(data) try: self._parse_command(data) except AioHeosException as exc: _LOGGER.error('[E]', exc) - if self._verbose: - _LOGGER.debug('MSG', msg) - _LOGGER.debug('MSG decoded', msg.decode()) - _LOGGER.debug('MSG json', data) + _LOGGER.debug('MSG', msg) + _LOGGER.debug('MSG decoded', msg.decode()) + _LOGGER.debug('MSG json', data) continue if callback: - if self._verbose: - _LOGGER.debug('TRIGGER CALLBACK') + _LOGGER.debug('TRIGGER CALLBACK') self._loop.create_task(self._callback_wrapper(callback)) def new_device_callback(self, callback): @@ -581,8 +572,7 @@ def _parse_now_playing_media(self, payload, message): player.qid = payload.get('qid') - if self._verbose: - _LOGGER.debug("[D] _parse_now_playing_media %s", vars(player)) + _LOGGER.debug("[D] _parse_now_playing_media %s", vars(player)) def get_favourites(self): """ get duration """ diff --git a/aioheos/aioheosupnp.py b/aioheos/aioheosupnp.py index 2cc7468..3091e1b 100755 --- a/aioheos/aioheosupnp.py +++ b/aioheos/aioheosupnp.py @@ -9,9 +9,10 @@ """ import asyncio +import logging import socket -from pprint import pprint from time import gmtime, strftime + import aiohttp import lxml.etree @@ -23,6 +24,8 @@ MEDIA_DEVICE = 'urn:schemas-upnp-org:device:MediaRenderer:1' AVTRANSPORT_SERVICE = 'urn:schemas-upnp-org:service:AVTransport:1' +_LOGGER = logging.getLogger(__name__) + def _get_ipaddress(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -138,12 +141,7 @@ class Upnp(): " Upnp class " # pylint: disable=redefined-outer-name - def __init__(self, - loop, - ssdp_host=SSDP_HOST, - ssdp_port=SSDP_PORT, - verbose=False): - self._verbose = verbose + def __init__(self, loop, ssdp_host=SSDP_HOST, ssdp_port=SSDP_PORT): self._loop = loop self._ssdp_host = ssdp_host self._ssdp_port = ssdp_port @@ -157,17 +155,15 @@ def __init__(self, class DiscoverProtocol: """ Discovery Protocol """ - def __init__(self, upnp, future, search_target, verbose=False): + def __init__(self, upnp, future, search_target): self._upnp = upnp self._future = future self._search_target = search_target self._transport = None - self._verbose = verbose def connection_made(self, transport): """ Protocol connection made """ - if self._verbose: - print('Connection made') + _LOGGER.debug('Connection made') self._transport = transport sock = self._transport.get_extra_info('socket') # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) @@ -182,7 +178,7 @@ def connection_made(self, transport): str(self._upnp.ssdp_port), 'Man: "ssdp:discover"', 'ST: {}'.format(self._search_target), - # 'ST: ssdp:all', + # 'ST: ssdp:all', 'MX: 3', '', '') @@ -204,8 +200,7 @@ def datagram_received(self, data, _): for k, v in [item.split(': ') for item in content if ": " in item] } - if self._verbose: - print(reply['st']) + _LOGGER.debug(reply['st']) if reply['st'] == self._search_target: url = reply['location'] self._future.set_result(url) @@ -213,12 +208,11 @@ def datagram_received(self, data, _): def error_received(self, exc): # pylint: disable=no-self-use """ error received """ - print('[E] Error received:', exc) + _LOGGER.error('[E] Error received: ', exc) def connection_lost(self, _): """ connection lost """ - if self._verbose: - print("[I] Connection lost.") + _LOGGER.warning("[I] Connection lost.") self._transport.close() async def discover(self, search_target, _addr=None): @@ -227,7 +221,7 @@ async def discover(self, search_target, _addr=None): self._asyncio_ensure_future( self._loop.create_datagram_endpoint( lambda: Upnp.DiscoverProtocol( - self, future, search_target, self._verbose + self, future, search_target ), family=socket.AF_INET, proto=socket.IPPROTO_UDP)) @@ -264,8 +258,7 @@ async def _soapaction(self, service, action, url=None, body=None): content = await response.read() await response.release() - if self._verbose: - print(content) + _LOGGER.debug(content) return content async def query_renderer(self, service, url=None): @@ -310,8 +303,7 @@ async def set_avtransport_uri(self, uri, url=None): '').format( service=service, uri=uri) response_xml = await self._soapaction(service, action, url, body) - if self._verbose: - pprint(response_xml) + _LOGGER.debug(response_xml) async def set_play(self, url=None): " play " @@ -328,8 +320,7 @@ async def set_play(self, url=None): '' '').format(service) response_xml = await self._soapaction(service, "Play", url, body) - if self._verbose: - pprint(response_xml) + _LOGGER.debug(response_xml) @property def ssdp_host(self): @@ -345,19 +336,17 @@ def ssdp_port(self): class PlayContentServer(asyncio.Protocol): """ Play Content Server """ - def __init__(self, content, content_type, verbose=False): + def __init__(self, content, content_type): self._content = content self._content_type = content_type self._transport = None - self._verbose = verbose def connection_made(self, transport): self._transport = transport def data_received(self, data): # dont care of request, sent data anyway... - if self._verbose: - pprint(data) + _LOGGER.debug(data) response = HttpResponse(200) # response.add_header('Content-Length', content.getbuffer().nbytes) @@ -371,22 +360,23 @@ def data_received(self, data): class AioHeosUpnp(): " Heos version of Upnp " - def __init__(self, loop, verbose=False): - self._verbose = verbose - self._upnp = Upnp(loop=loop, verbose=verbose) + def __init__(self, loop): self._loop = loop + self._upnp = None self._url = None self._path = None self._renderer_uri = None async def discover(self): " discover " + if not self._upnp: + self._upnp = Upnp(loop=self._loop) self._url = await self._upnp.discover(DENON_DEVICE) return self._url async def query_renderer(self): " query renderer " - if not self._url: + if not self._url or not self._upnp: return self._path = await self._upnp.query_renderer( AVTRANSPORT_SERVICE, self._url) @@ -415,8 +405,7 @@ async def play_content(self, content, content_type='audio/mpeg', port=0): # http server http_server = self._loop.create_server( - lambda: PlayContentServer(content, content_type, - verbose=self._verbose), + lambda: PlayContentServer(content, content_type), sock=sock ) @@ -428,12 +417,11 @@ async def play_content(self, content, content_type='audio/mpeg', port=0): async def main(aioloop): # pylint: disable=redefined-outer-name " main " + from pprint import pprint - _verbose = True - upnp = AioHeosUpnp(loop=aioloop, verbose=_verbose) + upnp = AioHeosUpnp(loop=aioloop) url = await upnp.discover() - if _verbose: - pprint(url) + pprint(url) print('Query renderer') await upnp.query_renderer() diff --git a/aioheos/version.py b/aioheos/version.py index be39dd9..3c25ed0 100644 --- a/aioheos/version.py +++ b/aioheos/version.py @@ -1,2 +1,2 @@ " version " -__version__ = '0.3.1' +__version__ = '0.3.2'