telematics-quality-kit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- telematics/__init__.py +10 -0
- telematics/backends/base.py +13 -0
- telematics/backends/simulator.py +330 -0
- telematics/cli/doctor.py +52 -0
- telematics/cli/formatting.py +52 -0
- telematics/cli/init.py +95 -0
- telematics/cli/inject.py +121 -0
- telematics/cli/main.py +433 -0
- telematics/cli/session.py +237 -0
- telematics/cli/shell.py +492 -0
- telematics/cli/stream.py +316 -0
- telematics/clock.py +35 -0
- telematics/codecs/base.py +15 -0
- telematics/codecs/crc.py +27 -0
- telematics/codecs/gt06.py +207 -0
- telematics/codecs/teltonika.py +137 -0
- telematics/config.py +106 -0
- telematics/errors.py +5 -0
- telematics/ingest/events.py +68 -0
- telematics/ingest/framing.py +74 -0
- telematics/ingest/pipeline.py +97 -0
- telematics/ingest/tap.py +97 -0
- telematics/mcp/export_schemas.py +20 -0
- telematics/mcp/prompts.py +32 -0
- telematics/mcp/resources.py +89 -0
- telematics/mcp/schemas.py +309 -0
- telematics/mcp/server.py +576 -0
- telematics/models/quality.py +23 -0
- telematics/models/telemetry.py +21 -0
- telematics/quality/_common.py +19 -0
- telematics/quality/caveats.py +117 -0
- telematics/quality/drift.py +49 -0
- telematics/quality/duplicates.py +46 -0
- telematics/quality/freshness.py +43 -0
- telematics/quality/fuel.py +36 -0
- telematics/quality/ignition.py +45 -0
- telematics/quality/plausibility.py +60 -0
- telematics/quality/scoring.py +44 -0
- telematics/report/__init__.py +1 -0
- telematics/report/builder.py +290 -0
- telematics/report/render.py +274 -0
- telematics/report/svg.py +112 -0
- telematics/service/vehicles.py +194 -0
- telematics/simulator/generator.py +157 -0
- telematics/simulator/identity.py +18 -0
- telematics/simulator/profiles.py +89 -0
- telematics/simulator/realtime.py +82 -0
- telematics/store/base.py +16 -0
- telematics/store/memory.py +47 -0
- telematics_quality_kit-0.1.0.dist-info/LICENSE +203 -0
- telematics_quality_kit-0.1.0.dist-info/METADATA +213 -0
- telematics_quality_kit-0.1.0.dist-info/RECORD +55 -0
- telematics_quality_kit-0.1.0.dist-info/WHEEL +5 -0
- telematics_quality_kit-0.1.0.dist-info/entry_points.txt +3 -0
- telematics_quality_kit-0.1.0.dist-info/top_level.txt +1 -0
telematics/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""The sole service-facing fleet backend boundary."""
|
|
2
|
+
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from telematics.models.telemetry import TelemetryPoint
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FleetBackend(Protocol):
|
|
9
|
+
"""Read-only fleet capabilities required by the vertical slice."""
|
|
10
|
+
|
|
11
|
+
def list_vehicle_ids(self) -> tuple[str, ...]: ...
|
|
12
|
+
|
|
13
|
+
def get_points(self, vehicle_id: str) -> tuple[TelemetryPoint, ...]: ...
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Simulator-backed fleet, with all points admitted through the GT06 parser."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass, replace
|
|
5
|
+
from datetime import datetime, timedelta
|
|
6
|
+
from math import sin, tau
|
|
7
|
+
from threading import RLock
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from telematics.clock import Clock
|
|
11
|
+
from telematics.codecs.base import Codec
|
|
12
|
+
from telematics.codecs.gt06 import GT06Codec
|
|
13
|
+
from telematics.codecs.teltonika import TeltonikaCodec
|
|
14
|
+
from telematics.ingest.events import FaultCleared, FaultInjected
|
|
15
|
+
from telematics.ingest.pipeline import IngestPipeline
|
|
16
|
+
from telematics.ingest.tap import EventTap
|
|
17
|
+
from telematics.models.telemetry import TelemetryPoint
|
|
18
|
+
from telematics.simulator.generator import Simulator
|
|
19
|
+
from telematics.simulator.profiles import VehicleProfile
|
|
20
|
+
from telematics.store.memory import MemoryPointStore
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class ActiveFault:
|
|
25
|
+
"""One simulator-only fault and its optional simulated-time expiry."""
|
|
26
|
+
|
|
27
|
+
vehicle_id: str
|
|
28
|
+
name: str
|
|
29
|
+
params: Mapping[str, int | float | str]
|
|
30
|
+
expires_at: datetime | None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class SimulatorBackend:
|
|
34
|
+
"""In-memory fleet backend initialized through each profile's wire codec."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
*,
|
|
39
|
+
seed: int,
|
|
40
|
+
clock: Clock,
|
|
41
|
+
vehicles: int,
|
|
42
|
+
profile_mix: Mapping[str, int] | None = None,
|
|
43
|
+
event_tap: EventTap | None = None,
|
|
44
|
+
) -> None:
|
|
45
|
+
self._lock = RLock()
|
|
46
|
+
self._store = MemoryPointStore()
|
|
47
|
+
self._clock = clock
|
|
48
|
+
self.event_tap = event_tap if event_tap is not None else EventTap()
|
|
49
|
+
simulator = Simulator(seed=seed, clock=clock, profile_mix=profile_mix)
|
|
50
|
+
self._simulator = simulator
|
|
51
|
+
fleet = simulator.vehicles(vehicles=vehicles)
|
|
52
|
+
profile_by_vehicle = {vehicle.vehicle_id: vehicle.profile for vehicle in fleet}
|
|
53
|
+
self._profiles = profile_by_vehicle
|
|
54
|
+
codecs: dict[str, Codec] = {"gt06": GT06Codec(), "teltonika": TeltonikaCodec()}
|
|
55
|
+
pipelines = {
|
|
56
|
+
protocol: IngestPipeline(codec, self._store, clock=clock, event_tap=self.event_tap)
|
|
57
|
+
for protocol, codec in codecs.items()
|
|
58
|
+
}
|
|
59
|
+
frames = simulator.frames(vehicles=vehicles)
|
|
60
|
+
initial_received_at = clock.now()
|
|
61
|
+
self._base_frames = [
|
|
62
|
+
(vehicle_id, frame, initial_received_at) for vehicle_id, frame in frames
|
|
63
|
+
]
|
|
64
|
+
self._frames = dict(frames)
|
|
65
|
+
self._protocol_by_vehicle = {
|
|
66
|
+
vehicle_id: profile_by_vehicle[vehicle_id].protocol for vehicle_id, _ in frames
|
|
67
|
+
}
|
|
68
|
+
self._codecs = codecs
|
|
69
|
+
self._active_faults: dict[str, ActiveFault] = {}
|
|
70
|
+
self._next_fault_id = 1
|
|
71
|
+
self._tick_index = 0
|
|
72
|
+
initial_time = clock.now()
|
|
73
|
+
self._next_tick = {
|
|
74
|
+
vehicle_id: initial_time + timedelta(seconds=profile.report_interval_seconds)
|
|
75
|
+
for vehicle_id, profile in profile_by_vehicle.items()
|
|
76
|
+
}
|
|
77
|
+
for vehicle_id, frame in frames:
|
|
78
|
+
profile = profile_by_vehicle[vehicle_id]
|
|
79
|
+
pipelines[profile.protocol].ingest(vehicle_id, frame)
|
|
80
|
+
self._vehicle_ids = tuple(vehicle_id for vehicle_id, _ in frames)
|
|
81
|
+
|
|
82
|
+
def list_vehicle_ids(self) -> tuple[str, ...]:
|
|
83
|
+
return self._vehicle_ids
|
|
84
|
+
|
|
85
|
+
def get_points(self, vehicle_id: str) -> tuple[TelemetryPoint, ...]:
|
|
86
|
+
with self._lock:
|
|
87
|
+
return tuple(self._store.points(vehicle_id))
|
|
88
|
+
|
|
89
|
+
def advance(self, duration: timedelta) -> datetime:
|
|
90
|
+
"""Advance simulated time and ingest deterministic profile-cadence frames."""
|
|
91
|
+
with self._lock:
|
|
92
|
+
return self._advance(duration)
|
|
93
|
+
|
|
94
|
+
def _advance(self, duration: timedelta) -> datetime:
|
|
95
|
+
if duration <= timedelta(0):
|
|
96
|
+
raise ValueError("simulator advance duration must be positive")
|
|
97
|
+
advance_clock = getattr(self._clock, "advance", None)
|
|
98
|
+
if not callable(advance_clock):
|
|
99
|
+
raise TypeError("simulator backend requires an advanceable clock")
|
|
100
|
+
end_time = self._clock.now() + duration
|
|
101
|
+
pipelines = {
|
|
102
|
+
name: IngestPipeline(codec, self._store, clock=self._clock, event_tap=self.event_tap)
|
|
103
|
+
for name, codec in self._codecs.items()
|
|
104
|
+
}
|
|
105
|
+
while self._next_tick and min(self._next_tick.values()) <= end_time:
|
|
106
|
+
tick_at = min(self._next_tick.values())
|
|
107
|
+
advance_clock(tick_at - self._clock.now())
|
|
108
|
+
if self._expire_faults():
|
|
109
|
+
pipelines = self._pipelines()
|
|
110
|
+
self._tick_index += 1
|
|
111
|
+
frames_at = dict(
|
|
112
|
+
self._simulator.frames_at(
|
|
113
|
+
vehicles=len(self._vehicle_ids), at=tick_at, tick_index=self._tick_index
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
due = [vehicle for vehicle, next_at in self._next_tick.items() if next_at == tick_at]
|
|
117
|
+
for vehicle_id in due:
|
|
118
|
+
self._next_tick[vehicle_id] += timedelta(
|
|
119
|
+
seconds=self._profiles[vehicle_id].report_interval_seconds
|
|
120
|
+
)
|
|
121
|
+
frame = frames_at[vehicle_id]
|
|
122
|
+
if any(
|
|
123
|
+
active.vehicle_id == vehicle_id and active.name == "rural_blackout"
|
|
124
|
+
for active in self._active_faults.values()
|
|
125
|
+
):
|
|
126
|
+
continue
|
|
127
|
+
self._base_frames.append((vehicle_id, frame, tick_at))
|
|
128
|
+
self._frames[vehicle_id] = frame
|
|
129
|
+
self._ingest_faulted(pipelines, vehicle_id, frame)
|
|
130
|
+
advance_clock(end_time - self._clock.now())
|
|
131
|
+
self._expire_faults()
|
|
132
|
+
return end_time
|
|
133
|
+
|
|
134
|
+
def get_profile(self, vehicle_id: str) -> VehicleProfile:
|
|
135
|
+
return self._profiles[vehicle_id]
|
|
136
|
+
|
|
137
|
+
def faults(self) -> "SimulatorBackend":
|
|
138
|
+
"""Expose simulator-only fault operations as an optional capability."""
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
def inject_fault(
|
|
142
|
+
self,
|
|
143
|
+
vehicle_id: str,
|
|
144
|
+
fault: Literal[
|
|
145
|
+
"stale_device",
|
|
146
|
+
"gps_drift",
|
|
147
|
+
"rural_blackout",
|
|
148
|
+
"duplicate_heartbeats",
|
|
149
|
+
"ignition_flicker",
|
|
150
|
+
"clock_skew",
|
|
151
|
+
"fuel_sensor_spike",
|
|
152
|
+
"buffered_burst",
|
|
153
|
+
],
|
|
154
|
+
params: Mapping[str, int | float | str],
|
|
155
|
+
) -> tuple[str, str]:
|
|
156
|
+
"""Apply a reversible simulator fault before frames enter their parser."""
|
|
157
|
+
with self._lock:
|
|
158
|
+
return self._inject_fault(vehicle_id, fault, params)
|
|
159
|
+
|
|
160
|
+
def _inject_fault(
|
|
161
|
+
self,
|
|
162
|
+
vehicle_id: str,
|
|
163
|
+
fault: Literal[
|
|
164
|
+
"stale_device",
|
|
165
|
+
"gps_drift",
|
|
166
|
+
"rural_blackout",
|
|
167
|
+
"duplicate_heartbeats",
|
|
168
|
+
"ignition_flicker",
|
|
169
|
+
"clock_skew",
|
|
170
|
+
"fuel_sensor_spike",
|
|
171
|
+
"buffered_burst",
|
|
172
|
+
],
|
|
173
|
+
params: Mapping[str, int | float | str],
|
|
174
|
+
) -> tuple[str, str]:
|
|
175
|
+
if vehicle_id not in self._frames:
|
|
176
|
+
raise ValueError(f"unknown simulator vehicle {vehicle_id}")
|
|
177
|
+
self._severity_multiplier(params)
|
|
178
|
+
expires_at = None
|
|
179
|
+
duration_value = params.get("duration")
|
|
180
|
+
if duration_value is not None:
|
|
181
|
+
if not isinstance(duration_value, str):
|
|
182
|
+
raise ValueError("fault duration must be an integer followed by s, m, or h")
|
|
183
|
+
expires_at = self._clock.now() + self._parse_duration(duration_value)
|
|
184
|
+
fault_id = f"fault-{self._next_fault_id:04d}"
|
|
185
|
+
self._next_fault_id += 1
|
|
186
|
+
self._active_faults[fault_id] = ActiveFault(vehicle_id, fault, dict(params), expires_at)
|
|
187
|
+
self._rebuild_store()
|
|
188
|
+
impact = {
|
|
189
|
+
"stale_device": "freshness BLOCK at high severity (device time shifted by 20m)",
|
|
190
|
+
"gps_drift": "drift BLOCK within 2m at high severity (implausible consecutive fixes)",
|
|
191
|
+
"rural_blackout": "freshness BLOCK after 5m without reports",
|
|
192
|
+
"duplicate_heartbeats": "duplicates BLOCK when duplicate fraction reaches its threshold",
|
|
193
|
+
"ignition_flicker": "ignition WARN when repeated transitions exceed its window threshold",
|
|
194
|
+
"clock_skew": "plausibility BLOCK at high severity (device clock shifted by 20m)",
|
|
195
|
+
"fuel_sensor_spike": "fuel WARN when the unexplained drop threshold is crossed",
|
|
196
|
+
"buffered_burst": "duplicates flags repeated records in the buffered burst",
|
|
197
|
+
}[fault]
|
|
198
|
+
self.event_tap.publish(FaultInjected(vehicle_id, fault, impact))
|
|
199
|
+
return fault_id, impact
|
|
200
|
+
|
|
201
|
+
def reset_simulator(self, *, fault: str | None = None, vehicle_id: str | None = None) -> int:
|
|
202
|
+
"""Clear matching simulator faults and restore original encoded frames."""
|
|
203
|
+
with self._lock:
|
|
204
|
+
return self._reset_simulator(fault=fault, vehicle_id=vehicle_id)
|
|
205
|
+
|
|
206
|
+
def _reset_simulator(self, *, fault: str | None = None, vehicle_id: str | None = None) -> int:
|
|
207
|
+
selected = tuple(
|
|
208
|
+
(fault_id, active)
|
|
209
|
+
for fault_id, active in self._active_faults.items()
|
|
210
|
+
if (fault is None or active.name == fault)
|
|
211
|
+
and (vehicle_id is None or active.vehicle_id == vehicle_id)
|
|
212
|
+
)
|
|
213
|
+
for fault_id, active in selected:
|
|
214
|
+
del self._active_faults[fault_id]
|
|
215
|
+
self.event_tap.publish(FaultCleared(active.vehicle_id, active.name))
|
|
216
|
+
if selected:
|
|
217
|
+
self._rebuild_store()
|
|
218
|
+
return len(selected)
|
|
219
|
+
|
|
220
|
+
def _expire_faults(self) -> bool:
|
|
221
|
+
"""Remove faults whose injected-clock duration has elapsed."""
|
|
222
|
+
now = self._clock.now()
|
|
223
|
+
expired = [
|
|
224
|
+
(fault_id, active)
|
|
225
|
+
for fault_id, active in self._active_faults.items()
|
|
226
|
+
if active.expires_at is not None and active.expires_at <= now
|
|
227
|
+
]
|
|
228
|
+
if expired:
|
|
229
|
+
for fault_id, active in expired:
|
|
230
|
+
del self._active_faults[fault_id]
|
|
231
|
+
self.event_tap.publish(FaultCleared(active.vehicle_id, active.name))
|
|
232
|
+
self._rebuild_store()
|
|
233
|
+
return bool(expired)
|
|
234
|
+
|
|
235
|
+
def _pipelines(self) -> dict[str, IngestPipeline]:
|
|
236
|
+
"""Create protocol pipelines targeting the current memory store."""
|
|
237
|
+
return {
|
|
238
|
+
name: IngestPipeline(codec, self._store, clock=self._clock, event_tap=self.event_tap)
|
|
239
|
+
for name, codec in self._codecs.items()
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def _parse_duration(value: str) -> timedelta:
|
|
244
|
+
"""Parse a positive simulated duration ending in s, m, or h."""
|
|
245
|
+
if len(value) < 2 or not value[:-1].isdigit() or int(value[:-1]) <= 0:
|
|
246
|
+
raise ValueError("fault duration must be a positive integer followed by s, m, or h")
|
|
247
|
+
multiplier = {"s": 1, "m": 60, "h": 3600}.get(value[-1])
|
|
248
|
+
if multiplier is None:
|
|
249
|
+
raise ValueError("fault duration must end in s, m, or h")
|
|
250
|
+
return timedelta(seconds=int(value[:-1]) * multiplier)
|
|
251
|
+
|
|
252
|
+
def _rebuild_store(self) -> None:
|
|
253
|
+
self._store = MemoryPointStore()
|
|
254
|
+
pipelines = {
|
|
255
|
+
name: IngestPipeline(codec, self._store, clock=self._clock, event_tap=self.event_tap)
|
|
256
|
+
for name, codec in self._codecs.items()
|
|
257
|
+
}
|
|
258
|
+
active_by_vehicle: dict[str, list[tuple[str, Mapping[str, int | float | str]]]] = {}
|
|
259
|
+
for active in self._active_faults.values():
|
|
260
|
+
active_by_vehicle.setdefault(active.vehicle_id, []).append((active.name, active.params))
|
|
261
|
+
for vehicle_id, frame, received_at in self._base_frames:
|
|
262
|
+
self._ingest_faulted(
|
|
263
|
+
pipelines,
|
|
264
|
+
vehicle_id,
|
|
265
|
+
frame,
|
|
266
|
+
[
|
|
267
|
+
(fault, params)
|
|
268
|
+
for fault, params in active_by_vehicle.get(vehicle_id, [])
|
|
269
|
+
if fault != "rural_blackout"
|
|
270
|
+
],
|
|
271
|
+
received_at=received_at,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
def _ingest_faulted(
|
|
275
|
+
self,
|
|
276
|
+
pipelines: Mapping[str, IngestPipeline],
|
|
277
|
+
vehicle_id: str,
|
|
278
|
+
frame: bytes,
|
|
279
|
+
faults: list[tuple[str, Mapping[str, int | float | str]]] | None = None,
|
|
280
|
+
*,
|
|
281
|
+
received_at: datetime | None = None,
|
|
282
|
+
) -> None:
|
|
283
|
+
protocol = self._protocol_by_vehicle[vehicle_id]
|
|
284
|
+
codec = self._codecs[protocol]
|
|
285
|
+
points = codec.decode(frame)
|
|
286
|
+
for fault, params in faults if faults is not None else self._faults_for(vehicle_id):
|
|
287
|
+
points = [self._apply_fault(point, fault, params) for point in points]
|
|
288
|
+
if fault == "duplicate_heartbeats":
|
|
289
|
+
repeats = round(2 * self._severity_multiplier(params))
|
|
290
|
+
points = [*points, *(points * repeats)]
|
|
291
|
+
elif fault == "buffered_burst":
|
|
292
|
+
points.reverse()
|
|
293
|
+
for point in points:
|
|
294
|
+
pipelines[protocol].ingest(vehicle_id, codec.encode((point,)), received_at=received_at)
|
|
295
|
+
|
|
296
|
+
def _faults_for(self, vehicle_id: str) -> list[tuple[str, Mapping[str, int | float | str]]]:
|
|
297
|
+
return [
|
|
298
|
+
(active.name, active.params)
|
|
299
|
+
for active in self._active_faults.values()
|
|
300
|
+
if active.vehicle_id == vehicle_id
|
|
301
|
+
]
|
|
302
|
+
|
|
303
|
+
@staticmethod
|
|
304
|
+
def _apply_fault(
|
|
305
|
+
point: TelemetryPoint, fault: str, params: Mapping[str, int | float | str]
|
|
306
|
+
) -> TelemetryPoint:
|
|
307
|
+
multiplier = SimulatorBackend._severity_multiplier(params)
|
|
308
|
+
if fault in {"stale_device", "clock_skew"}:
|
|
309
|
+
duration = timedelta(minutes=10 * multiplier)
|
|
310
|
+
return replace(point, device_time=point.device_time - duration)
|
|
311
|
+
if fault == "gps_drift":
|
|
312
|
+
# Deterministic per-fix jitter that varies between consecutive fixes,
|
|
313
|
+
# so the drift check sees impossible movement without teleporting.
|
|
314
|
+
phase = point.device_time.timestamp() / 47.0 * tau
|
|
315
|
+
offset = sin(phase) * 0.02 * multiplier
|
|
316
|
+
return replace(point, latitude=min(89.9, max(-89.9, point.latitude + offset)))
|
|
317
|
+
if fault == "ignition_flicker":
|
|
318
|
+
return replace(point, ignition_on=not bool(point.ignition_on))
|
|
319
|
+
if fault == "fuel_sensor_spike":
|
|
320
|
+
return replace(point, fuel_level_percent=100.0)
|
|
321
|
+
return point
|
|
322
|
+
|
|
323
|
+
@staticmethod
|
|
324
|
+
def _severity_multiplier(params: Mapping[str, int | float | str]) -> float:
|
|
325
|
+
# Phase 5 severity deliberately scales the fault's default magnitude/duration.
|
|
326
|
+
severity = params.get("severity", "medium")
|
|
327
|
+
multipliers = {"low": 0.5, "medium": 1.0, "high": 2.0}
|
|
328
|
+
if not isinstance(severity, str) or severity not in multipliers:
|
|
329
|
+
raise ValueError("severity must be low, medium, or high")
|
|
330
|
+
return multipliers[severity]
|
telematics/cli/doctor.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Short environment checks with direct repair commands."""
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def diagnose_environment(
|
|
10
|
+
*,
|
|
11
|
+
python_version: tuple[int, int, int],
|
|
12
|
+
uv_available: bool,
|
|
13
|
+
package_available: bool,
|
|
14
|
+
) -> tuple[str, ...]:
|
|
15
|
+
"""Return one compact status line per supported environment check."""
|
|
16
|
+
results: list[str] = []
|
|
17
|
+
if python_version >= (3, 12, 0):
|
|
18
|
+
results.append(f"OK Python {python_version[0]}.{python_version[1]}+")
|
|
19
|
+
else:
|
|
20
|
+
results.append("FAIL Python 3.12+ required — run: uv python install 3.12")
|
|
21
|
+
if uv_available:
|
|
22
|
+
results.append("OK uv available")
|
|
23
|
+
else:
|
|
24
|
+
results.append(
|
|
25
|
+
"FAIL uv not found — install it: https://docs.astral.sh/uv/getting-started/installation/"
|
|
26
|
+
)
|
|
27
|
+
if package_available:
|
|
28
|
+
results.append("OK package installed")
|
|
29
|
+
else:
|
|
30
|
+
results.append("FAIL package not installed — run: uv sync")
|
|
31
|
+
return tuple(results)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def doctor() -> int:
|
|
35
|
+
"""Print the current environment diagnosis and return a status code."""
|
|
36
|
+
try:
|
|
37
|
+
version("telematics-quality-kit")
|
|
38
|
+
installed = True
|
|
39
|
+
except PackageNotFoundError:
|
|
40
|
+
installed = False
|
|
41
|
+
results: Sequence[str] = diagnose_environment(
|
|
42
|
+
python_version=(
|
|
43
|
+
sys.version_info.major,
|
|
44
|
+
sys.version_info.minor,
|
|
45
|
+
sys.version_info.micro,
|
|
46
|
+
),
|
|
47
|
+
uv_available=shutil.which("uv") is not None,
|
|
48
|
+
package_available=installed,
|
|
49
|
+
)
|
|
50
|
+
for line in results:
|
|
51
|
+
print(line)
|
|
52
|
+
return int(any(line.startswith("FAIL") for line in results))
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Shared CLI formatting for text-first verdicts and structured output."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from datetime import datetime, timedelta, timezone
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
from telematics.models.quality import Verdict
|
|
13
|
+
|
|
14
|
+
_EAT = timezone(timedelta(hours=3))
|
|
15
|
+
|
|
16
|
+
_LABELS = {
|
|
17
|
+
Verdict.PASS: ("✓", "trust it"),
|
|
18
|
+
Verdict.WARN: ("⚠", "be careful"),
|
|
19
|
+
Verdict.BLOCK: ("⛔", "don't trust it"),
|
|
20
|
+
}
|
|
21
|
+
_COLORS = {Verdict.PASS: "\033[32m", Verdict.WARN: "\033[33m", Verdict.BLOCK: "\033[31m"}
|
|
22
|
+
_RESET = "\033[0m"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def use_color(*, is_terminal: bool) -> bool:
|
|
26
|
+
"""Use ANSI colors only for terminals when NO_COLOR is unset."""
|
|
27
|
+
return is_terminal and "NO_COLOR" not in os.environ
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def render_verdict(verdict: Verdict, *, color: bool = False) -> str:
|
|
31
|
+
"""Render a verdict with both its symbol and plain-language label."""
|
|
32
|
+
symbol, label = _LABELS[verdict]
|
|
33
|
+
text = f"{symbol} {verdict.value} — {label}"
|
|
34
|
+
return f"{_COLORS[verdict]}{text}{_RESET}" if color else text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def format_sim_time(value: datetime) -> str:
|
|
38
|
+
"""Format an instant for display in East Africa Time (UTC+3, no DST)."""
|
|
39
|
+
return value.astimezone(_EAT).strftime("%H:%M:%S EAT")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def configure_utf8_stdout() -> None:
|
|
43
|
+
"""Use UTF-8 for CLI text and JSON, including Windows redirected output."""
|
|
44
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
45
|
+
if callable(reconfigure):
|
|
46
|
+
reconfigure(encoding="utf-8")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def json_line(value: BaseModel | Mapping[str, Any]) -> str:
|
|
50
|
+
"""Serialize one structured result as compact JSON on a single line."""
|
|
51
|
+
data = value.model_dump(mode="json") if isinstance(value, BaseModel) else dict(value)
|
|
52
|
+
return json.dumps(data, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
telematics/cli/init.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Safe starter templates for fleet, scenario, and shell-script files."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
import yaml # type: ignore[import-untyped]
|
|
8
|
+
|
|
9
|
+
TemplateKind = Literal["fleet", "scenario", "script"]
|
|
10
|
+
|
|
11
|
+
_TEMPLATES: Mapping[TemplateKind, str] = {
|
|
12
|
+
"fleet": """# Synthetic fleet profile mix; percentages must sum to 100.
|
|
13
|
+
seed: 42
|
|
14
|
+
vehicles: 12
|
|
15
|
+
profile_mix:
|
|
16
|
+
trk: 40
|
|
17
|
+
lry: 30
|
|
18
|
+
car: 30
|
|
19
|
+
""",
|
|
20
|
+
"scenario": """# A small simulator drill definition.
|
|
21
|
+
name: blackout-drill
|
|
22
|
+
seed: 42
|
|
23
|
+
vehicles: 12
|
|
24
|
+
duration: 1h
|
|
25
|
+
faults:
|
|
26
|
+
- fault: rural_blackout
|
|
27
|
+
vehicle_id: TRK-0001
|
|
28
|
+
severity: medium
|
|
29
|
+
""",
|
|
30
|
+
"script": """# Run with: telematics shell --script drill.tqs
|
|
31
|
+
fleet
|
|
32
|
+
expect verdict TRK-0001 PASS
|
|
33
|
+
""",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_DEFAULT_NAMES: Mapping[TemplateKind, str] = {
|
|
37
|
+
"fleet": "fleet.yaml",
|
|
38
|
+
"scenario": "scenario.yaml",
|
|
39
|
+
"script": "drill.tqs",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def render_template(kind: TemplateKind) -> str:
|
|
44
|
+
"""Return a deterministic starter file for one supported template kind."""
|
|
45
|
+
try:
|
|
46
|
+
contents = _TEMPLATES[kind]
|
|
47
|
+
except KeyError as exc:
|
|
48
|
+
raise ValueError(f"unknown template kind: {kind}") from exc
|
|
49
|
+
load_template(kind, contents)
|
|
50
|
+
return contents
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load_template(kind: TemplateKind, contents: str) -> dict[str, object] | tuple[str, ...]:
|
|
54
|
+
"""Round-trip a YAML template with safe_load or parse shell commands."""
|
|
55
|
+
if kind == "script":
|
|
56
|
+
commands = tuple(
|
|
57
|
+
line.strip()
|
|
58
|
+
for line in contents.splitlines()
|
|
59
|
+
if line.strip() and not line.lstrip().startswith("#")
|
|
60
|
+
)
|
|
61
|
+
if not commands:
|
|
62
|
+
raise ValueError("script template contains no commands")
|
|
63
|
+
return commands
|
|
64
|
+
if kind not in {"fleet", "scenario"}:
|
|
65
|
+
raise ValueError(f"unknown template kind: {kind}")
|
|
66
|
+
loaded = yaml.safe_load(contents)
|
|
67
|
+
if not isinstance(loaded, dict) or not all(isinstance(key, str) for key in loaded):
|
|
68
|
+
raise ValueError(f"{kind} template must contain a YAML mapping")
|
|
69
|
+
return loaded
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def write_template(kind: TemplateKind, path: str | Path | None = None) -> Path:
|
|
73
|
+
"""Write a starter file without overwriting an existing path."""
|
|
74
|
+
target = Path(path) if path is not None else Path(_DEFAULT_NAMES[kind])
|
|
75
|
+
contents = render_template(kind)
|
|
76
|
+
with target.open("x", encoding="utf-8", newline="\n") as output:
|
|
77
|
+
output.write(contents)
|
|
78
|
+
return target
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def init_command(kind: TemplateKind, path: str | None = None) -> int:
|
|
82
|
+
"""CLI action for printing a template or writing it to a new file."""
|
|
83
|
+
if path is None:
|
|
84
|
+
print(render_template(kind), end="")
|
|
85
|
+
return 0
|
|
86
|
+
try:
|
|
87
|
+
target = write_template(kind, path)
|
|
88
|
+
except FileExistsError:
|
|
89
|
+
print(f"refusing to overwrite {path}; choose another path")
|
|
90
|
+
return 2
|
|
91
|
+
except OSError as exc:
|
|
92
|
+
print(f"cannot write template {path}: {exc}")
|
|
93
|
+
return 4
|
|
94
|
+
print(f"wrote {kind} template to {target}")
|
|
95
|
+
return 0
|
telematics/cli/inject.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Fault injection against an attached simulator MCP server."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from telematics.cli.session import AttachedSession, MCPToolError
|
|
8
|
+
|
|
9
|
+
ToolCall = Callable[[str, dict[str, Any]], dict[str, Any]]
|
|
10
|
+
Monotonic = Callable[[], float]
|
|
11
|
+
Sleeper = Callable[[float], None]
|
|
12
|
+
_FAULT_ALIASES = {
|
|
13
|
+
"stale": "stale_device",
|
|
14
|
+
"drift": "gps_drift",
|
|
15
|
+
"blackout": "rural_blackout",
|
|
16
|
+
"dupes": "duplicate_heartbeats",
|
|
17
|
+
"flicker": "ignition_flicker",
|
|
18
|
+
"skew": "clock_skew",
|
|
19
|
+
"fuel-spike": "fuel_sensor_spike",
|
|
20
|
+
"burst": "buffered_burst",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _root_exception_message(error: BaseException) -> str:
|
|
25
|
+
"""Unwrap transport exception groups to show the actionable network cause."""
|
|
26
|
+
while isinstance(error, BaseExceptionGroup) and error.exceptions:
|
|
27
|
+
error = error.exceptions[0]
|
|
28
|
+
return str(error)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def poll_for_verdict(
|
|
32
|
+
call_tool: ToolCall,
|
|
33
|
+
*,
|
|
34
|
+
vehicle_id: str,
|
|
35
|
+
expected: str,
|
|
36
|
+
timeout_seconds: float,
|
|
37
|
+
interval_seconds: float,
|
|
38
|
+
monotonic: Monotonic = time.monotonic,
|
|
39
|
+
sleep: Sleeper = time.sleep,
|
|
40
|
+
) -> int:
|
|
41
|
+
"""Poll the public quality report until a verdict arrives or time expires."""
|
|
42
|
+
if timeout_seconds <= 0 or interval_seconds <= 0:
|
|
43
|
+
raise ValueError("timeout and polling interval must be positive")
|
|
44
|
+
deadline = monotonic() + timeout_seconds
|
|
45
|
+
while True:
|
|
46
|
+
report = call_tool("get_quality_report", {"vehicle_id": vehicle_id, "verbose": False})
|
|
47
|
+
vehicles = report.get("vehicles")
|
|
48
|
+
if vehicles:
|
|
49
|
+
observed = vehicles[0].get("data_quality", {}).get("verdict")
|
|
50
|
+
else:
|
|
51
|
+
observed = report.get("data_quality", {}).get("verdict")
|
|
52
|
+
if observed == expected:
|
|
53
|
+
return 0
|
|
54
|
+
remaining = deadline - monotonic()
|
|
55
|
+
if remaining <= 0:
|
|
56
|
+
return 1
|
|
57
|
+
sleep(min(interval_seconds, remaining))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def inject_and_wait(
|
|
61
|
+
session: AttachedSession,
|
|
62
|
+
*,
|
|
63
|
+
fault: str,
|
|
64
|
+
vehicle_id: str,
|
|
65
|
+
severity: str,
|
|
66
|
+
duration: str | None,
|
|
67
|
+
expected: str,
|
|
68
|
+
timeout_seconds: float | None,
|
|
69
|
+
interval_seconds: float = 1.0,
|
|
70
|
+
monotonic: Monotonic = time.monotonic,
|
|
71
|
+
sleep: Sleeper = time.sleep,
|
|
72
|
+
) -> int:
|
|
73
|
+
"""Inject one fault and optionally wait for its expected trust verdict."""
|
|
74
|
+
fault = _FAULT_ALIASES.get(fault, fault)
|
|
75
|
+
params: dict[str, str] = {"severity": severity}
|
|
76
|
+
if duration is not None:
|
|
77
|
+
params["duration"] = duration
|
|
78
|
+
try:
|
|
79
|
+
result = session.call_tool(
|
|
80
|
+
"inject_fault",
|
|
81
|
+
{"vehicle_id": vehicle_id, "fault": fault, "params": params},
|
|
82
|
+
)
|
|
83
|
+
except MCPToolError as exc:
|
|
84
|
+
print(f"simulator rejected the request: {exc}")
|
|
85
|
+
return 2
|
|
86
|
+
except (OSError, RuntimeError, TimeoutError, ExceptionGroup) as exc:
|
|
87
|
+
print(
|
|
88
|
+
f"cannot reach simulator at {session.url}: {_root_exception_message(exc)}\n"
|
|
89
|
+
"Start it with: uv run telematics serve --transport streamable-http",
|
|
90
|
+
)
|
|
91
|
+
return 3
|
|
92
|
+
print(
|
|
93
|
+
f"injected {result['fault']} on {vehicle_id} ({severity}) "
|
|
94
|
+
f"[{result['fault_id']}]: {result['expected_quality_impact']}"
|
|
95
|
+
)
|
|
96
|
+
if timeout_seconds is None:
|
|
97
|
+
return 0
|
|
98
|
+
try:
|
|
99
|
+
status = poll_for_verdict(
|
|
100
|
+
session.call_tool,
|
|
101
|
+
vehicle_id=vehicle_id,
|
|
102
|
+
expected=expected,
|
|
103
|
+
timeout_seconds=timeout_seconds,
|
|
104
|
+
interval_seconds=interval_seconds,
|
|
105
|
+
monotonic=monotonic,
|
|
106
|
+
sleep=sleep,
|
|
107
|
+
)
|
|
108
|
+
except MCPToolError as exc:
|
|
109
|
+
print(f"simulator rejected the quality request: {exc}")
|
|
110
|
+
return 2
|
|
111
|
+
except (OSError, RuntimeError, TimeoutError, ExceptionGroup) as exc:
|
|
112
|
+
print(
|
|
113
|
+
f"cannot reach simulator at {session.url}: {_root_exception_message(exc)}\n"
|
|
114
|
+
"Start it with: uv run telematics serve --transport streamable-http",
|
|
115
|
+
)
|
|
116
|
+
return 3
|
|
117
|
+
if status == 0:
|
|
118
|
+
print(f"observed expected {expected} verdict for {vehicle_id}")
|
|
119
|
+
else:
|
|
120
|
+
print(f"timed out waiting for {expected} verdict for {vehicle_id}")
|
|
121
|
+
return status
|