0
|
1 import logging
|
|
2 import time
|
|
3 from dataclasses import dataclass
|
|
4
|
|
5 import background_loop
|
|
6 import pigpio
|
|
7 from prometheus_client import Gauge
|
|
8 from starlette.applications import Starlette
|
|
9 from starlette.requests import Request
|
|
10 from starlette.responses import JSONResponse
|
|
11 from starlette.routing import Route
|
|
12 from starlette_exporter import PrometheusMiddleware, handle_metrics
|
|
13
|
|
14 SENSOR_MOTION = Gauge('sensor_motion', 'motion detected', ['loc'])
|
|
15 OUTPUT_LIGHT = Gauge('output_light', 'light level', ['loc'])
|
|
16 logging.basicConfig(level=logging.INFO)
|
|
17 log = logging.getLogger()
|
|
18
|
|
19
|
|
20 def hello(request: Request) -> JSONResponse:
|
|
21 return JSONResponse({"demo": "hello"})
|
|
22
|
|
23
|
|
24 @dataclass
|
|
25 class Poller:
|
|
26 garage: pigpio.pi
|
|
27 last_motion = 0
|
|
28
|
|
29 def poll(self, first_run=False):
|
|
30 now = time.time()
|
|
31 mo = self.garage.read(4)
|
|
32 SENSOR_MOTION.labels(loc='ga').set(mo)
|
|
33 if mo:
|
|
34 self.last_motion = now
|
|
35
|
|
36 light_on = self.last_motion > now - 20 * 60
|
|
37 OUTPUT_LIGHT.labels(loc='ga').set(light_on)
|
|
38 self.garage.write(15, not light_on)
|
|
39
|
|
40
|
|
41 def main():
|
|
42 garage = pigpio.pi(host='garage5', port=8888)
|
|
43
|
|
44 poller = Poller(garage)
|
|
45 garage.set_mode(4, pigpio.INPUT)
|
|
46 garage.set_mode(15, pigpio.OUTPUT)
|
|
47 background_loop.loop_forever(poller.poll, 1)
|
|
48
|
|
49 app = Starlette(debug=True, routes=[
|
|
50 Route('/api/hello', hello),
|
|
51 ])
|
|
52
|
|
53 app.add_middleware(PrometheusMiddleware, app_name='pi_mqtt')
|
|
54 app.add_route("/metrics", handle_metrics)
|
|
55 return app
|
|
56
|
|
57
|
|
58 app = main()
|