annotate front_door_lock.py @ 3:89d47e203fc2

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