aboutsummaryrefslogtreecommitdiffstats
path: root/gps.py
blob: ff6aeae96cfc7c314171d39bff7a5beef2941afa (plain)
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
from random import randint
import sys
import asyncio
from random import randint
from websockets import connect
from websockets.exceptions import ConnectionClosedError
import json
import concurrent


IPADDR = '192.168.234.34'
PORT = '30011'
# PORT = '30031'
TOKEN = 'HELLO'
UUID = 'magic'
URL = f'ws://{IPADDR}:{PORT}/api?token={TOKEN}&uuid={UUID}'

msgq = {}


class GPSService:
    def __await__(self):
        return self._async_init().__await__()

    async def _async_init(self):
        self._conn = connect(close_timeout=0, uri=URL, subprotocols=['x-afb-ws-json1'], ping_interval=1)
        self.websocket = await self._conn.__aenter__()
        return self

    async def close(self):
        await self._conn.__aexit__(*sys.exc_info())

    async def send(self, message):
        await self.websocket.send(message)

    async def receive(self):
        return await self.websocket.recv()

    async def location(self):
        msgid = randint(0, 999999)
        msgq[msgid] = {'request': msgid, 'response': None}
        await self.websocket.send(f'[2,"{msgid}","gps/location",""]')
        return await self.receive()

    async def subscribe(self, event='location'):
        msgid = randint(0, 999999)
        msg = f'[2,"{msgid}","gps/subscribe",{{"value": "{event}"}}]'
        await self.send(msg)

async def main():
    gpss = await GPSService()
    try:
        data = await gpss.receive()
        print(data)
        await gpss.subscribe()

    except ConnectionClosedError as e:
        print(e)

    finally:
        await gpss.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())