Mercurial > code > home > repos > light-bridge
annotate light_bridge.py @ 7:05fb0319eb64
cleanup
author | drewp@bigasterisk.com |
---|---|
date | Sun, 28 Jan 2024 16:03:40 -0800 |
parents | fc8ed0efcd72 |
children | 140633abfa2a |
rev | line source |
---|---|
0 | 1 """ |
2 replaces a lot of mqtt_to_rdf and rdf_to_mqtt | |
3 """ | |
4 import json | |
5 import logging | |
7 | 6 import time |
2 | 7 from functools import partial |
0 | 8 |
9 from patchablegraph import PatchableGraph | |
10 from patchablegraph.handler import GraphEvents, StaticGraph | |
2 | 11 from sse_starlette.sse import EventSourceResponse |
0 | 12 from starlette.applications import Starlette |
13 from starlette.requests import Request | |
14 from starlette.responses import JSONResponse | |
15 from starlette.routing import Route | |
16 from starlette_exporter import PrometheusMiddleware, handle_metrics | |
2 | 17 |
7 | 18 from light import Lights |
0 | 19 |
20 logging.basicConfig(level=logging.INFO) | |
21 log = logging.getLogger() | |
22 | |
23 | |
24 async def output(lights: Lights, request: Request) -> JSONResponse: | |
25 light = lights.byName(request.query_params['light']) | |
5
7eeda7f4f9cd
spell it to_dict, for compat with DataClassJsonMixin
drewp@bigasterisk.com
parents:
2
diff
changeset
|
26 return JSONResponse(light.to_dict()) |
0 | 27 |
28 | |
29 async def table(lights: Lights, req: Request) -> EventSourceResponse: | |
30 | |
31 async def g(): | |
32 async for ping in lights.changes(): | |
5
7eeda7f4f9cd
spell it to_dict, for compat with DataClassJsonMixin
drewp@bigasterisk.com
parents:
2
diff
changeset
|
33 yield json.dumps({'now': time.time()} | lights.to_dict()) |
0 | 34 |
35 return EventSourceResponse(g()) | |
36 | |
37 | |
38 def main(): | |
39 lights = Lights() | |
40 graph = PatchableGraph() | |
41 app = Starlette(debug=True, | |
42 routes=[ | |
43 Route('/api/output', partial(output, lights), methods=['PUT']), | |
44 Route('/api/table', partial(table, lights)), | |
45 Route('/api/graph', StaticGraph(graph)), | |
46 Route('/api/graph/events', GraphEvents(graph)), | |
47 ]) | |
48 | |
49 app.add_middleware(PrometheusMiddleware, app_name='light-bridge') | |
50 app.add_route("/metrics", handle_metrics) | |
51 | |
52 return app | |
53 | |
54 | |
55 app = main() |