Coverage for src/anpr2mqtt/handler_common.py: 81%

76 statements  

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

1import datetime as dt 

2import threading 

3from typing import Any 

4 

5import paho.mqtt.client as mqtt 

6import structlog 

7 

8from anpr2mqtt.api_client import APIClient, DVLAClient 

9from anpr2mqtt.normalizers import Normalizer, fuzzy_match 

10from anpr2mqtt.settings import TARGET_TYPE_PLATE, DVLASettings, EventSettings 

11 

12log = structlog.get_logger() 

13 

14SUBSCRIPTIONS = "subscriptions" 

15 

16 

17def subscribe(client: mqtt.Client, topic: str) -> None: 

18 """Subscribe, and record the topic in the client userdata so on_connect can renew it. 

19 

20 The client uses a clean session, so the broker drops subscriptions whenever the connection does. 

21 """ 

22 userdata: Any = client.user_data_get() 

23 if isinstance(userdata, dict): 

24 topics: list[str] = userdata.setdefault(SUBSCRIPTIONS, []) 

25 if topic not in topics: 

26 topics.append(topic) 

27 client.subscribe(topic) 

28 

29 

30def build_dvla_client(dvla_settings: DVLASettings, target_type: str | None = None) -> APIClient | None: 

31 if not dvla_settings.api_key: 

32 return None 

33 if target_type is not None and target_type != TARGET_TYPE_PLATE: 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true

34 return None 

35 return DVLAClient( 

36 dvla_settings.api_key, 

37 cache_type=dvla_settings.cache_type, 

38 cache_ttl=dvla_settings.cache_ttl, 

39 cache_dir=dvla_settings.cache_dir, 

40 verify_plate=dvla_settings.verify_plate, 

41 ) 

42 

43 

44def correct_against_good_read( 

45 plate: str, 

46 cached: tuple[str, dt.datetime] | None, 

47 ttl: int, 

48 tolerance: int, 

49 normalizer: Normalizer | None = None, 

50) -> str: 

51 if ttl <= 0 or tolerance <= 0 or cached is None: 

52 return plate 

53 good_plate, good_ts = cached 

54 age = (dt.datetime.now(dt.UTC) - good_ts).total_seconds() 

55 if age > ttl: 

56 return plate 

57 candidates: list[str] = [good_plate] 

58 alt_candidate: str | None = normalizer.normalize(plate) if normalizer else None 

59 if alt_candidate: 

60 candidates.append(alt_candidate) 

61 

62 if fuzzy_match(plate, tolerance, candidates) is not None and plate != good_plate: 

63 log.info("Correcting %s -> %s via last known good (age=%.1fs)", plate, good_plate, age) 

64 return good_plate 

65 return plate 

66 

67 

68class CameraGatekeeper: 

69 """Camera-level duplicate gate. 

70 

71 Suppresses events within the visit gap window even when the plate string differs 

72 (e.g. two bad reads of the same vehicle). Exception: if the last published event 

73 had no DVLA enrichment, one replacement is allowed through so a subsequently-enriched 

74 read can supersede the raw notification. 

75 """ 

76 

77 def __init__(self) -> None: 

78 self._last_time: dt.datetime | None = None 

79 self._last_had_dvla: bool = False 

80 self._lock = threading.Lock() 

81 

82 def allow(self, event_time: dt.datetime, has_dvla: bool, gap_seconds: int) -> bool: 

83 """Return True (and update state) if this event should be published.""" 

84 with self._lock: 

85 if self._last_time is None or gap_seconds <= 0: 85 ↛ 90line 85 didn't jump to line 90 because the condition on line 85 was always true

86 self._last_time = event_time 

87 self._last_had_dvla = has_dvla 

88 return True 

89 

90 elapsed = (event_time - self._last_time).total_seconds() 

91 

92 if elapsed < 0 or elapsed >= gap_seconds: 

93 self._last_time = event_time 

94 self._last_had_dvla = has_dvla 

95 return True 

96 

97 # Within gap — prior had DVLA enrichment: suppress 

98 if self._last_had_dvla: 

99 log.info( 

100 "Camera gate: suppressing within-gap event (prior enriched, elapsed=%.1fs gap=%ds)", 

101 elapsed, 

102 gap_seconds, 

103 ) 

104 return False 

105 

106 # Prior lacked enrichment: allow one replacement 

107 log.info( 

108 "Camera gate: allowing replacement (prior unenriched, elapsed=%.1fs gap=%ds)", 

109 elapsed, 

110 gap_seconds, 

111 ) 

112 self._last_time = event_time 

113 self._last_had_dvla = has_dvla 

114 return True 

115 

116 

117class AutoclearTimer: 

118 """Manages a cancel-and-restart debounce timer for a single autoclear slot.""" 

119 

120 def __init__(self) -> None: 

121 self._timer: threading.Timer | None = None 

122 self._lock = threading.Lock() 

123 

124 def schedule(self, event_config: EventSettings, callback: Any, label: str) -> None: 

125 autoclear = event_config.autoclear 

126 if not autoclear.enabled: 

127 return 

128 with self._lock: 

129 if self._timer is not None: 

130 self._timer.cancel() 

131 self._timer = threading.Timer(autoclear.post_event, callback) 

132 self._timer.daemon = True 

133 self._timer.start() 

134 log.debug("Autoclear scheduled in %ss for %s", autoclear.post_event, label)