aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEdi Feschiyan <edi.feschiyan@konsulko.com>2020-05-14 12:32:59 +0300
committerEdi Feschiyan <edi.feschiyan@konsulko.com>2020-06-09 09:29:49 +0300
commit32540833af3e633880aa365284c72950da27fece (patch)
tree7f319fad0d79ad2c7a10baccd012ed58876da7c1
parent219e992aa8a8e5a7db48cc9d66bb0ddbbe7c21a3 (diff)
removing waitresponse, will be using *Service.response() to get a packet. trying to figure out async generator as a service listener. WIP
-rw-r--r--aglbaseservice.py54
-rw-r--r--bluetooth.py36
-rw-r--r--geoclue.py12
-rw-r--r--gps.py29
-rw-r--r--mediaplayer.py18
-rw-r--r--test_gps.py39
6 files changed, 100 insertions, 88 deletions
diff --git a/aglbaseservice.py b/aglbaseservice.py
index ff35df4..6d68095 100644
--- a/aglbaseservice.py
+++ b/aglbaseservice.py
@@ -24,6 +24,7 @@ class AFBT(IntEnum):
EVENT = 5
msgq = {}
+AFBLEN = 3
def addrequest(msgid, msg):
msgq[msgid] = {'request': msg, 'response': None}
@@ -41,7 +42,7 @@ class AGLBaseService:
token: str
uuid: str
service = None
- logger = logging.getLogger(service)
+ logger = None
@staticmethod
def getparser():
@@ -150,45 +151,24 @@ class AGLBaseService:
return port
async def listener(self, stdout: bool = False):
- try:
- while True:
- msg = await self.receive()
- try:
- data = json.loads(msg)
- self.logger.debug('[AGL] -> ' + msg)
- if isinstance(data, list):
- if stdout:
- print(data)
- if data[0] == AFBT.RESPONSE and str.isnumeric(data[1]):
- msgid = int(data[1])
- if msgid in msgq:
- addresponse(msgid, data)
-
- except JSONDecodeError:
- self.logger.warning("Not decoding a non-json message")
+ while True:
+ data = await self.response()
+ if stdout: print(data)
+ yield data
- except KeyboardInterrupt:
- self.logger.debug("Received keyboard interrupt, exiting")
- except asyncio.CancelledError:
- self.logger.warning("Websocket listener coroutine stopped")
- except Exception as e:
- self.logger.error("Unhandled seal: " + str(e))
-
- async def response(self, stdout: bool = False):
+ async def response(self):
try:
msg = await self.websocket.recv()
try:
data = json.loads(msg)
- yield data
self.logger.debug('[AGL] -> ' + msg)
if isinstance(data, list):
- if stdout:
- print(data)
- if data[0] == AFBT.RESPONSE and str.isnumeric(data[1]):
+
+ if len(data) == AFBLEN and data[0] == AFBT.RESPONSE and str.isnumeric(data[1]):
msgid = int(data[1])
if msgid in msgq:
addresponse(msgid, data)
- yield data
+ return data
except JSONDecodeError:
self.logger.warning("Not decoding a non-json message")
@@ -199,16 +179,14 @@ class AGLBaseService:
except Exception as e:
self.logger.error("Unhandled seal: " + str(e))
- async def request(self, verb: str, values: Union[str, dict] = "", msgid: int = randint(0, 9999999),
- waitresponse: bool = False):
+ async def request(self, verb: str, values: Union[str, dict] = "", msgid: int = randint(0, 9999999)):
l = json.dumps([AFBT.REQUEST, str(msgid), f'{self.api}/{verb}', values])
self.logger.debug(f'[AGL] <- {l}')
await self.send(l)
- if waitresponse:
- return await self.receive()
+ return msgid
- async def subscribe(self, event, waitresponse=False):
- await self.request('subscribe', {'value': f'{event}'}, waitresponse=waitresponse)
+ async def subscribe(self, event):
+ return await self.request('subscribe', {'value': f'{event}'})
- async def unsubscribe(self, event, waitresponse=False):
- await self.request('unsubscribe', {'value': f'{event}'}, waitresponse=waitresponse)
+ async def unsubscribe(self, event):
+ return await self.request('unsubscribe', {'value': f'{event}'})
diff --git a/bluetooth.py b/bluetooth.py
index a28bc3c..a4bbac3 100644
--- a/bluetooth.py
+++ b/bluetooth.py
@@ -13,41 +13,41 @@ class BluetoothService(AGLBaseService):
def __init__(self, ip, port=None, service='agl-service-bluetooth'):
super().__init__(api='Bluetooth-Manager', ip=ip, port=port, service=service)
- async def subscribe(self, event='device_changes', waitresponse=False):
+ async def subscribe(self, event='device_changes'):
await super().subscribe(event=event)
- async def unsubscribe(self, event='device_changes', waitresponse=False):
+ async def unsubscribe(self, event='device_changes'):
await super().unsubscribe(event=event)
- async def managed_objects(self, waitresponse=False):
- return await self.request('managed_objects', waitresponse=waitresponse)
+ async def managed_objects(self):
+ return await self.request('managed_objects')
- async def adapter_state(self, adapter=None, value=None, waitresponse=False):
+ async def adapter_state(self, adapter=None, value=None):
p = {}
if adapter:
p = {'adapter': adapter}
if isinstance(value, dict):
p = {**p, **value}
- return await self.request('adapter_state', p, waitresponse=waitresponse)
+ return await self.request('adapter_state', p)
- async def default_adapter(self, waitresponse=False):
- return await self.request('default_adapter', "", waitresponse=waitresponse)
+ async def default_adapter(self):
+ return await self.request('default_adapter', "")
- async def connect(self, device: str = 'hci0', waitresponse=False):
- return await self.request('connect', {'device': device}, waitresponse=waitresponse)
+ async def connect(self, device: str = 'hci0'):
+ return await self.request('connect', {'device': device})
- async def disconnect(self, device: str = 'hci0', waitresponse=False):
- return await self.request('disconnect', {'device': device}, waitresponse=waitresponse)
+ async def disconnect(self, device: str = 'hci0'):
+ return await self.request('disconnect', {'device': device})
- async def pair(self, device, waitresponse=False):
- return await self.request('pair', {'device': device}, waitresponse=waitresponse)
+ async def pair(self, device):
+ return await self.request('pair', {'device': device})
- async def cancel_pairing(self, waitresponse=False):
- return await self.request('cancel_pairing', waitresponse=waitresponse)
+ async def cancel_pairing(self):
+ return await self.request('cancel_pairing')
- async def confirm_pairing(self, pincode, waitresponse=False):
- return await self.request('confirm_pairing', {'pincode': pincode}, waitresponse=waitresponse)
+ async def confirm_pairing(self, pincode):
+ return await self.request('confirm_pairing', {'pincode': pincode})
async def avrcp_controls(self):
pass
diff --git a/geoclue.py b/geoclue.py
index cbccf3b..1578b74 100644
--- a/geoclue.py
+++ b/geoclue.py
@@ -7,14 +7,14 @@ class GeoClueService(AGLBaseService):
def __init__(self, ip, port=None, api='geoclue'):
super().__init__(ip=ip, port=port, api=api, service='agl-service-geoclue')
- async def location(self, waitresponse=False):
- return await self.request('location', waitresponse=waitresponse)
+ async def location(self):
+ return await self.request('location')
- async def subscribe(self, event='location', waitresponse=False):
- await super().subscribe(event=event, waitresponse=waitresponse)
+ async def subscribe(self, event='location'):
+ await super().subscribe(event=event)
- async def unsubscribe(self, event='location', waitresponse=False):
- await super().unsubscribe(event=event, waitresponse=waitresponse)
+ async def unsubscribe(self, event='location'):
+ await super().unsubscribe(event=event)
async def main(loop):
diff --git a/gps.py b/gps.py
index 2fd1c36..61e3153 100644
--- a/gps.py
+++ b/gps.py
@@ -13,38 +13,33 @@ class GPSService(AGLBaseService):
def __init__(self, ip, port=None):
super().__init__(api='gps', ip=ip, port=port, service='agl-service-gps')
- async def location(self, waitresponse=False):
- return await self.request('location', waitresponse=waitresponse)
+ async def location(self):
+ return await self.request('location')
- async def subscribe(self, event='location', waitresponse=False):
- return await super().subscribe(event=event, waitresponse=waitresponse)
+ async def subscribe(self, event='location'):
+ return await super().subscribe(event=event)
- async def unsubscribe(self, event='location', waitresponse=False):
- return await super().subscribe(event=event, waitresponse=waitresponse)
+ async def unsubscribe(self, event='location'):
+ return await super().subscribe(event=event)
async def main(loop):
args = GPSService.parser.parse_args()
gpss = await GPSService(args.ipaddr)
- r = await loop.run_in_executor(xc, gpss.response)
+ l = await loop.run_in_executor(xc, gpss.listener)
+ # print(await r.__anext__())
if args.loglevel:
- GPSService.logger.setLevel(args.loglevel)
+ gpss.logger.setLevel(args.loglevel)
if args.location:
- await gpss.location()
- async for response in r:
- await gpss.location()
- print(await r.__anext__())
-
-
- # loc = await l
- # print(loc)
+ msgid = await gpss.location()
+ print(await gpss.receive())
if args.subscribe:
await gpss.subscribe(args.subscribe)
- await gpss.listener()
+ print(await l.__anext__())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
diff --git a/mediaplayer.py b/mediaplayer.py
index b916dd8..3466d06 100644
--- a/mediaplayer.py
+++ b/mediaplayer.py
@@ -10,16 +10,16 @@ class MediaPlayerService(AGLBaseService):
def __init__(self, ip, port = None):
super().__init__(api='mediaplayer', ip=ip, port=port, service='agl-service-mediaplayer')
- async def playlist(self, waitresponse=False):
- return await self.request('playlist', waitresponse=waitresponse)
+ async def playlist(self):
+ return await self.request('playlist')
- async def subscribe(self, event='metadata', waitresponse=False):
- await super().subscribe(event=event, waitresponse=waitresponse)
+ async def subscribe(self, event='metadata'):
+ await super().subscribe(event=event)
- async def unsubscribe(self, event='metadata', waitresponse=False):
- await super().subscribe(event=event, waitresponse=waitresponse)
+ async def unsubscribe(self, event='metadata'):
+ await super().subscribe(event=event)
- async def control(self, name, value=None, waitresponse=False):
+ async def control(self, name, value=None):
loopstate = ['off', 'playlist', 'track']
controls = {
'play': None,
@@ -53,7 +53,7 @@ class MediaPlayerService(AGLBaseService):
assert value in loopstate, f'Tried to set invalid loopstate - {value}, use "off", "playlist" or "track"'
msg = {'value': name, controls[name]: str(value)}
- await self.request('controls', msg, waitresponse=waitresponse)
+ await self.request('controls', msg)
async def main(loop):
@@ -64,7 +64,7 @@ async def main(loop):
# listener = loop.create_task(MPS.listener())
try:
await MPS.subscribe('metadata')
- print(await MPS.playlist(waitresponse=True))
+ await MPS.playlist()
await MPS.control('next')
# await listener
diff --git a/test_gps.py b/test_gps.py
new file mode 100644
index 0000000..4c8d245
--- /dev/null
+++ b/test_gps.py
@@ -0,0 +1,39 @@
+import asyncio
+import os
+import pytest
+from gps import GPSService
+from concurrent import futures
+import logging
+
+logger = logging.getLogger('pytest-gps')
+logger.setLevel(logging.DEBUG)
+
+@pytest.fixture
+async def service():
+ address = os.environ.get('AGL_TGT_IP', 'localhost')
+ gpss = await GPSService(ip=address)
+ yield gpss
+ gpss.websocket.close()
+
+# @pytest.fixture
+# async def listener(service):
+# loop = asyncio.get_event_loop()
+# xc = futures.ThreadPoolExecutor(1)
+# l = await loop.run_in_executor(xc, service.listener)
+# while True:
+# try:
+# yield l.__anext__()
+# except RuntimeError:
+# xc.shutdown()
+# except asyncio.CancelledError:
+# logger.warning("Websocket listener coroutine stopped")
+# except Exception as e:
+# logger.error(e)
+
+@pytest.mark.asyncio
+async def test_location(service):
+ await service.location()
+ r = await service.response()
+ print(r)
+ assert True
+