Coverage for src/anpr2mqtt/hass.py: 92%
173 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-23 13:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-23 13:55 +0000
1import json
2import random
3import threading
4import time
5from io import BytesIO
6from pathlib import Path
7from typing import Any
9import paho.mqtt.client as mqtt
10import structlog
11from paho.mqtt.properties import Properties
12from paho.mqtt.reasoncodes import ReasonCode
13from PIL import Image
15import anpr2mqtt
16from anpr2mqtt.settings import CameraSettings, EventSettings, HomeAssistantSettings, Target
17from anpr2mqtt.tracker import Sighting
19from .const import ImageInfo
20from .handler_common import subscribe
22log = structlog.get_logger()
24AVAILABILITY_ONLINE = "online" # Home Assistant default payload_available
25AVAILABILITY_OFFLINE = "offline" # Home Assistant default payload_not_available
26OFFLINE_PUBLISH_TIMEOUT = 2.0
27# on every device, so an integration building on anpr2mqtt can tell its devices for certain
28DEVICE_MANUFACTURER = "Rhizomatics"
29DEVICE_MODEL = "anpr2mqtt"
32def availability_topic(topic_root: str) -> str:
33 return f"{topic_root}/availability"
36def publish_availability(client: mqtt.Client, topic: str, online: bool) -> mqtt.MQTTMessageInfo:
37 """Retained plain string payload, as expected by Home Assistant availability_topic"""
38 payload: str = AVAILABILITY_ONLINE if online else AVAILABILITY_OFFLINE
39 log.debug("Publishing availability %s to %s", payload, topic)
40 return client.publish(topic, payload=payload, qos=1, retain=True)
43class HomeAssistantPublisher:
44 def __init__(self, client: mqtt.Client, cfg: HomeAssistantSettings, availability_topic: str | None = None) -> None:
45 self.client: mqtt.Client = client
46 self.availability_topic: str | None = availability_topic
47 self.hass_status_topic: str = cfg.status_topic
48 self.discovery_topic_prefix: str = cfg.discovery_topic_root
49 self.device_creation: bool = cfg.device_creation
50 self.republish: dict[str, dict[str, Any]] = {}
51 self.hass_online: bool | None = None
53 def start(self) -> None:
54 log.info("Subscribing to Home Assistant birth and last will at %s", self.hass_status_topic)
55 self.client.on_message = self.on_message
56 self.client.on_subscribe = self.on_subscribe
57 self.client.on_unsubscribe = self.on_unsubscribe
58 subscribe(self.client, self.hass_status_topic)
60 def on_subscribe(
61 self,
62 _client: mqtt.Client,
63 userdata: Any,
64 mid: int,
65 reason_code_list: list[ReasonCode],
66 properties: Properties | None = None,
67 ) -> None:
68 log.debug("on_subscribe, userdata=%s, mid=%s, reasons=%s, properties=%s", userdata, mid, reason_code_list, properties)
70 def on_unsubscribe(
71 self,
72 _client: mqtt.Client,
73 userdata: Any,
74 mid: int,
75 reason_code_list: list[ReasonCode],
76 properties: Properties | None = None,
77 ) -> None:
78 log.debug("on_unsubscribe, userdata=%s, mid=%s, reasons=%s, properties=%s", userdata, mid, reason_code_list, properties)
80 def on_message(self, _client: mqtt.Client, _userdata: Any, msg: mqtt.MQTTMessage) -> None:
81 """Callback for incoming MQTT messages""" # ruff: ignore[non-imperative-mood]
82 if msg.topic == self.hass_status_topic:
83 decoded: str | None = msg.payload.decode("utf-8") if msg.payload else None
84 if decoded == "offline":
85 log.warn("Home Assistant gone offline")
86 self.hass_online = False
87 elif decoded == "online":
88 if self.hass_online is False:
89 log.info("Home Assistant back online, republishing discoveries")
90 self.hass_online = True
91 # off the paho network thread, since the jittered sleeps would stall keepalives and Frigate events
92 threading.Thread(
93 target=self.republish_discovery, args=(f"{msg.topic}_{decoded}",), name="hass-republish", daemon=True
94 ).start()
95 else:
96 log.info("Home Assistant online")
97 self.hass_online = True
98 else:
99 log.warn("Unknown Home Assistant status payload: %s", msg.payload)
100 else:
101 log.debug("Unknown message on %s", msg.topic)
103 def republish_discovery(self, source_event: str) -> None:
104 for topic, payload in self.republish.items():
105 log.debug("Republishing to %s for %s", topic, source_event)
106 # add jitter to republish to reduce herd load on HA after restart
107 time.sleep(random.randint(1, 10)) # ruff: ignore[suspicious-non-cryptographic-random-usage]
108 payload["trigger"] = source_event
109 self.client.publish(topic, json.dumps(payload))
111 def publish_sensor_discovery(self, state_topic: str, event_config: EventSettings, camera: CameraSettings) -> None:
112 name: str = event_config.description or f"{event_config.event} {camera.name}"
113 payload: dict[str, Any] = {
114 "o": {
115 "name": "anpr2mqtt",
116 "sw": anpr2mqtt.version, # pyright: ignore[reportAttributeAccessIssue]
117 "url": "https://anpr2mqtt.rhizomatics.org.uk",
118 },
119 "device_class": None,
120 "value_template": "{{ value_json.target }}",
121 "default_entity_id": f"sensor.{event_config.event}_{event_config.camera}",
122 "unique_id": f"{event_config.event}_{event_config.camera}",
123 "state_topic": state_topic,
124 "json_attributes_topic": state_topic,
125 "name": name,
126 }
127 if event_config.icon: 127 ↛ 129line 127 didn't jump to line 129 because the condition on line 127 was always true
128 payload["icon"] = event_config.icon
129 if self.device_creation:
130 self.add_device_info(payload, camera)
131 self.add_availability(payload)
132 topic: str = f"{self.discovery_topic_prefix}/sensor/{event_config.camera}/{event_config.event}/config"
133 msg: str = json.dumps(payload)
134 self.client.publish(topic, payload=msg, qos=0, retain=True)
135 self.republish[topic] = payload
136 log.info("Published HA MQTT sensor Discovery message to %s", topic)
138 def publish_image_discovery(
139 self, state_topic: str, image_topic: str, event_config: EventSettings, camera: CameraSettings
140 ) -> None:
141 name: str = event_config.description or f"{event_config.event} {event_config.camera}"
142 payload = {
143 "o": {
144 "name": "anpr2mqtt",
145 "sw": anpr2mqtt.version, # pyright: ignore[reportAttributeAccessIssue]
146 "url": "https://anpr2mqtt.rhizomatics.org.uk",
147 },
148 "device_class": None,
149 "unique_id": f"{event_config.event}_{event_config.camera}",
150 "default_entity_id": f"image.{event_config.event}_{event_config.camera}",
151 "image_topic": image_topic,
152 "json_attributes_topic": state_topic,
153 "icon": event_config.icon,
154 "name": name,
155 }
156 if self.device_creation:
157 self.add_device_info(payload, camera)
158 self.add_availability(payload)
159 topic = f"{self.discovery_topic_prefix}/image/{event_config.camera}/{event_config.event}/config"
160 msg = json.dumps(payload)
161 self.client.publish(topic, payload=msg, qos=0, retain=True)
162 self.republish[topic] = payload
163 log.info("Published HA MQTT Discovery message to %s", topic)
165 def publish_camera_discovery(
166 self, state_topic: str, image_topic: str, event_config: EventSettings, camera: CameraSettings
167 ) -> None:
168 name: str = event_config.description or f"{event_config.event} {event_config.camera}"
169 payload = {
170 "o": {
171 "name": "anpr2mqtt",
172 "sw": anpr2mqtt.version, # pyright: ignore[reportAttributeAccessIssue]
173 "url": "https://anpr2mqtt.rhizomatics.org.uk",
174 },
175 "unique_id": f"{event_config.event}_{camera.name}",
176 "default_entity_id": f"camera.{event_config.event}_{camera.name}_anpr",
177 "topic": image_topic,
178 "json_attributes_topic": state_topic,
179 "icon": event_config.icon,
180 "name": name,
181 }
182 if self.device_creation:
183 self.add_device_info(payload, camera)
184 self.add_availability(payload)
185 topic = f"{self.discovery_topic_prefix}/camera/{camera.name}/{event_config.event}/config"
186 msg = json.dumps(payload)
187 self.client.publish(topic, payload=msg, qos=0, retain=True)
188 self.republish[topic] = payload
189 log.info("Published HA MQTT Discovery message to %s", topic)
191 def publish_target_sensor_discovery(
192 self, entity_id: str, target_type: str, targets: list[Target], state_topic: str, icon: str | None
193 ) -> None:
194 payload: dict[str, Any] = {
195 "o": {
196 "name": "anpr2mqtt",
197 "sw": anpr2mqtt.version, # pyright: ignore[reportAttributeAccessIssue]
198 "url": "https://anpr2mqtt.rhizomatics.org.uk",
199 },
200 # keyed like the discovery topic, so it survives restarts and group membership changes
201 "unique_id": f"{target_type}_{entity_id}",
202 "default_entity_id": f"sensor.{entity_id}",
203 "name": targets[0].description if len(targets) == 1 else entity_id,
204 "state_topic": state_topic,
205 "json_attributes_topic": state_topic,
206 "value_template": "{{ value_json.last_seen }}",
207 "device_class": "timestamp",
208 }
209 if icon: 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true
210 payload["icon"] = icon
211 self.add_availability(payload)
212 topic = f"{self.discovery_topic_prefix}/sensor/{entity_id}/config"
213 msg = json.dumps(payload)
214 self.client.publish(topic, payload=msg, qos=0, retain=True)
215 self.republish[topic] = payload
216 log.info("Published HA MQTT target sensor Discovery message to %s", topic)
218 def publish_target_state(self, state_topic: str, time_analysis: dict[str, Any], description: str | None = None) -> None:
219 payload: dict[str, Any] = {**time_analysis}
220 if description:
221 payload["description"] = description
222 try:
223 msg = json.dumps(payload)
224 self.client.publish(state_topic, payload=msg, qos=0, retain=True)
225 log.debug("Published target state to %s: %s", state_topic, payload)
226 except Exception as e:
227 log.error("Failed to publish target state to %s: %s", state_topic, e, exc_info=1)
229 def add_availability(self, payload: dict[str, Any]) -> None:
230 if self.availability_topic:
231 # payloads are the Home Assistant defaults, `online` and `offline`, so not repeated here
232 payload["availability_topic"] = self.availability_topic
234 def add_device_info(self, payload: dict[str, Any], camera: CameraSettings) -> None:
235 # manufacturer and model together say for certain that a device is anpr2mqtt's, for integrations that build on it
236 payload["dev"] = {
237 "name": f"anpr2mqtt on {camera.name}",
238 "sw_version": anpr2mqtt.version, # pyright: ignore[reportAttributeAccessIssue]
239 "manufacturer": DEVICE_MANUFACTURER,
240 "model": DEVICE_MODEL,
241 "identifiers": [f"{camera.name}.anpr2mqtt"],
242 }
243 if camera.area:
244 payload["dev"]["suggested_area"] = camera.area
245 # Home Assistant rejects the whole discovery message for a configuration URL it can't use
246 if camera.live_url and camera.live_url.startswith(("http://", "https://")):
247 payload["dev"]["configuration_url"] = camera.live_url
249 def post_state_message(
250 self,
251 topic: str,
252 sighting: Sighting | None,
253 event_config: EventSettings,
254 camera: CameraSettings,
255 extra_info: dict[str, Any] | None = None,
256 image_info: ImageInfo | None = None,
257 time_analysis: dict[str, Any] | None = None,
258 url: str | None = None,
259 error: str | None = None,
260 file_path: Path | None = None,
261 reg_info: Any = None,
262 source: str | None = None,
263 frigate_event_id: str | None = None,
264 frigate_ui_url: str | None = None,
265 ) -> None:
267 payload: dict[str, Any] = sighting.as_dict() if sighting else {"target": None, "target_type": event_config.target_type}
268 if payload.get("description") is None:
269 payload["description"] = event_config.default_description
270 payload.update(
271 {
272 event_config.target_type: sighting.target.id if sighting else None,
273 "event": event_config.event,
274 "camera": camera.name or "UNKNOWN",
275 "area": camera.area,
276 "live_url": camera.live_url,
277 "linked_cameras": camera.linked_cameras,
278 "reg_info": reg_info,
279 "history": time_analysis,
280 }
281 )
282 if extra_info:
283 payload.update(extra_info)
284 if error:
285 payload["error"] = error
286 if url is not None:
287 payload["event_image_url"] = url
288 if file_path is not None:
289 payload["file_path"] = str(file_path)
290 if source is not None:
291 payload["source"] = source
292 if frigate_event_id is not None: 292 ↛ 293line 292 didn't jump to line 293 because the condition on line 292 was never true
293 payload["frigate_event_id"] = frigate_event_id
294 if frigate_ui_url is not None: 294 ↛ 295line 294 didn't jump to line 295 because the condition on line 294 was never true
295 payload["frigate_ui_url"] = frigate_ui_url
297 try:
298 if image_info:
299 payload.update(
300 {
301 "event_time": image_info.timestamp.isoformat(),
302 "image_event": image_info.event,
303 "ext": image_info.ext,
304 "image_size": image_info.size,
305 }
306 )
307 msg: str = json.dumps(payload)
308 self.client.publish(topic, payload=msg, qos=0, retain=True)
309 log.debug("Published HA MQTT State message to %s: %s", topic, payload)
310 except Exception as e:
311 log.error("Failed to publish event %s: %s", payload, e, exc_info=1)
313 def post_image_message(self, topic: str, image: Image.Image | None, img_format: str = "JPEG") -> None:
314 try:
315 if image is None:
316 self.client.publish(topic, payload=None, qos=0, retain=True)
317 log.debug("Cleared HA MQTT Image message at %s", topic)
318 return
319 img_byte_arr = BytesIO()
320 image.save(img_byte_arr, format=img_format)
321 img_bytes = img_byte_arr.getvalue()
323 self.client.publish(topic, payload=img_bytes, qos=0, retain=True)
324 log.debug("Published HA MQTT Image message to %s: %s bytes", topic, len(img_bytes))
325 except Exception as e:
326 log.error("Failed to publish image entity: %s", e, exc_info=1)