Coverage for src/anpr2mqtt/app.py: 87%

165 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-23 13:55 +0000

1import logging 

2import sys 

3from typing import Any 

4 

5import paho.mqtt.client as mqtt 

6import structlog 

7from paho.mqtt.enums import CallbackAPIVersion, MQTTErrorCode, MQTTProtocolVersion 

8from paho.mqtt.properties import Properties 

9from paho.mqtt.reasoncodes import ReasonCode 

10from pydantic import ValidationError 

11from pydantic_settings import CliApp 

12from watchdog.observers import Observer 

13 

14import anpr2mqtt 

15from anpr2mqtt.event_handler import EventHandler, verify_ocr 

16from anpr2mqtt.frigate_handler import CameraConfig, FrigateHandler 

17from anpr2mqtt.handler_common import SUBSCRIPTIONS 

18from anpr2mqtt.hass import ( 

19 AVAILABILITY_OFFLINE, 

20 OFFLINE_PUBLISH_TIMEOUT, 

21 HomeAssistantPublisher, 

22 availability_topic, 

23 publish_availability, 

24) 

25from anpr2mqtt.heartbeat import Heartbeat 

26from anpr2mqtt.settings import LINK_FRIGATE, CameraSettings, EventSettings, Settings, linked_cameras 

27from anpr2mqtt.tracker import Tracker, compute_time_analysis 

28 

29log = structlog.get_logger() 

30# run like docker run --restart always -d -v /ftp:/ftp d4d8dea7d1e3 

31 

32 

33def on_connect( 

34 client: mqtt.Client, 

35 userdata: Any, 

36 _flags: mqtt.ConnectFlags, 

37 rc: ReasonCode, 

38 _props: Properties | None = None, 

39) -> None: 

40 log.debug("on_connect, MQTT result code " + str(rc)) 

41 if rc.getName() == "Not authorized": 

42 log.error("Invalid MQTT credentials", result_code=rc) 

43 return 

44 if rc != 0: 

45 log.warning("Connection failed to broker", result_code=rc) 

46 else: 

47 log.debug("Connected to broker", result_code=rc) 

48 if isinstance(userdata, dict) and userdata.get("availability_topic"): 

49 # on every (re)connect, since the will may have marked us offline while disconnected 

50 publish_availability(client, userdata["availability_topic"], online=True) 

51 if isinstance(userdata, dict): 

52 # clean session, so the broker has dropped any subscriptions from a previous connection 

53 for topic in list(userdata.get(SUBSCRIPTIONS, [])): 

54 log.debug("(Re)subscribing", topic=topic) 

55 client.subscribe(topic) 

56 

57 

58def on_disconnect( 

59 _client: mqtt.Client, 

60 _userdata: Any, 

61 _disconnect_flags: mqtt.DisconnectFlags, 

62 rc: ReasonCode, 

63 _props: Properties | None, 

64) -> None: 

65 if rc == 0: 

66 log.debug("Disconnected from broker", result_code=rc) 

67 else: 

68 log.warning("Disconnect failure from broker", result_code=rc) 

69 

70 

71def main_loop() -> None: 

72 """Watch a directory, post any matching files to MQTT after optionally analyzing the image""" 

73 structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(logging.INFO)) 

74 settings: Settings = Settings() 

75 if settings.log_level != "INFO": 

76 structlog.configure(wrapper_class=structlog.make_filtering_bound_logger(getattr(logging, str(settings.log_level)))) 

77 log.info("ANPR2MQTT %s starting up", anpr2mqtt.version) # pyright: ignore[reportAttributeAccessIssue] 

78 for target_type in settings.targets: 

79 log.info( 

80 "ANPR2MQTT %s target groups, %s corrections, %s ignore patterns", 

81 len(settings.targets[target_type].groups), 

82 len(settings.targets[target_type].correction), 

83 len(settings.targets[target_type].ignore), 

84 ) 

85 if settings.ocr.verify_on_startup and any(event.ocr_field_ids for event in settings.events): 

86 verify_ocr() 

87 

88 client: mqtt.Client 

89 publisher: HomeAssistantPublisher 

90 protocol: MQTTProtocolVersion 

91 if settings.mqtt.protocol in ("3", "3.11"): 

92 protocol = MQTTProtocolVersion.MQTTv311 

93 elif settings.mqtt.protocol == "3.1": 

94 protocol = MQTTProtocolVersion.MQTTv31 

95 elif settings.mqtt.protocol in ("5", "5.0"): 

96 protocol = MQTTProtocolVersion.MQTTv5 

97 else: 

98 log.info("No valid MQTT protocol version found (%s), setting to default v3.11", settings.mqtt.protocol) 

99 protocol = MQTTProtocolVersion.MQTTv311 

