Coverage for src/anpr2mqtt/settings.py: 93%
206 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 re
2import warnings
3from enum import StrEnum, auto
4from pathlib import Path
5from typing import Final, Literal
7from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
8from pydantic_settings import (
9 BaseSettings,
10 CliSettingsSource,
11 NestedSecretsSettingsSource,
12 PydanticBaseSettingsSource,
13 SettingsConfigDict,
14 YamlConfigSettingsSource,
15)
17TARGET_TYPE_PLATE: Final[str] = "plate"
20class MQTTSettings(BaseModel):
21 model_config = ConfigDict(populate_by_name=True)
23 topic_root: str = "anpr2mqtt"
24 host: str = Field(default="localhost", description="MQTT broker IP address or hostname")
25 port: int = Field(default=1883, description="MQTT broker port number")
26 user: str = Field(description="MQTT account user name")
27 protocol: str = Field(default="3.11", description="MQTT protocol version, v3 and v5 supported")
28 password: str = Field(alias="pass", description="MQTT account password")
31class CameraSettings(BaseModel):
32 name: str = Field(default="driveway", description="Camera Identifier, used to build MQTT topic names")
33 area: str | None = Field(default=None, description="Home Assistant area ID")
34 live_url: str | None = Field(default=None, description="URL to watch camera feed live")
35 linked_cameras: dict[str, str] = Field(
36 default_factory=dict,
37 description="The same camera in other integrations, by the Home Assistant domain of each, such as frigate, "
38 "unifiprotect, viseron or blueiris, for integrations that join sightings to their events. The frigate camera "
39 "is also the one whose licence plate events are published as this camera, only needed where its name differs",
40 )
43class AutoClearSettings(BaseModel):
44 enabled: bool = Field(default=True, description="Enable auto-clear of state after last event")
45 post_event: int = Field(default=300, description="Seconds after last event to reset state")
46 state: bool = Field(default=True, description="Auto-clear state")
47 image: bool = Field(default=False, description="Auto-clear image")
50class EventSettings(BaseModel):
51 camera: str = Field(default="driveway", description="Camera name")
52 event: str = Field(default="anpr", description="Identifier of the event, used in MQTT topic description")
53 description: str | None = Field(default=None, description="Free text description of event")
54 target_type: str = Field(default="plate", description="Type of target for this event, 'plate' if ANPR")
55 region: str | None = Field(default="UK", description="Region for applying correction, normalization rules")
56 default_description: str = Field(default="Unknown vehicle", description="Default description if no known match found")
57 icon: str | None = Field(
58 default="mdi:car-back",
59 description="Default icon to provide for Home Assistant sensors",
60 )
61 watch_path: Path = Field(default=Path(), description="File system directory to watch")
62 watch_tree: bool = Field(
63 default=False, description="Watch directory tree at path, or false for only the root watch_path directory"
64 )
65 image_name_re: re.Pattern[str] = Field(
66 default=re.compile(r"(?P<dt>[0-9]{17})_(?P<target>[A-Z0-9]+)_(?P<event>VEHICLE_DETECTION)\.(?P<ext>jpg|png|gif|jpeg)"),
67 description="Regular expression to find datetime, file extension and target from image name",
68 )
69 image_url_base: str | None = Field(default=None, description="Base URL to turn a file name into a web link")
70 ocr_field_ids: list[str] = Field(
71 default_factory=lambda: ["hik_direction"], description="OCR field definitions to find in image"
72 )
73 autoclear: AutoClearSettings = AutoClearSettings()
74 auto_match_tolerance: int = Field(
75 default=1,
76 description="Maximum tolerance for auto matching against known plates, using Levenshtein, 0 to disable fuzzy matching",
77 )
78 good_read_ttl: int = Field(
79 default=60,
80 description="Seconds to retain the last DVLA-confirmed plate per camera for mis-read correction; 0 to disable",
81 )
82 good_read_tolerance: int = Field(
83 default=2,
84 description="Max Levenshtein distance from last known-good plate to trigger correction; 0 to disable",
85 )
87 @field_validator("image_url_base")
88 @classmethod
89 def validate_image_url_base(cls, v: str | None) -> str | None:
90 if v is not None and v.endswith("/"): 90 ↛ 91line 90 didn't jump to line 91 because the condition on line 90 was never true
91 warnings.warn(
92 f"image_url_base has a trailing slash ({v!r}); this will produce double-slash URLs. "
93 "Remove the trailing slash from image_url_base.",
94 UserWarning,
95 stacklevel=2,
96 )
97 return v
99 @field_validator("image_name_re")
100 @classmethod
101 def validate_image_name_re(cls, v: re.Pattern[str]) -> re.Pattern[str]:
102 required = {"dt", "target"}
103 missing = required - set(v.groupindex)
104 if missing:
105 raise ValueError(f"image_name_re is missing required named groups: {sorted(missing)}")
106 return v
109class HomeAssistantSettings(BaseModel):
110 discovery_topic_root: str = "homeassistant"
111 status_topic: str = Field(
112 default="homeassistant/status", description="HomeAssistant status topic, where birth and will messages are posted"
113 )
114 device_creation: bool = Field(
115 default=True, description="Create a Home Assistant Device and associate the event sensors and images to it"
116 )
117 image_entity: bool = Field(default=True, description="Create an Image entity via MQTT discovery")
118 camera_entity: bool = Field(default=True, description="Create a Camera entity via MQTT discovery")
121class CacheType(StrEnum):
122 MEMORY = auto()
123 FILE = auto()
126class DVLASettings(BaseModel):
127 api_key: str | None = Field(default=None, description="DVLA issued API key")
128 cache_ttl: int = Field(default=86400, description="Time to live for cached DVLA API results, in seconds, default 1 day")
129 cache_type: CacheType = Field(default=CacheType.FILE, description="Cache implementation, MEMORY or FILE")
130 cache_dir: Path | None = Field(default=Path("/data/cache"), description="Cache directory")
131 verify_plate: str | None = Field(default=None, description="Plate to check at startup to verify API")
134class FrigateSettings(BaseModel):
135 enabled: bool = Field(default=False, description="Enable Frigate MQTT event listener")
136 topic: list[str] = Field(
137 default=["frigate/events", "frigate/tracked_object_update"], description="MQTT topic for Frigate events"
138 )
139 min_score: float = Field(default=0.70, description="Minimum plate recognition score to process (0.0->1.0)")
140 url: str | None = Field(
141 default=None, description="Frigate base URL for API snapshot fallback and UI links, e.g. http://frigate:5000"
142 )
143 cameras: list[str] | None = Field(default=None, description="Camera names to process; None means all cameras")
146# the key of a linked Frigate camera, the Frigate integration's Home Assistant domain
147LINK_FRIGATE = "frigate"
150def linked_cameras(camera: CameraSettings, frigate: FrigateSettings) -> dict[str, str]:
151 """Find the cameras linked to this one, by the Home Assistant domain of each integration.
153 Those set are always kept. While the Frigate listener is on, and processes a camera of the same name, that Frigate
154 camera is linked too, unless another is set, since its licence plate events are published as this camera.
155 """
156 links = dict(camera.linked_cameras)
157 if frigate.enabled and LINK_FRIGATE not in links and (frigate.cameras is None or camera.name in frigate.cameras):
158 links[LINK_FRIGATE] = camera.name
159 return links
162class TrackerSettings(BaseModel):
163 data_dir: Path = Path("/data")
164 min_visit_gap_seconds: int = Field(
165 default=0,
166 description="Minimum seconds between recorded visits for the same target; 0 to disable (every read is a visit)",
167 )
170class ImageSettings(BaseModel):
171 jpeg_opts: dict[str, int | bool | float | str | tuple[int | float, int | float]] = Field(
172 default={"quality": 30, "progressive": True, "optimize": True}
173 )
174 png_opts: dict[str, int | bool | float | str | tuple[int, int]] = Field(
175 default={"quality": 30, "dpi": (60, 90), "optimize": True}
176 )
179class DimensionSettings(BaseModel):
180 x: int = Field(description="Horizontal position of crop box, measured from image left side")
181 y: int = Field(description="Vertical position of crop box, measured from image bottom side")
182 h: int = Field(description="Height of crop box in pixels")
183 w: int = Field(description="Width of crop box in pixels")
186class OCRFieldSettings(BaseModel):
187 label: str = "ocr_field"
188 crop: DimensionSettings | None = None
189 invert: bool = True
190 correction: dict[str, list[re.Pattern[str]]] = Field(default_factory=lambda: {})
191 values: list[str] | None = None
194def hik_direction_field() -> OCRFieldSettings:
195 """Field to read `direction` from the caption bar of the Hikvision DS-2CD4A25FWD-IZS"""
196 return OCRFieldSettings(
197 label="vehicle_direction",
198 invert=True,
199 crop=DimensionSettings(x=850, y=0, h=30, w=650),
200 values=["Forward", "Reverse", "Unknown"],
201 correction={"Forward": [re.compile(r"Fo.*rd")], "Reverse": [re.compile(r"Re.*rse"), re.compile(r"Bac.*rd")]},
202 )
205class OCRSettings(BaseModel):
206 """Defaults for reading `direction` for the Hikvision DS-2CD4A25FWD-IZS"""
208 fields: dict[str, OCRFieldSettings] = Field(default_factory=lambda: {"hik_direction": hik_direction_field()})
209 verify_on_startup: bool = Field(
210 default=True, description="OCR a bundled sample image at startup, to check Tesseract is installed and working"
211 )
214class Target(BaseModel):
215 id: str = Field(description="Target identifier, for example reg plate")
216 target_type: str = ""
217 group: str | None = None
218 lookup: bool | None = Field(
219 default=None, description="Lookup registration plate using API, defaults to False for configured plates"
220 )
221 description: str | None = Field(default=None, description="Target description")
222 entity_id: str | None = Field(
223 default=None, description="Entity ID to publish using Home Assistant MQTT Discovery compatible message"
224 )
225 icon: str | None = Field(
226 default=None,
227 description="Name of icon to publish, for Home Assistant should be a Material Design reference like 'mdi:car'",
228 )
229 priority: str | None = Field(default=None, description="Priority to report for use in Home Assistant notifications")
230 correction: list[str | re.Pattern[str]] = Field(default_factory=lambda: [])
232 def as_dict(self) -> dict[str, bool | str | None]:
233 result: dict[str, bool | str | None] = {
234 "dangerous": self.group == "dangerous", # backward compat
235 "description": self.description,
236 "known": self.group == "known", # backward compat
237 "priority": self.priority,
238 "target": self.id,
239 "target_type": self.target_type,
240 "entity_id": self.entity_id,
241 }
242 if self.icon: 242 ↛ 243line 242 didn't jump to line 243 because the condition on line 242 was never true
243 result["icon"] = self.icon
245 return result
248_PRIORITY_BY_GROUP: dict[str, str] = {"known": "medium", "dangerous": "critical"}
251class TargetGroup(BaseModel):
252 name: str = Field(description="Name of the target group, for example 'known'")
253 priority: str = Field(default="medium", description="Priority to report on MQTT message for sightings of this group")
254 lookup: bool = Field(
255 default=False, description="Lookup registration plate using API, defaults to False for configured plates"
256 )
257 members: list[Target] = Field(description="List of target IDs or full target definitions")
258 icon: str | None = Field(
259 default=None,
260 description="Name of icon to publish, for Home Assistant should be a Material Design reference like 'mdi:car'",
261 )
262 entity_id: str | None = Field(
263 default=None, description="Entity ID to publish using Home Assistant MQTT Discovery compatible message"
264 )
266 @field_validator("members", mode="before")
267 @classmethod
268 def coerce_member_strings(cls, v: object) -> object:
269 if not isinstance(v, list): 269 ↛ 270line 269 didn't jump to line 270 because the condition on line 269 was never true
270 return v
271 return [{"id": item} if isinstance(item, str) else item for item in v]
273 @model_validator(mode="after")
274 def apply_group_defaults(self) -> "TargetGroup":
276 for target in self.members:
277 target.group = self.name
278 if target.lookup is None:
279 target.lookup = self.lookup
280 if target.priority is None:
281 target.priority = self.priority
282 if target.icon is None:
283 target.icon = self.icon
284 if target.entity_id is None:
285 target.entity_id = self.entity_id
286 if target.description is None:
287 target.description = self.name
288 return self
291class TargetSettings(BaseModel):
292 groups: list[TargetGroup] = Field(default_factory=list)
293 known: dict[str, object] = Field(default_factory=dict, deprecated="Replaced by a 'groups' entry with name 'known'")
294 dangerous: dict[str, object] = Field(
295 default_factory=dict, deprecated="Replaced by a 'groups' entry with name 'dangerous' and priority 'critical'"
296 )
297 ignore: list[str | re.Pattern[str]] = Field(default_factory=list)
298 correction: dict[str, list[str | re.Pattern[str]]] = Field(default_factory=lambda: {})
301class Settings(BaseSettings):
302 model_config = SettingsConfigDict(
303 secrets_dir="/run/secrets",
304 yaml_file="/config/anpr2mqtt.yaml",
305 env_nested_delimiter="__",
306 env_ignore_empty=True,
307 cli_avoid_json=False,
308 )
310 log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
311 cameras: list[CameraSettings] = Field(default_factory=list)
312 events: list[EventSettings] = Field(default_factory=lambda: [])
313 image: ImageSettings = ImageSettings()
314 targets: dict[str, TargetSettings] = Field(default_factory=lambda: {})
315 tracker: TrackerSettings = TrackerSettings()
316 mqtt: MQTTSettings
317 dvla: DVLASettings = DVLASettings()
318 frigate: FrigateSettings = FrigateSettings()
319 homeassistant: HomeAssistantSettings = HomeAssistantSettings()
320 ocr: OCRSettings = OCRSettings()
322 @model_validator(mode="before")
323 @classmethod
324 def migrate_and_inject_target_type(cls, data: object) -> object:
325 """Migrate legacy 'known'/'dangerous' to TargetGroup entries and inject target_type into all members."""
326 if not isinstance(data, dict): 326 ↛ 327line 326 didn't jump to line 327 because the condition on line 326 was never true
327 return data
328 for target_type, target_settings in (data.get("targets") or {}).items():
329 if not isinstance(target_settings, dict): 329 ↛ 330line 329 didn't jump to line 330 because the condition on line 329 was never true
330 continue
331 groups: list[dict[str, object] | TargetGroup] = list(target_settings.get("groups") or [])
333 # migration of original known/dangerous fixed groups
334 existing_names = {g["name"] if isinstance(g, dict) else g.name for g in groups}
335 for group_name in ("known", "dangerous"):
336 legacy: dict[str, object] = target_settings.get(group_name) or {}
337 if not legacy or group_name in existing_names:
338 continue
339 members = []
340 for target_id, val in legacy.items():
341 if isinstance(val, str):
342 members.append({"id": target_id, "description": val, "target_type": target_type})
343 elif isinstance(val, dict): 343 ↛ 346line 343 didn't jump to line 346 because the condition on line 343 was always true
344 members.append({"id": target_id, "target_type": target_type, **val})
345 else:
346 members.append({"id": target_id, "target_type": target_type})
347 groups.append(
348 {
349 "name": group_name,
350 "priority": _PRIORITY_BY_GROUP.get(group_name, "medium"),
351 "members": members,
352 "lookup": group_name == "dangerous",
353 }
354 )
355 # normalize strings->dicts
356 target_settings["groups"] = groups
357 for group in groups:
358 if not isinstance(group, dict): 358 ↛ 359line 358 didn't jump to line 359 because the condition on line 358 was never true
359 continue
360 raw_members = group.get("members")
361 if not isinstance(raw_members, list): 361 ↛ 362line 361 didn't jump to line 362 because the condition on line 361 was never true
362 continue
363 for i, member in enumerate(raw_members):
364 if isinstance(member, str):
365 raw_members[i] = {"id": member, "target_type": target_type}
366 elif isinstance(member, dict) and "target_type" not in member:
367 member["target_type"] = target_type
368 return data
370 @classmethod
371 def settings_customise_sources(
372 cls,
373 settings_cls: type[BaseSettings],
374 init_settings: PydanticBaseSettingsSource,
375 env_settings: PydanticBaseSettingsSource,
376 dotenv_settings: PydanticBaseSettingsSource,
377 file_secret_settings: PydanticBaseSettingsSource,
378 ) -> tuple[PydanticBaseSettingsSource, ...]:
379 return (
380 CliSettingsSource(settings_cls, cli_parse_args=True),
381 env_settings,
382 dotenv_settings,
383 NestedSecretsSettingsSource(file_secret_settings, secrets_dir_missing="ok"),
384 YamlConfigSettingsSource(settings_cls),
385 init_settings,
386 )