0
|
1 """
|
3
|
2 Output mqtt messages:
|
0
|
3 frontdoorlock/switch/strike/command 'ON'
|
|
4 frontdoorlock/switch/strike/command 'OFF'
|
|
5
|
3
|
6 Simple command mode:
|
|
7 PUT /api/simple/unlock
|
|
8 PUT /api/simple/lock
|
|
9 PUT /api/simple/stayUnlocked
|
0
|
10
|
3
|
11 Planned rdf mode:
|
|
12 Watch a collector graph that includes the graph from the fingerprint service.
|
|
13 When that graph contains 'unlockRequest' and an agent, we do our unlock command.
|
0
|
14 """
|
|
15
|
|
16 import asyncio
|
|
17 import logging
|
|
18 import time
|
|
19 from dataclasses import dataclass
|
1
|
20 from functools import partial
|
0
|
21 from typing import Optional, cast
|
|
22
|
|
23 import aiomqtt
|
|
24 from patchablegraph import PatchableGraph
|
|
25 from patchablegraph.handler import GraphEvents, StaticGraph
|
1
|
26 from rdfdb.patch import Patch
|
0
|
27 from rdflib import Literal, Namespace, URIRef
|
|
28 from starlette.applications import Starlette
|
1
|
29 from starlette.exceptions import HTTPException
|
0
|
30 from starlette.requests import Request
|
|
31 from starlette.responses import JSONResponse
|
|
32 from starlette.routing import Route
|
|
33 from starlette_exporter import PrometheusMiddleware, handle_metrics
|
|
34
|
|
35 from get_agent import Agent, getAgent
|
|
36
|
|
37 logging.basicConfig(level=logging.INFO)
|
|
38 log = logging.getLogger()
|
|
39
|
|
40 ROOM = Namespace('http://projects.bigasterisk.com/room/')
|
|
41 ctx = ROOM['frontDoorLockGraph']
|
|
42 lockUri = ROOM['frontDoorLock']
|
|
43
|
|
44
|
|
45 def output(graph: PatchableGraph, request: Request) -> JSONResponse:
|
|
46 return JSONResponse({"demo": "hello"})
|
|
47
|
|
48
|
|
49 def status(graph: PatchableGraph, request: Request) -> JSONResponse:
|
|
50 with graph.currentState() as current:
|
|
51 sneakGraph = current.graph # current doesn't expose __contains__
|
|
52 return JSONResponse({
|
|
53 "locked": (lockUri, ROOM['state'], ROOM['locked'], ctx) in sneakGraph,
|
|
54 "unlocked": (lockUri, ROOM['state'], ROOM['unlocked'], ctx) in sneakGraph,
|
|
55 })
|
|
56
|
|
57
|
|
58 def patchObjectToNone(g: PatchableGraph, ctx, subj, pred): #missing feature for patchObject
|
|
59 p = g.getObjectPatch(ctx, subj, pred, URIRef('unused'))
|
|
60 g.patch(Patch(delQuads=p.delQuads, addQuads=[]))
|
|
61
|
|
62
|
|
63 @dataclass
|
|
64 class LockHardware:
|
|
65 graph: PatchableGraph
|
|
66 mqtt: Optional['MqttConnection'] = None
|
|
67
|
|
68 def __post_init__(self):
|
|
69 self.writeHwLockStateToGraph(ROOM['unknown'])
|
|
70
|
|
71 def setOnline(self, yes: bool):
|
|
72 self.graph.patchObject(ctx, lockUri, ROOM['hardwareConnected'], Literal(yes))
|
|
73
|
|
74 def writeHwLockStateToGraph(self, state: URIRef):
|
|
75 self.graph.patchObject(ctx, lockUri, ROOM['state'], state)
|
|
76
|
|
77 async def unlock(self, agent: Agent | None, autoLock=True):
|
|
78 if agent is None:
|
|
79 raise HTTPException(403)
|
|
80 if self.mqtt is None:
|
|
81 raise TypeError
|
|
82 log.info("mock: await self.mqtt.sendStrikeCommand(True)")
|
|
83 await self.mqtt.sendStrikeCommand(True)
|
|
84 if autoLock:
|
|
85 asyncio.create_task(self.autoLockTask(agent, sec=6))
|
|
86
|
|
87 async def autoLockTask(self, agent: Agent, sec: float):
|
|
88 """running more than one of these should be safe"""
|
|
89 end = time.time() + sec
|
|
90 while now := time.time():
|
|
91 if now > end:
|
|
92 patchObjectToNone(self.graph, ctx, lockUri, ROOM['secondsUntilAutoLock'])
|
|
93 await self.lock(agent)
|
|
94 return
|
|
95 await asyncio.sleep(.7)
|
|
96 secUntil = round(end - now, 1)
|
|
97 self.graph.patchObject(ctx, lockUri, ROOM['secondsUntilAutoLock'], Literal(secUntil))
|
1
|
98 log.info(f"{secUntil} sec until autolock")
|
0
|
99
|
|
100 async def lock(self, agent: Agent | None):
|
|
101 if agent is None:
|
|
102 raise HTTPException(403)
|
|
103 if self.mqtt is None:
|
|
104 raise TypeError
|
|
105 await self.mqtt.sendStrikeCommand(False)
|
|
106
|
|
107
|
|
108 @dataclass
|
|
109 class MqttConnection:
|
|
110
|
|
111 hw: LockHardware
|
|
112 topicRoot: str = 'frontdoorlock'
|
|
113
|
|
114 def startup(self):
|
1
|
115 asyncio.create_task(self._go())
|
0
|
116
|
1
|
117 async def _go(self):
|
0
|
118 self.client = aiomqtt.Client("mosquitto-frontdoor", 10210, client_id="lock-service-%s" % time.time(), keepalive=6)
|
|
119 while True:
|
|
120 try:
|
|
121 async with self.client:
|
1
|
122 await self._handleMessages()
|
0
|
123 except aiomqtt.MqttError:
|
|
124 log.error('mqtt reconnecting', exc_info=True)
|
|
125 await asyncio.sleep(5)
|
|
126
|
1
|
127 async def _handleMessages(self):
|
0
|
128 async with self.client.messages() as messages:
|
|
129 await self.client.subscribe(self.topicRoot + '/#')
|
|
130 async for message in messages:
|
|
131 try:
|
1
|
132 self._onMessage(message)
|
0
|
133 except Exception:
|
|
134 log.error(f'onMessage {message=}', exc_info=True)
|
|
135 await asyncio.sleep(1)
|
|
136
|
|
137 async def sendStrikeCommand(self, value: bool):
|
|
138 await self.client.publish(self.topicRoot + '/switch/strike/command', 'ON' if value else 'OFF', qos=0, retain=False)
|
|
139
|
1
|
140 def _stateFromMqtt(self, payload: str) -> URIRef:
|
0
|
141 return {
|
|
142 'OFF': ROOM['locked'],
|
|
143 'ON': ROOM['unlocked'],
|
|
144 }[payload]
|
|
145
|
1
|
146 def _onMessage(self, message: aiomqtt.Message):
|
0
|
147 subtopic = str(message.topic).partition(self.topicRoot + '/')[2]
|
|
148 payload = cast(bytes, message.payload).decode('utf-8')
|
|
149 match subtopic:
|
|
150 case 'switch/strike/command':
|
|
151 log.info(f'command message: {subtopic} {payload=}')
|
|
152 case 'switch/strike/state':
|
|
153 log.info(f'hw reports strike state = {payload}')
|
1
|
154 self.hw.writeHwLockStateToGraph(self._stateFromMqtt(payload))
|
0
|
155 case 'status':
|
|
156 self.hw.setOnline(payload == 'online')
|
|
157 case 'debug':
|
|
158 log.info(f'hw debug: {payload}') # note: may include ansi colors
|
|
159 case _:
|
|
160 raise NotImplementedError(subtopic)
|
|
161
|
|
162
|
|
163 async def simpleCommand(hw: LockHardware, req: Request) -> JSONResponse:
|
|
164 command = req.path_params['command']
|
|
165 agent = await getAgent(req)
|
|
166 log.info(f'{command=} from {agent.asDict() if agent else agent}')
|
|
167 match command:
|
|
168 case 'unlock':
|
|
169 await hw.unlock(agent)
|
|
170 case 'lock':
|
|
171 await hw.lock(agent)
|
|
172 case 'stayUnlocked':
|
|
173 await hw.unlock(agent, autoLock=False)
|
|
174 case _:
|
|
175 raise NotImplementedError(command)
|
|
176 return JSONResponse({'ok': True})
|
|
177
|
|
178
|
|
179 def main():
|
|
180 graph = PatchableGraph()
|
|
181 hw = LockHardware(graph)
|
|
182 mqtt = MqttConnection(hw)
|
|
183 hw.mqtt = mqtt
|
|
184 app = Starlette(debug=True,
|
|
185 on_startup=[mqtt.startup],
|
|
186 routes=[
|
|
187 Route('/api/status', partial(status, graph)),
|
|
188 Route('/api/output', partial(output, graph)),
|
|
189 Route('/api/graph', StaticGraph(graph)),
|
|
190 Route('/api/graph/events', GraphEvents(graph)),
|
|
191 Route('/api/simple/{command:str}', partial(simpleCommand, hw), methods=['PUT']),
|
|
192 ])
|
|
193
|
|
194 app.add_middleware(PrometheusMiddleware, app_name='front_door_lock')
|
|
195 app.add_route("/metrics", handle_metrics)
|
|
196
|
|
197 return app
|
|
198
|
|
199
|
|
200 app = main()
|