Mercurial > code > home > repos > light-bridge
view light_bridge.py @ 11:028ed39aa78f
more ts types; attempted multiplayer but the change events are managed wrong
author | drewp@bigasterisk.com |
---|---|
date | Sun, 28 Jan 2024 17:31:06 -0800 |
parents | 140633abfa2a |
children | e3dbd04dab96 |
line wrap: on
line source
""" replaces a lot of mqtt_to_rdf and rdf_to_mqtt """ import asyncio import json import logging import time from functools import partial from color import Color from patchablegraph import PatchableGraph from patchablegraph.handler import GraphEvents, StaticGraph from sse_starlette.sse import EventSourceResponse from starlette.applications import Starlette from starlette.requests import Request from starlette.responses import JSONResponse from starlette.routing import Route from starlette_exporter import PrometheusMiddleware, handle_metrics from light import Lights logging.basicConfig(level=logging.INFO) log = logging.getLogger() async def output(lights: Lights, request: Request) -> JSONResponse: light = lights.byName(request.query_params['light']) body = (await request.body()).decode('utf8') await light.setColor(Color.fromHex(body)) return JSONResponse(light.to_dict()) async def table(lights: Lights, req: Request) -> EventSourceResponse: def updateMessage(): return json.dumps({'now': time.time()} | lights.to_dict()) async def g(): yield updateMessage() async for ping in lights.changes(): # broken if there's more than one caller! log.info('send table event') yield updateMessage() await asyncio.sleep(.5) # slow down the inf loop return EventSourceResponse(g()) def main(): lights = Lights() graph = PatchableGraph() app = Starlette(debug=True, routes=[ Route('/api/output', partial(output, lights), methods=['PUT']), Route('/api/table', partial(table, lights)), Route('/api/graph', StaticGraph(graph)), Route('/api/graph/events', GraphEvents(graph)), ]) app.add_middleware(PrometheusMiddleware, app_name='light-bridge') app.add_route("/metrics", handle_metrics) return app app = main()