new client connection logic
- esp32 requests for image when ready to receive - server serves initial image on request
This commit is contained in:
@@ -17,6 +17,7 @@ Protocol:
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -68,17 +69,17 @@ async def handler(ws):
|
||||
|
||||
configs = load_config(_config_path)
|
||||
img_idle = load_status_image(IMG_DIR / "idle.png")
|
||||
current_img = img_idle
|
||||
|
||||
try:
|
||||
await send_status_image(ws, img_idle)
|
||||
alarms = [_prepare_alarm(entry) for entry in configs] if configs else []
|
||||
|
||||
if not configs:
|
||||
async def alarm_ticker():
|
||||
nonlocal current_img
|
||||
if not alarms:
|
||||
log.info("No alarms configured — idling forever")
|
||||
await asyncio.Future()
|
||||
return
|
||||
|
||||
alarms = [_prepare_alarm(entry) for entry in configs]
|
||||
|
||||
while True:
|
||||
for alarm in alarms:
|
||||
if should_fire(alarm["config"]):
|
||||
@@ -88,13 +89,28 @@ async def handler(ws):
|
||||
alarm["last_fired"] = current_minute
|
||||
log.info("Alarm firing: %s at %s",
|
||||
alarm["config"]["alarm_time"], current_minute)
|
||||
await send_status_image(ws, alarm["img"])
|
||||
current_img = alarm["img"]
|
||||
await send_status_image(ws, current_img)
|
||||
await stream_alarm(ws, alarm["pcm"], alarm["sr"],
|
||||
alarm["ch"], alarm["bits"])
|
||||
await send_status_image(ws, img_idle)
|
||||
current_img = img_idle
|
||||
await send_status_image(ws, current_img)
|
||||
|
||||
await asyncio.sleep(TICK_INTERVAL)
|
||||
|
||||
async def receiver():
|
||||
async for msg in ws:
|
||||
try:
|
||||
data = json.loads(msg)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
continue
|
||||
if data.get("type") == "request_image":
|
||||
log.info("Client requested image — sending current (%d bytes)",
|
||||
len(current_img))
|
||||
await send_status_image(ws, current_img)
|
||||
|
||||
try:
|
||||
await asyncio.gather(alarm_ticker(), receiver())
|
||||
except websockets.exceptions.ConnectionClosed:
|
||||
log.info("Client disconnected: %s:%d", remote[0], remote[1])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user