from http import HTTPStatus
-async def process_command(command, pins, out_queue):
+async def process_command(command, pins, queue):
if command['command'] == 'setpin':
if command['pin'] in pins and pins[command['pin']].settable:
pins[command['pin']].value = command['value']
elif command['command'] == 'getpin':
if command['pin'] in pins:
pin = pins[command['pin']]
- await out_queue.put({'event': 'pinstate', 'pin': command['pin'],
- 'settable': pin.settable, 'value': pin.value,
- 'changed': False})
+ await queue.put({'event': 'pinstate', 'pin': command['pin'],
+ 'settable': pin.settable, 'value': pin.value,
+ 'changed': False})
elif command['command'] == 'getallpins':
for pin_name in pins:
pin = pins[pin_name]
- await out_queue.put({'event': 'pinstate', 'pin': pin_name,
- 'settable': pin.settable, 'value': pin.value,
- 'changed': False})
+ await queue.put({'event': 'pinstate', 'pin': pin_name,
+ 'settable': pin.settable, 'value': pin.value,
+ 'changed': False})
-async def command_handler(websocket, path, pins, out_queue):
+async def command_handler(websocket, path, pins, queue):
async for message in websocket:
command = json.loads(message)
- await process_command(command, pins, out_queue)
+ await process_command(command, pins, queue)
-async def event_handler(websocket, path, out_queue):
+async def event_handler(websocket, path, queue):
while True:
- event = await out_queue.get()
+ event = await queue.get()
message = json.dumps(event)
await websocket.send(message)
- out_queue.task_done()
+ queue.task_done()
-async def handler(pins, out_queue, websocket, path):
+async def handler(pins, queues, websocket, path):
+ queue = asyncio.Queue()
+ queues.append(queue)
command_task = asyncio.create_task(command_handler(websocket, path,
- pins, out_queue))
+ pins, queue))
event_task = asyncio.create_task(event_handler(websocket, path,
- out_queue))
+ queue))
done, pending = await asyncio.wait(
[command_task, event_task],
return_when=asyncio.FIRST_COMPLETED,
)
for task in pending:
task.cancel()
+ queues.remove(queue)
async def process_request(server_root, path, request_headers):
return ip
-async def setup_websocket(pins, out_queue, server_root):
- parameterised_handler = functools.partial(handler, pins, out_queue)
+async def setup_websocket(pins, queues, server_root):
+ parameterised_handler = functools.partial(handler, pins, queues)
parameterised_process_request = functools.partial(process_request, server_root)
hostname = get_ip()
await websockets.serve(parameterised_handler, hostname, 80,