100 log.debug("MQTT protocol set to %r", protocol) 

101 

102 avail_topic: str = availability_topic(settings.mqtt.topic_root) 

103 try: 

104 client = mqtt.Client( 

105 callback_api_version=CallbackAPIVersion.VERSION2, 

106 clean_session=True if protocol != MQTTProtocolVersion.MQTTv5 else None, 

107 client_id="anpr2mqtt", 

108 protocol=protocol, 

109 userdata={"availability_topic": avail_topic, SUBSCRIPTIONS: []}, 

110 ) 

111 # broker publishes this if the connection drops without a clean disconnect, e.g. a crash or kill 

112 client.will_set(avail_topic, payload=AVAILABILITY_OFFLINE, qos=1, retain=True) 

113 client.on_connect = on_connect 

114 client.on_disconnect = on_disconnect 

115 client.username_pw_set(username=settings.mqtt.user, password=settings.mqtt.password) 

116 rc: MQTTErrorCode = client.connect(host=settings.mqtt.host, port=int(settings.mqtt.port), keepalive=60) 

117 log.info("Client connection requested", result_code=rc) 

118 client.loop_start() 

119 log.info(f"Connected to MQTT at {settings.mqtt.host}:{settings.mqtt.port} as {settings.mqtt.user}") 

120 log.info(f"Publishing at {settings.mqtt.topic_root}") 

121 publisher = HomeAssistantPublisher(client, settings.homeassistant, availability_topic=avail_topic) 

122 

123 except Exception as e: 

124 log.error("Failed to connect to MQTT: %s", e, exc_info=1) 

125 sys.exit(-500) 

126 

127 try: 

128 observer = Observer() 

129 except Exception as e: 

130 log.error("Failed to setup file system watchdog: %s", e) 

131 sys.exit(-400) 

132 

133 # Maps camera name → (event_config, camera_settings, tracker, state_topic, image_topic) 

134 # Used by FrigateHandler to share the same pipeline as filesystem events. 

135 frigate_camera_configs: dict[str, CameraConfig] = {} 

136 

137 for event_config in settings.events: 

138 camera: CameraSettings | None = None 

139 try: 

140 for camera_config in settings.cameras: 

141 if camera_config.name == event_config.camera: 

142 camera = camera_config 

143 if camera is None: 

144 camera = CameraSettings(name=event_config.camera) 

145 # resolved once, so Home Assistant is told the same Frigate camera that events are routed by 

146 camera = camera.model_copy(update={"linked_cameras": linked_cameras(camera, settings.frigate)}) 

147 state_topic = f"{settings.mqtt.topic_root}/{event_config.event}/cameras/{camera.name}/state" 

148 image_topic = f"{settings.mqtt.topic_root}/{event_config.event}/cameras/{camera.name}/image" 

149 tracker = Tracker( 

150 event_config.target_type, 

151 tracker_config=settings.tracker, 

152 target_config=settings.targets.get(event_config.target_type), 

153 region=event_config.region, 

154 auto_match_tolerance=event_config.auto_match_tolerance, 

155 ) 

156 # keyed by the Frigate camera, so a differently named one is published as this camera 

157 frigate_key = camera.linked_cameras.get(LINK_FRIGATE, camera.name) 

158 if frigate_key not in frigate_camera_configs: 158 ↛ 160line 158 didn't jump to line 160 because the condition on line 158 was always true

159 frigate_camera_configs[frigate_key] = (event_config, camera, tracker, state_topic, image_topic) 

160 event_handler = EventHandler( 

161 publisher=publisher, 

162 event_config=event_config, 

163 state_topic=state_topic, 

164 camera=camera, 

165 image_topic=image_topic, 

166 ocr_config=settings.ocr, 

167 image_config=settings.image, 

168 dvla_config=settings.dvla, 

169 tracker=tracker, 

170 mqtt_topic_root=settings.mqtt.topic_root, 

171 ) 

172 log.debug("Scheduling watchdog for %s", event_config.watch_path) 

173 observer.schedule(event_handler, str(event_config.watch_path), recursive=event_config.watch_tree) 

174 publisher.publish_sensor_discovery(state_topic=state_topic, event_config=event_config, camera=camera) 

175 if settings.homeassistant.image_entity: 

176 publisher.publish_image_discovery( 

177 state_topic=state_topic, image_topic=image_topic, event_config=event_config, camera=camera 

178 ) 

179 if settings.homeassistant.camera_entity: 

180 publisher.publish_camera_discovery( 

181 state_topic=state_topic, image_topic=image_topic, event_config=event_config, camera=camera 

182 ) 

183 # selectively publish known targets as HA sensors, using last seen timestamp as state value 

