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