|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +import socket |
| 4 | +import time |
| 5 | + |
| 6 | +from async_event_emitter import AsyncEventEmitter |
| 7 | + |
| 8 | +class PlugListener(AsyncEventEmitter): |
| 9 | + """An interface class for accessing the event stream from a single plug. |
| 10 | + The following events may be emitted: |
| 11 | + - ("connecting") Whenever a connection attempt is made. |
| 12 | + - ("connected") When a connection is successful. |
| 13 | + - ("disconnected") When a connection is dropped, be it intentional or not. |
| 14 | + - ("message",{...}) For each event message received from the plug. The |
| 15 | + plug's JSON message is decoded into a dict which is passed as the second |
| 16 | + argument to the registered event handler(s). The event handlers must be |
| 17 | + async. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, ip, port=49476): |
| 21 | + """Initialises a PlugListener object, bound to the given IP address. |
| 22 | + The port number may be overridden if necessary.""" |
| 23 | + super().__init__() |
| 24 | + self._ip = ip |
| 25 | + self._port = port |
| 26 | + self._task = None |
| 27 | + self._connection = None |
| 28 | + self._disconnecting = False |
| 29 | + |
| 30 | + def connect(self): |
| 31 | + """Initiates the connection to the plug. The object will automatically |
| 32 | + retry as necessary if/when it can't connect to the plug, until such |
| 33 | + a time disconnect() is called.""" |
| 34 | + if self._task is not None: |
| 35 | + raise RuntimeError("already connected/connecting") |
| 36 | + self._disconnecting = False |
| 37 | + self._task = asyncio.create_task(self._do_connection()) |
| 38 | + |
| 39 | + async def disconnect(self): |
| 40 | + """Goes through the disconnection process towards a plug. No further |
| 41 | + automatic reconnects will take place, until connect() is called.""" |
| 42 | + if self._task is None: |
| 43 | + return |
| 44 | + |
| 45 | + self._disconnecting = True |
| 46 | + |
| 47 | + await self._close_connection() |
| 48 | + |
| 49 | + if self._task is not None: |
| 50 | + await self._task |
| 51 | + self._task = None |
| 52 | + |
| 53 | + async def _close_connection(self): |
| 54 | + if self._connection is not None: |
| 55 | + (reader, writer) = self._connection |
| 56 | + self._connection = None |
| 57 | + |
| 58 | + writer.close() |
| 59 | + await writer.wait_closed() |
| 60 | + |
| 61 | + await self.emit('disconnected') |
| 62 | + |
| 63 | + async def _do_connection(self, backoff = 0): |
| 64 | + if backoff < 9: |
| 65 | + backoff += 1 |
| 66 | + try: |
| 67 | + await self.emit('connecting') |
| 68 | + reader, writer = await asyncio.open_connection(self._ip, self._port) |
| 69 | + self._connection = (reader, writer) |
| 70 | + |
| 71 | + await self._send_subscribe(writer) |
| 72 | + backoff = 1 |
| 73 | + |
| 74 | + await self.emit('connected') |
| 75 | + |
| 76 | + while not self._disconnecting: |
| 77 | + await self._process_line(reader, writer) |
| 78 | + |
| 79 | + except (ConnectionResetError, asyncio.TimeoutError): |
| 80 | + # Handle disconnection and retry with exponential backoff |
| 81 | + await self._close_connection() |
| 82 | + if self._disconnecting: |
| 83 | + return |
| 84 | + await asyncio.sleep(min(5 * 60, 2**backoff * 1)) |
| 85 | + return await self._do_connection(backoff) |
| 86 | + |
| 87 | + async def _process_line(self, reader, writer): |
| 88 | + data = await reader.readline() |
| 89 | + if data == b'': |
| 90 | + raise ConnectionResetError |
| 91 | + if data != b'\n': # Silently ignore empty lines |
| 92 | + try: |
| 93 | + message = json.loads(data.decode('utf-8')) |
| 94 | + typ = message['type'] |
| 95 | + if typ == 'subscription': |
| 96 | + if message['subtype'] == 'warning': |
| 97 | + await self._send_subscribe(writer) |
| 98 | + elif typ == 'discovery': |
| 99 | + pass |
| 100 | + else: |
| 101 | + await self.emit('message', message) |
| 102 | + except (json.decoder.JSONDecodeError) as ex: |
| 103 | + print(f"JSON error {ex} from {data}") |
| 104 | + |
| 105 | + async def _send_subscribe(self, writer): |
| 106 | + writer.write(b'subscribe(60)\n') |
| 107 | + await writer.drain() |
0 commit comments