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