Skip to content

Commit

Permalink
Remove potential issues from init and remove Upnp printing
Browse files Browse the repository at this point in the history
  • Loading branch information
easink committed Mar 13, 2019
1 parent fb9c70c commit 33e0b74
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 67 deletions.
46 changes: 18 additions & 28 deletions aioheos/aioheoscontroller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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 """
Expand Down
64 changes: 26 additions & 38 deletions aioheos/aioheosupnp.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
"""

import asyncio
import logging
import socket
from pprint import pprint
from time import gmtime, strftime

import aiohttp
import lxml.etree

Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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',
'',
'')
Expand All @@ -204,21 +200,19 @@ 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)
self._transport.close()

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):
Expand All @@ -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))
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -310,8 +303,7 @@ async def set_avtransport_uri(self, uri, url=None):
'</s:Envelope>').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 "
Expand All @@ -328,8 +320,7 @@ async def set_play(self, url=None):
'</s:Body>'
'</s:Envelope>').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):
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
)

Expand All @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion aioheos/version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
" version "
__version__ = '0.3.1'
__version__ = '0.3.2'

0 comments on commit 33e0b74

Please sign in to comment.