I'd like to encapsulate the functionality of the python websockets package into a class, representing a sensor coordinator. The aim of this is to allow me to create a coordinator object, and only have the server persist for as long as it is needed. Unfortunately, I have not been able to find any similar examples of this online and have so far struggled.
My code is as follows:
import asyncio
import json
import logging
import websockets
logging.basicConfig()
class Coordinator(object):
def __init__(self, host='localhost', port=8080):
self.host = host
self.port = port
self.running = False
self.server = None
self.sensors = set()
def __enter__(self):
self.server = websockets.serve((self.ws_handler, self.host, self.port))
self.running = True
def __exit__(self, exc_type, exc_val, exc_tb):
# Gracefully stop serving
self.running = False
pass
def sensors_event(self):
return json.dumps({'type': 'sensors', 'count': len(self.sensors)})
async def notify_sensors(self):
if self.sensors:
message = self.sensors_event()
await asyncio.wait([user.send(message) for user in self.sensors])
async def register(self, websocket):
self.sensors.add(websocket)
await self.notify_sensors()
async def unregister(self, websocket):
self.sensors.remove(websocket)
await self.notify_sensors()
async def ws_handler(self, websocket):
try:
await self.register(websocket)
pass
finally:
await self.unregister(websocket)
if __name__ == '__main__':
with Coordinator() as coordinator:
pass
At the moment it would appear that the websocket server does not start, as it is not visible on netstat.
Would it be possible to run the server in a separate (demonised) thread, held by the coordinator object?
Thanks