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
|
3
|
10 from starlette.responses import PlainTextResponse
|
0
|
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
|
3
|
19 lastSuccessfulPoll = time.time()
|
0
|
20
|
3
|
21 def health(request: Request) -> PlainTextResponse:
|
|
22 if time.time() - lastSuccessfulPoll > 10:
|
|
23 return PlainTextResponse('err', status_code=500)
|
|
24 return PlainTextResponse('ok', status_code=200)
|
0
|
25
|
|
26
|
|
27 @dataclass
|
|
28 class Poller:
|
|
29 garage: pigpio.pi
|
|
30 last_motion = 0
|
|
31
|
|
32 def poll(self, first_run=False):
|
3
|
33 global lastSuccessfulPoll
|
0
|
34 now = time.time()
|
|
35 mo = self.garage.read(4)
|
|
36 SENSOR_MOTION.labels(loc='ga').set(mo)
|
|
37 if mo:
|
|
38 self.last_motion = now
|
|
39
|
|
40 light_on = self.last_motion > now - 20 * 60
|
|
41 OUTPUT_LIGHT.labels(loc='ga').set(light_on)
|
|
42 self.garage.write(15, not light_on)
|
3
|
43 lastSuccessfulPoll = time.time()
|
0
|
44
|
|
45
|
|
46 def main():
|
|
47 garage = pigpio.pi(host='garage5', port=8888)
|
|
48
|
|
49 poller = Poller(garage)
|
|
50 garage.set_mode(4, pigpio.INPUT)
|
|
51 garage.set_mode(15, pigpio.OUTPUT)
|
|
52 background_loop.loop_forever(poller.poll, 1)
|
|
53
|
|
54 app = Starlette(debug=True, routes=[
|
3
|
55 Route('/health', health),
|
0
|
56 ])
|
|
57
|
|
58 app.add_middleware(PrometheusMiddleware, app_name='pi_mqtt')
|
|
59 app.add_route("/metrics", handle_metrics)
|
|
60 return app
|
|
61
|
|
62
|
|
63 app = main()
|