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