OpenZilo 0.6.3__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.
- openzilo/__init__.py +302 -0
- openzilo/__main__.py +4 -0
- openzilo/_audio.py +670 -0
- openzilo/_cli.py +751 -0
- openzilo/_cli_calibration.py +224 -0
- openzilo/_cli_config.py +46 -0
- openzilo/_client.py +364 -0
- openzilo/_codec.py +813 -0
- openzilo/_compatibility.py +209 -0
- openzilo/_device.py +243 -0
- openzilo/_errors.py +73 -0
- openzilo/_firmware_bundle.py +124 -0
- openzilo/_identity.py +23 -0
- openzilo/_imu_calibration.py +251 -0
- openzilo/_imu_profiles.py +194 -0
- openzilo/_live_audio.py +422 -0
- openzilo/_ota.py +257 -0
- openzilo/_pcm.py +87 -0
- openzilo/_protocol.py +303 -0
- openzilo/_recording.py +250 -0
- openzilo/_sensor.py +251 -0
- openzilo/_tasks.py +67 -0
- openzilo/_transport.py +371 -0
- openzilo/_version.py +2 -0
- openzilo-0.6.3.dist-info/METADATA +225 -0
- openzilo-0.6.3.dist-info/RECORD +30 -0
- openzilo-0.6.3.dist-info/WHEEL +5 -0
- openzilo-0.6.3.dist-info/entry_points.txt +2 -0
- openzilo-0.6.3.dist-info/licenses/LICENSE +373 -0
- openzilo-0.6.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Software IMU calibration in physical units. No gyro scale or axis rotation fit."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
|
+
import math
|
|
8
|
+
from statistics import mean, pstdev
|
|
9
|
+
from typing import Sequence
|
|
10
|
+
|
|
11
|
+
from ._client import OpenZiloClient
|
|
12
|
+
from ._sensor import SensorDataBatch, SensorDataSample, SensorStartInfo, wait_sensor_data
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class ImuCalibration:
|
|
17
|
+
"""Board-frame physical biases and diagonal accel gains; gyro gain stays unchanged."""
|
|
18
|
+
sensor_type: int
|
|
19
|
+
accel_range_g: int
|
|
20
|
+
gyro_range_dps: int
|
|
21
|
+
accel_bias_ug: tuple[int, int, int] = (0, 0, 0)
|
|
22
|
+
accel_scale_ppm: tuple[int, int, int] = (1000000, 1000000, 1000000)
|
|
23
|
+
gyro_bias_udps: tuple[int, int, int] = (0, 0, 0)
|
|
24
|
+
|
|
25
|
+
def __post_init__(self) -> None:
|
|
26
|
+
if (any(type(v) is not int for v in (self.sensor_type, self.accel_range_g, self.gyro_range_dps)) or
|
|
27
|
+
self.sensor_type not in (0, 1, 2, 3) or self.accel_range_g not in (2, 4, 8, 16) or
|
|
28
|
+
self.gyro_range_dps not in (0, 125, 250, 500, 1000, 2000)):
|
|
29
|
+
raise ValueError('Invalid sensor identity or ranges')
|
|
30
|
+
for values, low, high in ((self.accel_bias_ug, -200000, 200000),
|
|
31
|
+
(self.accel_scale_ppm, 800000, 1200000),
|
|
32
|
+
(self.gyro_bias_udps, -20000000, 20000000)):
|
|
33
|
+
if len(values) != 3 or any(type(v) is not int or not low <= v <= high for v in values):
|
|
34
|
+
raise ValueError('Calibration parameters exceed supported bounds')
|
|
35
|
+
for name in ('accel_bias_ug', 'accel_scale_ppm', 'gyro_bias_udps'):
|
|
36
|
+
object.__setattr__(self, name, tuple(getattr(self, name)))
|
|
37
|
+
if not self.gyro_range_dps and any(self.gyro_bias_udps):
|
|
38
|
+
raise ValueError('Accelerometer-only sensor cannot have gyro bias')
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def identity(cls, config: SensorStartInfo) -> ImuCalibration:
|
|
42
|
+
"""Unknown chip type is 0; never guess a chip identity on legacy firmware."""
|
|
43
|
+
return cls(0, config.accel_range_g, config.gyro_range_dps)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class CalibratedImuSample:
|
|
48
|
+
timestamp_ms: int
|
|
49
|
+
accel_g: tuple[float, float, float]
|
|
50
|
+
gyro_dps: tuple[float, float, float]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class CalibratedImuBatch:
|
|
55
|
+
sequence_start: int
|
|
56
|
+
frame_count: int
|
|
57
|
+
samples: tuple[CalibratedImuSample, ...]
|
|
58
|
+
applied_components: tuple[str, ...]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def apply_imu_calibration(batch: SensorDataBatch, config: SensorStartInfo,
|
|
62
|
+
calibration: ImuCalibration, *, accel: bool = True,
|
|
63
|
+
gyro: bool = True) -> CalibratedImuBatch:
|
|
64
|
+
"""Apply to RAW board-frame ADC counts, returning new physical-unit samples.
|
|
65
|
+
|
|
66
|
+
Original samples remain untouched. Device/profile/source checks belong to
|
|
67
|
+
open_calibrated_imu_stream(); offline callers must supply original raw data.
|
|
68
|
+
"""
|
|
69
|
+
if not isinstance(batch, SensorDataBatch):
|
|
70
|
+
raise ValueError('Expected raw SensorDataBatch, not already calibrated data')
|
|
71
|
+
if (config.accel_range_g != calibration.accel_range_g or
|
|
72
|
+
config.gyro_range_dps != calibration.gyro_range_dps):
|
|
73
|
+
raise ValueError('Calibration ranges differ from active IMU configuration')
|
|
74
|
+
if batch.frame_count != len(batch.samples) or batch.sample_size != 16:
|
|
75
|
+
raise ValueError('Invalid raw IMU batch')
|
|
76
|
+
converted = []
|
|
77
|
+
for sample in batch.samples:
|
|
78
|
+
a = (sample.accel_x, sample.accel_y, sample.accel_z)
|
|
79
|
+
g = (sample.gyro_x, sample.gyro_y, sample.gyro_z)
|
|
80
|
+
if any(type(v) is not int or not -32768 <= v <= 32767 for v in (*a, *g)):
|
|
81
|
+
raise ValueError('Expected signed i16 raw sensor counts')
|
|
82
|
+
converted.append(CalibratedImuSample(
|
|
83
|
+
sample.timestamp_ms,
|
|
84
|
+
tuple((v*config.accel_range_g/32768 - (calibration.accel_bias_ug[i]/1e6 if accel else 0)) *
|
|
85
|
+
(calibration.accel_scale_ppm[i]/1e6 if accel else 1) for i, v in enumerate(a)),
|
|
86
|
+
tuple(v*config.gyro_range_dps/32768 - (calibration.gyro_bias_udps[i]/1e6 if gyro else 0)
|
|
87
|
+
for i, v in enumerate(g)),
|
|
88
|
+
))
|
|
89
|
+
components = tuple(name for name, enabled in (('accel', accel), ('gyro', gyro and bool(config.gyro_range_dps)))
|
|
90
|
+
if enabled)
|
|
91
|
+
return CalibratedImuBatch(batch.sequence_start, batch.frame_count, tuple(converted), components)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class ImuStaticWindow:
|
|
96
|
+
accel_g: tuple[float, float, float]
|
|
97
|
+
gyro_dps: tuple[float, float, float]
|
|
98
|
+
accel_std_g: float
|
|
99
|
+
gyro_std_dps: float
|
|
100
|
+
samples: int
|
|
101
|
+
|
|
102
|
+
def __post_init__(self) -> None:
|
|
103
|
+
for name in ('accel_g', 'gyro_dps'):
|
|
104
|
+
values = tuple(getattr(self, name))
|
|
105
|
+
if len(values) != 3 or any(not math.isfinite(v) for v in values):
|
|
106
|
+
raise ValueError('Static window must contain finite three-axis values')
|
|
107
|
+
object.__setattr__(self, name, values)
|
|
108
|
+
if (not math.isfinite(self.accel_std_g) or self.accel_std_g < 0 or
|
|
109
|
+
not math.isfinite(self.gyro_std_dps) or self.gyro_std_dps < 0 or
|
|
110
|
+
type(self.samples) is not int or self.samples < 1):
|
|
111
|
+
raise ValueError('Invalid static window statistics')
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def face(self) -> str:
|
|
115
|
+
axis = max(range(3), key=lambda i: abs(self.accel_g[i]))
|
|
116
|
+
norm = math.sqrt(sum(v*v for v in self.accel_g))
|
|
117
|
+
if not norm or abs(self.accel_g[axis])/norm < 0.8:
|
|
118
|
+
raise ValueError('Orientation is ambiguous between two axes; adjust the case and let it settle')
|
|
119
|
+
return 'XYZ'[axis] + ('+' if self.accel_g[axis] > 0 else '-')
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def analyze_imu_static_window(samples: Sequence[SensorDataSample], config: SensorStartInfo, *,
|
|
123
|
+
check_gyro: bool = True) -> ImuStaticWindow:
|
|
124
|
+
"""Reject motion, clipping and insufficient data; thresholds await ring validation."""
|
|
125
|
+
if config.sample_rate_hz <= 0 or config.accel_range_g <= 0:
|
|
126
|
+
raise ValueError('Invalid IMU sampling configuration')
|
|
127
|
+
if len(samples) < max(20, config.sample_rate_hz * 2):
|
|
128
|
+
raise ValueError('Not enough valid samples; keep the ring still for longer')
|
|
129
|
+
axes = [(s.accel_x, s.accel_y, s.accel_z, s.gyro_x, s.gyro_y, s.gyro_z) for s in samples]
|
|
130
|
+
if any(abs(v) >= 32760 for row in axes for v in (row if check_gyro else row[:3])):
|
|
131
|
+
raise ValueError('Sensor data is saturated; calibration cannot proceed')
|
|
132
|
+
acc = [tuple(row[i] * config.accel_range_g/32768 for row in axes) for i in range(3)]
|
|
133
|
+
gyr = [tuple(row[i+3] * config.gyro_range_dps/32768 for row in axes) for i in range(3)]
|
|
134
|
+
a, g = tuple(map(mean, acc)), tuple(map(mean, gyr))
|
|
135
|
+
ast, gst = max(map(pstdev, acc)), max(map(pstdev, gyr))
|
|
136
|
+
if not 0.7 < math.sqrt(sum(v*v for v in a)) < 1.3:
|
|
137
|
+
raise ValueError('Acceleration magnitude is not near gravity; check mounting, units and sensor ranges')
|
|
138
|
+
if check_gyro and max(map(abs, g)) > 20:
|
|
139
|
+
raise ValueError('Stationary angular velocity exceeds the supported bias range; check mounting, ranges and the sensor')
|
|
140
|
+
if (ast > 0.008 or (check_gyro and gst > 0.3) or
|
|
141
|
+
any(max(v)-min(v) > 0.06 for v in acc)):
|
|
142
|
+
raise ValueError(f'Motion or vibration detected: accel standard deviation {ast:.4f} g, gyro standard deviation {gst:.3f} deg/s, '
|
|
143
|
+
f'accel peak-to-peak {max(max(v)-min(v) for v in acc):.4f} g. Keep the ring still and retry')
|
|
144
|
+
# Detect slow drift/heating within the window, not just high-frequency noise.
|
|
145
|
+
half = len(samples)//2
|
|
146
|
+
if any(abs(mean(v[:half])-mean(v[half:])) > 0.003 for v in acc) or (check_gyro and any(
|
|
147
|
+
abs(mean(v[:half])-mean(v[half:])) > 0.15 for v in gyr)):
|
|
148
|
+
raise ValueError('Readings are still drifting; wait for them to stabilize and retry')
|
|
149
|
+
return ImuStaticWindow(a, g, ast, gst, len(samples))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
async def collect_imu_static_window(client: OpenZiloClient, config: SensorStartInfo, *,
|
|
153
|
+
seconds: float = 5.0, settle_seconds: float = 1.0,
|
|
154
|
+
check_gyro: bool = True) -> ImuStaticWindow:
|
|
155
|
+
"""Collect fresh contiguous samples after a settling period; no raw captures saved."""
|
|
156
|
+
if not math.isfinite(seconds) or not 2 <= seconds <= 120:
|
|
157
|
+
raise ValueError('seconds must be between 2 and 120')
|
|
158
|
+
if not math.isfinite(settle_seconds) or not 0 <= settle_seconds <= 30:
|
|
159
|
+
raise ValueError('Invalid settling time')
|
|
160
|
+
if not 1 <= config.sample_rate_hz <= 1000:
|
|
161
|
+
raise ValueError('Unsupported sampling rate')
|
|
162
|
+
client._drain_queue(0x0605)
|
|
163
|
+
skip, target = math.ceil(settle_seconds*config.sample_rate_hz), math.ceil(seconds*config.sample_rate_hz)
|
|
164
|
+
samples: list[SensorDataSample] = []
|
|
165
|
+
sequence = None
|
|
166
|
+
deadline = asyncio.get_running_loop().time() + settle_seconds + seconds + 10
|
|
167
|
+
while len(samples) < target:
|
|
168
|
+
remaining = deadline - asyncio.get_running_loop().time()
|
|
169
|
+
if remaining <= 0:
|
|
170
|
+
raise ValueError('Sampling timed out; check the Bluetooth connection')
|
|
171
|
+
batch = await wait_sensor_data(client, timeout_s=min(remaining, 5))
|
|
172
|
+
if not batch.samples:
|
|
173
|
+
raise ValueError('Received an empty sensor batch')
|
|
174
|
+
if sequence is not None and batch.sequence_start != sequence:
|
|
175
|
+
raise ValueError('Sample sequence gap detected; ensure a stable connection and retry')
|
|
176
|
+
sequence = (batch.sequence_start + batch.frame_count) & 0xFFFFFFFF
|
|
177
|
+
for sample in batch.samples:
|
|
178
|
+
if skip:
|
|
179
|
+
skip -= 1
|
|
180
|
+
elif len(samples) < target:
|
|
181
|
+
samples.append(sample)
|
|
182
|
+
return analyze_imu_static_window(samples, config, check_gyro=check_gyro)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def fit_imu_gyro_bias(previous: ImuCalibration, window: ImuStaticWindow) -> ImuCalibration:
|
|
186
|
+
"""Input window must contain RAW samples, not previously corrected samples."""
|
|
187
|
+
if not previous.gyro_range_dps:
|
|
188
|
+
raise ValueError('This sensor has no gyroscope')
|
|
189
|
+
result = replace(previous, gyro_bias_udps=tuple(round(v*1000000) for v in window.gyro_dps))
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _solve(matrix: list[list[float]], rhs: list[float]) -> list[float]:
|
|
194
|
+
n = len(rhs)
|
|
195
|
+
m = [list(row)+[value] for row, value in zip(matrix, rhs)]
|
|
196
|
+
for col in range(n):
|
|
197
|
+
pivot = max(range(col, n), key=lambda r: abs(m[r][col]))
|
|
198
|
+
if abs(m[pivot][col]) < 1e-7:
|
|
199
|
+
raise ValueError('Six-face data does not support a stable fit; collect the faces again')
|
|
200
|
+
m[col], m[pivot] = m[pivot], m[col]
|
|
201
|
+
scale = m[col][col]
|
|
202
|
+
m[col] = [v/scale for v in m[col]]
|
|
203
|
+
for row in range(n):
|
|
204
|
+
if row == col:
|
|
205
|
+
continue
|
|
206
|
+
factor = m[row][col]
|
|
207
|
+
m[row] = [a-factor*b for a, b in zip(m[row], m[col])]
|
|
208
|
+
return [row[-1] for row in m]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def fit_imu_six_face_calibration(previous: ImuCalibration,
|
|
212
|
+
windows: Sequence[ImuStaticWindow]) -> ImuCalibration:
|
|
213
|
+
"""Fit a diagonal ellipsoid to six RAW static positions; no cross-axis fit.
|
|
214
|
+
|
|
215
|
+
Preserves gyro bias: estimate it from a fresh static window after the faces.
|
|
216
|
+
Uses gravity magnitude, so small fixture tilt is allowed. Six distinct
|
|
217
|
+
dominant signed axes are required; independent validation is mandatory.
|
|
218
|
+
"""
|
|
219
|
+
if len(windows) != 6 or {w.face for w in windows} != {'X+', 'X-', 'Y+', 'Y-', 'Z+', 'Z-'}:
|
|
220
|
+
raise ValueError('Six distinct orientations are required, each with a stable data window')
|
|
221
|
+
rows = [[*(v*v for v in w.accel_g), *w.accel_g] for w in windows]
|
|
222
|
+
q = _solve(rows, [1.0]*6)
|
|
223
|
+
if any(v <= 0 or not math.isfinite(v) for v in q[:3]):
|
|
224
|
+
raise ValueError('Calibration fit is invalid; check the six-face recordings')
|
|
225
|
+
bias = [-q[i+3]/(2*q[i]) for i in range(3)]
|
|
226
|
+
denominator = 1 + sum(q[i]*bias[i]*bias[i] for i in range(3))
|
|
227
|
+
gains = [math.sqrt(q[i]/denominator) for i in range(3)]
|
|
228
|
+
result = replace(previous,
|
|
229
|
+
accel_bias_ug=tuple(round(v*1000000) for v in bias),
|
|
230
|
+
accel_scale_ppm=tuple(round(v*1000000) for v in gains))
|
|
231
|
+
return result
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def validate_imu_calibration(windows: Sequence[ImuStaticWindow], *, full: bool,
|
|
235
|
+
component: str = "all") -> dict[str, float]:
|
|
236
|
+
"""Validate NEW corrected samples, separate from fitting samples."""
|
|
237
|
+
if component not in ('all', 'accel', 'gyro'):
|
|
238
|
+
raise ValueError('Unknown validation component')
|
|
239
|
+
if len(windows) < (3 if full else 1):
|
|
240
|
+
raise ValueError('Not enough independent validation data')
|
|
241
|
+
if full:
|
|
242
|
+
if len({w.face for w in windows}) < 3:
|
|
243
|
+
raise ValueError('Use at least three distinct orientations for validation')
|
|
244
|
+
if len({w.face[0] for w in windows}) < 3:
|
|
245
|
+
raise ValueError('Validation must cover all three axes')
|
|
246
|
+
gravity_error = max(abs(math.sqrt(sum(v*v for v in w.accel_g))-1) for w in windows)
|
|
247
|
+
gyro_error = max(abs(v) for w in windows for v in w.gyro_dps)
|
|
248
|
+
if ((component != 'gyro' and (full or component == 'accel') and gravity_error > 0.015) or
|
|
249
|
+
(component != 'accel' and gyro_error > 0.15)):
|
|
250
|
+
raise ValueError(f'Validation failed: gravity magnitude error {gravity_error:.4f} g, gyro residual {gyro_error:.3f} deg/s')
|
|
251
|
+
return {'max_gravity_error_g': gravity_error, 'max_gyro_residual_dps': gyro_error}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Local software profiles and an explicit calibrated IMU stream. No device writes."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import tempfile
|
|
13
|
+
from typing import AsyncIterator
|
|
14
|
+
|
|
15
|
+
from ._cli_config import config_path
|
|
16
|
+
from ._client import OpenZiloClient
|
|
17
|
+
from ._compatibility import get_device_capabilities
|
|
18
|
+
from ._device import get_system_info
|
|
19
|
+
from ._errors import CompatibilityError, ProtocolError, TransportError
|
|
20
|
+
from ._imu_calibration import CalibratedImuBatch, ImuCalibration, apply_imu_calibration
|
|
21
|
+
from ._sensor import SensorStartInfo, start_sensor_report, stop_sensor_report, wait_sensor_data
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def imu_device_key(device_id: str) -> str:
|
|
25
|
+
"""Local binding key; identifiers are hashed rather than embedded in profiles."""
|
|
26
|
+
if not isinstance(device_id, str) or not device_id.strip():
|
|
27
|
+
raise ValueError('A device address/identifier is required')
|
|
28
|
+
return hashlib.sha256(device_id.strip().casefold().encode('utf-8')).hexdigest()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def imu_calibration_path(device_id: str) -> Path:
|
|
32
|
+
"""Per-device profile next to CLI preferences, outside the source checkout."""
|
|
33
|
+
return config_path().parent / 'imu' / (imu_device_key(device_id) + '.json')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ImuCalibrationProfile:
|
|
38
|
+
device_key: str
|
|
39
|
+
firmware_version: str
|
|
40
|
+
model: str
|
|
41
|
+
calibration: ImuCalibration
|
|
42
|
+
accel_validated: bool = False
|
|
43
|
+
gyro_validated: bool = False
|
|
44
|
+
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
|
|
45
|
+
|
|
46
|
+
def __post_init__(self) -> None:
|
|
47
|
+
if (not isinstance(self.device_key, str) or len(self.device_key) != 64 or
|
|
48
|
+
any(c not in '0123456789abcdef' for c in self.device_key)):
|
|
49
|
+
raise ValueError('Invalid profile device key')
|
|
50
|
+
if not isinstance(self.firmware_version, str) or not self.firmware_version:
|
|
51
|
+
raise ValueError('Missing firmware identity')
|
|
52
|
+
if not isinstance(self.model, str) or not self.model:
|
|
53
|
+
raise ValueError('Missing device model')
|
|
54
|
+
if not isinstance(self.calibration, ImuCalibration):
|
|
55
|
+
raise ValueError('Invalid calibration parameters')
|
|
56
|
+
if type(self.accel_validated) is not bool or type(self.gyro_validated) is not bool:
|
|
57
|
+
raise ValueError('Invalid component validation flags')
|
|
58
|
+
if not (self.accel_validated or self.gyro_validated):
|
|
59
|
+
raise ValueError('A profile must have at least one validated component')
|
|
60
|
+
c = self.calibration
|
|
61
|
+
if not self.accel_validated and (any(c.accel_bias_ug) or c.accel_scale_ppm != (1000000,)*3):
|
|
62
|
+
raise ValueError('Unvalidated accelerometer parameters must be identity')
|
|
63
|
+
if not self.gyro_validated and any(c.gyro_bias_udps):
|
|
64
|
+
raise ValueError('Unvalidated gyro parameters must be zero')
|
|
65
|
+
if self.gyro_validated and not c.gyro_range_dps:
|
|
66
|
+
raise ValueError('Cannot validate gyro on an accelerometer-only sensor')
|
|
67
|
+
try:
|
|
68
|
+
if datetime.fromisoformat(self.created_at).tzinfo is None:
|
|
69
|
+
raise ValueError('Profile date must include timezone')
|
|
70
|
+
except (TypeError, ValueError) as exc:
|
|
71
|
+
raise ValueError('Invalid profile creation date') from exc
|
|
72
|
+
|
|
73
|
+
def check_device(self, device_id: str, firmware_version: str, model: str) -> None:
|
|
74
|
+
if self.device_key != imu_device_key(device_id):
|
|
75
|
+
raise CompatibilityError('IMU profile belongs to another device')
|
|
76
|
+
if self.firmware_version != firmware_version or self.model != model:
|
|
77
|
+
raise CompatibilityError('IMU profile firmware/model differs; recalibrate after upgrading')
|
|
78
|
+
|
|
79
|
+
def apply(self, batch, config: SensorStartInfo) -> CalibratedImuBatch:
|
|
80
|
+
return apply_imu_calibration(batch, config, self.calibration,
|
|
81
|
+
accel=self.accel_validated, gyro=self.gyro_validated)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def save_imu_calibration_profile(profile: ImuCalibrationProfile, path: Path) -> None:
|
|
85
|
+
"""Atomically replace a local profile. Call only after independent validation."""
|
|
86
|
+
path = Path(path)
|
|
87
|
+
payload = {'schema_version': 1, 'application': 'software', 'input_domain': 'board_adc_counts',
|
|
88
|
+
'bias_accel_unit': 'micro_g', 'bias_gyro_unit': 'micro_deg_per_s',
|
|
89
|
+
'scale_unit': 'ppm', **asdict(profile)}
|
|
90
|
+
encoded = json.dumps(payload, indent=2, allow_nan=False) + '\n'
|
|
91
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
fd, temporary = tempfile.mkstemp(prefix='.imu-', dir=path.parent)
|
|
93
|
+
try:
|
|
94
|
+
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
|
95
|
+
stream.write(encoded)
|
|
96
|
+
stream.flush()
|
|
97
|
+
os.fsync(stream.fileno())
|
|
98
|
+
os.replace(temporary, path)
|
|
99
|
+
finally:
|
|
100
|
+
Path(temporary).unlink(missing_ok=True)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def load_imu_calibration_profile(path: Path) -> ImuCalibrationProfile:
|
|
104
|
+
"""Strict schema/units checking; malformed profiles never silently disable correction."""
|
|
105
|
+
try:
|
|
106
|
+
data = json.loads(Path(path).read_text(encoding='utf-8'))
|
|
107
|
+
metadata = {'schema_version': 1, 'application': 'software', 'input_domain': 'board_adc_counts',
|
|
108
|
+
'bias_accel_unit': 'micro_g', 'bias_gyro_unit': 'micro_deg_per_s', 'scale_unit': 'ppm'}
|
|
109
|
+
if not isinstance(data, dict) or type(data.get('schema_version')) is not int:
|
|
110
|
+
raise ValueError('Invalid profile object')
|
|
111
|
+
for key, expected in metadata.items():
|
|
112
|
+
if data.pop(key, None) != expected:
|
|
113
|
+
raise ValueError(f'Unsupported IMU profile {key}')
|
|
114
|
+
c = data.pop('calibration')
|
|
115
|
+
if not isinstance(c, dict):
|
|
116
|
+
raise ValueError('Invalid calibration record')
|
|
117
|
+
for key in ('accel_bias_ug', 'accel_scale_ppm', 'gyro_bias_udps'):
|
|
118
|
+
c[key] = tuple(c[key])
|
|
119
|
+
return ImuCalibrationProfile(calibration=ImuCalibration(**c), **data)
|
|
120
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
121
|
+
raise ValueError(f'Invalid IMU calibration profile: {exc}') from exc
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def require_software_imu_source(client: OpenZiloClient) -> None:
|
|
125
|
+
"""Only consume supported raw IMU contracts; refuse firmware calibration layers."""
|
|
126
|
+
caps = await get_device_capabilities(client)
|
|
127
|
+
caps.require('imu')
|
|
128
|
+
if any(f.name in ('imu_calibration', 'unknown_11') for f in caps.features):
|
|
129
|
+
raise CompatibilityError('Firmware advertises IMU calibration; software correction is disabled '
|
|
130
|
+
'until an explicit raw-data contract is supported')
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class CalibratedImuStream:
|
|
134
|
+
"""Physical-unit view of raw batches; only valid inside its opening context."""
|
|
135
|
+
def __init__(self, client, config, profile):
|
|
136
|
+
self.config = config
|
|
137
|
+
self.profile = profile
|
|
138
|
+
self._client = client
|
|
139
|
+
self._connection = client._connection_token
|
|
140
|
+
self._closed = False
|
|
141
|
+
|
|
142
|
+
def __aiter__(self):
|
|
143
|
+
return self
|
|
144
|
+
|
|
145
|
+
async def __anext__(self) -> CalibratedImuBatch:
|
|
146
|
+
if self._closed:
|
|
147
|
+
raise StopAsyncIteration
|
|
148
|
+
if self._client._connection_token is not self._connection:
|
|
149
|
+
raise TransportError('Connection changed; reopen the calibrated IMU stream')
|
|
150
|
+
batch = await wait_sensor_data(self._client)
|
|
151
|
+
if self._client._connection_token is not self._connection:
|
|
152
|
+
raise TransportError('Connection changed while receiving IMU data')
|
|
153
|
+
return self.profile.apply(batch, self.config)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@asynccontextmanager
|
|
157
|
+
async def open_calibrated_imu_stream(client: OpenZiloClient, profile: ImuCalibrationProfile | None = None,
|
|
158
|
+
*, device_id: str | None = None) -> AsyncIterator[CalibratedImuStream]:
|
|
159
|
+
"""Start/stop a software-corrected stream using a matching local profile.
|
|
160
|
+
|
|
161
|
+
No calibration commands are sent. Old raw APIs remain unchanged. Do not run
|
|
162
|
+
another IMU consumer on the same connection while this context owns reports.
|
|
163
|
+
"""
|
|
164
|
+
if getattr(client, '_software_imu_stream_active', False):
|
|
165
|
+
raise ProtocolError('A software IMU stream already owns this client')
|
|
166
|
+
client._software_imu_stream_active = True
|
|
167
|
+
stream = None
|
|
168
|
+
started = False
|
|
169
|
+
connection = client._connection_token
|
|
170
|
+
try:
|
|
171
|
+
await require_software_imu_source(client)
|
|
172
|
+
identifier = device_id or getattr(client.transport, 'address', None)
|
|
173
|
+
if profile is None:
|
|
174
|
+
profile = load_imu_calibration_profile(imu_calibration_path(identifier))
|
|
175
|
+
info = await get_system_info(client)
|
|
176
|
+
profile.check_device(identifier, info.firmware_version, info.model)
|
|
177
|
+
started = True
|
|
178
|
+
config = await start_sensor_report(client)
|
|
179
|
+
if (config.accel_range_g != profile.calibration.accel_range_g or
|
|
180
|
+
config.gyro_range_dps != profile.calibration.gyro_range_dps):
|
|
181
|
+
raise CompatibilityError('IMU profile range differs from device configuration')
|
|
182
|
+
if connection is not client._connection_token:
|
|
183
|
+
raise TransportError('Connection changed while opening IMU stream')
|
|
184
|
+
client._drain_queue(0x0605)
|
|
185
|
+
stream = CalibratedImuStream(client, config, profile)
|
|
186
|
+
yield stream
|
|
187
|
+
finally:
|
|
188
|
+
if stream:
|
|
189
|
+
stream._closed = True
|
|
190
|
+
try:
|
|
191
|
+
if started and connection is client._connection_token:
|
|
192
|
+
await stop_sensor_report(client)
|
|
193
|
+
finally:
|
|
194
|
+
client._software_imu_stream_active = False
|