184 for entity_id, targets in tracker.entities.items(): 184 ↛ 185line 184 didn't jump to line 185 because the loop on line 184 never started

185 target_topic: str = f"{settings.mqtt.topic_root}/{event_config.event}/targets/{entity_id}/state" 

186 log.info("Publishing sensor.%s for %s targets", entity_id, len(targets)) 

187 icon: str | None = targets[0].icon if len(targets) > 1 and targets[0].icon else event_config.icon 

188 publisher.publish_target_sensor_discovery( 

189 entity_id=entity_id, 

190 target_type=event_config.target_type, 

191 icon=icon, 

192 targets=targets, 

193 state_topic=target_topic, 

194 ) 

195 

196 previous_sightings: list[str] = [] 

197 for target in targets: 

198 previous_sightings.extend(tracker.history(target.id, target.target_type)) 

199 if previous_sightings: 

200 time_analysis: dict[str, Any] = compute_time_analysis(sorted(previous_sightings)) 

201 else: 

202 time_analysis = {"last_seen": None} 

203 publisher.publish_target_state( 

204 state_topic=target_topic, 

205 time_analysis=time_analysis, 

206 ) 

207 

208 # post initial empty state message 

209 publisher.post_state_message(state_topic, sighting=None, event_config=event_config, camera=camera) 

210 log.info("Publishing %s %s state to %s", event_config.event, camera.name, state_topic) 

211 except Exception as e: 

212 log.error( 

213 "Failed to schedule event %s %s watchdog: %s", 

214 event_config.event, 

215 camera.name if camera else "unknown camera", 

216 e, 

217 ) 

218 

219 publisher.start() 

220 observer.start() 

221 

222 if settings.frigate.enabled: 

223 event_settings: EventSettings | None = None 

224 for cfg in settings.events: 224 ↛ 228line 224 didn't jump to line 228 because the loop on line 224 didn't complete

225 if cfg.target_type == "plate": 225 ↛ 224line 225 didn't jump to line 224 because the condition on line 225 was always true

226 event_settings = cfg 

227 break 

228 event_settings = event_settings or EventSettings(target_type="plate") 

229 

230 default_tracker = Tracker( 

231 target_type="plate", 

232 tracker_config=settings.tracker, 

233 target_config=settings.targets.get("plate"), 

234 region=event_settings.region, 

235 auto_match_tolerance=event_settings.auto_match_tolerance, 

236 ) 

237 frigate_handler = FrigateHandler( 

238 mqtt_client=client, 

239 frigate_settings=settings.frigate, 

240 publisher=publisher, 

241 image_settings=settings.image, 

242 dvla_settings=settings.dvla, 

243 camera_configs=frigate_camera_configs, 

244 mqtt_topic_root=settings.mqtt.topic_root, 

245 default_tracker=default_tracker, 

246 ) 

247 frigate_handler.start() 

248 else: 

249 log.info("Frigate listener disabled") 

250 

251 heartbeat = Heartbeat() 

252 try: 

253 log.info("Starting observer loop") 

254 while observer.is_alive(): 

255 # only while connected, so the healthcheck also fails if the broker connection is lost 

256 if client.is_connected(): 256 ↛ 258line 256 didn't jump to line 258 because the condition on line 256 was always true

257 heartbeat.beat() 

258 observer.join(1) 

259 except Exception as e: 

260 log.error("Failed in run observer loop: %s", e, exc_info=1) 

261 finally: 

262 heartbeat.clear() 

263 observer.stop() 

264 observer.join() 

265 log.info("loop observer ended") 

266 shutdown_mqtt(client, avail_topic) 

267 

268 

269def shutdown_mqtt(client: mqtt.Client, avail_topic: str) -> None: 

270 """Mark entities unavailable then disconnect, since a clean disconnect doesn't trigger the will""" 

271 try: 

272 if client.is_connected(): 

273 publish_availability(client, avail_topic, online=False).wait_for_publish(timeout=OFFLINE_PUBLISH_TIMEOUT) 

274 except Exception as e: 

275 log.warning("Unable to confirm offline availability published: %s", e) 

276 client.disconnect() 

277 client.loop_stop() 

278 

279 

280class Anpr2MQTT(Settings): 

281 def cli_cmd(self) -> None: 

282 main_loop() 

283 

284 

285def run() -> None: 

286 try: 

287 CliApp.run(model_cls=Anpr2MQTT) 

288 except ValidationError as e: 

289 log.error(e) 

290 log.error("Unable to startup, validation error on settings, check configuration file, arguments or env vars") 

291 log.error("MQTT host, account and password are mandatory (if using env vars, be sure to use MQTT__HOST not MQTT_HOST)") 

292 log.error("Use --help for a full set of config") 

293 log.error("Use the anprtools CLI for testing out directory watch, image analysis and APIs")