Coverage for src/bluetooth_sig/gatt/characteristics/glucose_measurement.py: 80%
160 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-30 00:10 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-30 00:10 +0000
1"""Glucose Measurement characteristic implementation."""
3from __future__ import annotations
5from datetime import datetime
6from enum import IntEnum, IntFlag
8import msgspec
10from ..constants import SINT16_MAX, SINT16_MIN
11from ..context import CharacteristicContext
12from .base import BaseCharacteristic
13from .glucose_feature import GlucoseFeatureCharacteristic, GlucoseFeatureData, GlucoseFeatures
14from .utils import BitFieldUtils, DataParser, IEEE11073Parser
17class GlucoseMeasurementBits:
18 """Glucose measurement bit field constants."""
20 # pylint: disable=missing-class-docstring,too-few-public-methods
22 # Glucose Measurement bit field constants
23 GLUCOSE_TYPE_SAMPLE_MASK = 0x0F # 4-bit mask for type and sample location
24 GLUCOSE_TYPE_START_BIT = 4 # Glucose type in high 4 bits
25 GLUCOSE_TYPE_BIT_WIDTH = 4
26 GLUCOSE_SAMPLE_LOCATION_START_BIT = 0 # Sample location in low 4 bits
27 GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH = 4
30class GlucoseType(IntEnum):
31 """Glucose sample type enumeration as per Bluetooth SIG specification."""
33 CAPILLARY_WHOLE_BLOOD = 1
34 CAPILLARY_PLASMA = 2
35 VENOUS_WHOLE_BLOOD = 3
36 VENOUS_PLASMA = 4
37 ARTERIAL_WHOLE_BLOOD = 5
38 ARTERIAL_PLASMA = 6
39 UNDETERMINED_WHOLE_BLOOD = 7
40 UNDETERMINED_PLASMA = 8
41 INTERSTITIAL_FLUID = 9
42 CONTROL_SOLUTION = 10
43 # Values 11-15 (0xB-0xF) are Reserved for Future Use
45 def __str__(self) -> str:
46 """Return human-readable glucose type name."""
47 names = {
48 self.CAPILLARY_WHOLE_BLOOD: "Capillary Whole blood",
49 self.CAPILLARY_PLASMA: "Capillary Plasma",
50 self.VENOUS_WHOLE_BLOOD: "Venous Whole blood",
51 self.VENOUS_PLASMA: "Venous Plasma",
52 self.ARTERIAL_WHOLE_BLOOD: "Arterial Whole blood",
53 self.ARTERIAL_PLASMA: "Arterial Plasma",
54 self.UNDETERMINED_WHOLE_BLOOD: "Undetermined Whole blood",
55 self.UNDETERMINED_PLASMA: "Undetermined Plasma",
56 self.INTERSTITIAL_FLUID: "Interstitial Fluid (ISF)",
57 self.CONTROL_SOLUTION: "Control Solution",
58 }
59 return names[self]
62class SampleLocation(IntEnum):
63 """Sample location enumeration as per Bluetooth SIG specification."""
65 # Value 0 is Reserved for Future Use
66 FINGER = 1
67 ALTERNATE_SITE_TEST = 2
68 EARLOBE = 3
69 CONTROL_SOLUTION = 4
70 # Values 5-14 (0x5-0xE) are Reserved for Future Use
71 NOT_AVAILABLE = 15
73 def __str__(self) -> str:
74 """Return human-readable sample location name."""
75 names = {
76 self.FINGER: "Finger",
77 self.ALTERNATE_SITE_TEST: "Alternate Site Test (AST)",
78 self.EARLOBE: "Earlobe",
79 self.CONTROL_SOLUTION: "Control solution",
80 self.NOT_AVAILABLE: "Sample Location value not available",
81 }
82 return names[self]
85class GlucoseMeasurementFlags(IntFlag):
86 """Glucose Measurement flags as per Bluetooth SIG specification."""
88 TIME_OFFSET_PRESENT = 0x01
89 GLUCOSE_CONCENTRATION_UNITS_MMOL_L = 0x02
90 TYPE_SAMPLE_LOCATION_PRESENT = 0x04
91 SENSOR_STATUS_ANNUNCIATION_PRESENT = 0x08
94class GlucoseMeasurementData(msgspec.Struct, frozen=True, kw_only=True): # pylint: disable=too-few-public-methods,too-many-instance-attributes
95 """Parsed glucose measurement data."""
97 sequence_number: int
98 base_time: datetime
99 glucose_concentration: float
100 unit: str
101 flags: GlucoseMeasurementFlags
102 time_offset_minutes: int | None = None
103 glucose_type: GlucoseType | None = None
104 sample_location: SampleLocation | None = None
105 sensor_status: int | None = None
107 min_length: int = 12 # Aligned with GlucoseMeasurementCharacteristic
108 max_length: int = 17 # Aligned with GlucoseMeasurementCharacteristic
110 def __post_init__(self) -> None:
111 """Validate glucose measurement data."""
112 if self.unit not in ("mg/dL", "mmol/L"):
113 raise ValueError(f"Glucose unit must be 'mg/dL' or 'mmol/L', got {self.unit}")
115 # Validate concentration range based on unit
116 if self.unit == "mg/dL":
117 # Allow any non-negative value (no SIG-specified range)
118 if self.glucose_concentration < 0:
119 raise ValueError(f"Glucose concentration must be non-negative, got {self.glucose_concentration}")
120 else: # mmol/L
121 # Allow any non-negative value (no SIG-specified range)
122 if self.glucose_concentration < 0:
123 raise ValueError(f"Glucose concentration must be non-negative, got {self.glucose_concentration}")
125 @staticmethod
126 def is_reserved_range(value: int) -> bool:
127 """Check if glucose type or sample location is in reserved range."""
128 return value in {0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
131class GlucoseMeasurementCharacteristic(BaseCharacteristic):
132 """Glucose Measurement characteristic (0x2A18).
134 Used to transmit glucose concentration measurements with timestamps
135 and status. Core characteristic for glucose monitoring devices.
136 """
138 _manual_unit: str = "mg/dL or mmol/L" # Unit depends on flags
140 min_length: int = 12 # Ensured consistency with GlucoseMeasurementData
141 max_length: int = 17 # Ensured consistency with GlucoseMeasurementData
142 allow_variable_length: bool = True # Variable optional fields
144 def decode_value(self, data: bytearray, ctx: CharacteristicContext | None = None) -> GlucoseMeasurementData: # pylint: disable=too-many-locals
145 """Parse glucose measurement data according to Bluetooth specification.
147 Format: Flags(1) + Sequence Number(2) + Base Time(7) + [Time Offset(2)] +
148 Glucose Concentration(2) + [Type-Sample Location(1)] + [Sensor Status(2)].
150 Args:
151 data: Raw bytearray from BLE characteristic.
152 ctx: Optional CharacteristicContext providing surrounding context (may be None).
154 Returns:
155 GlucoseMeasurementData containing parsed glucose measurement data with metadata.
157 Raises:
158 ValueError: If data format is invalid.
160 """
161 if len(data) < 12:
162 raise ValueError("Glucose Measurement data must be at least 12 bytes")
164 flags = GlucoseMeasurementFlags(data[0])
165 offset = 1
167 # Parse sequence number (2 bytes)
168 sequence_number = DataParser.parse_int16(data, offset, signed=False)
169 offset += 2
171 # Parse base time (7 bytes) - IEEE-11073 timestamp
172 base_time = IEEE11073Parser.parse_timestamp(data, offset)
173 offset += 7
175 # Parse optional time offset (2 bytes) if present
176 time_offset_minutes = None
177 if GlucoseMeasurementFlags.TIME_OFFSET_PRESENT in flags and len(data) >= offset + 2:
178 time_offset_minutes = DataParser.parse_int16(data, offset, signed=True) # signed
179 offset += 2
181 # Parse glucose concentration (2 bytes) - IEEE-11073 SFLOAT
182 glucose_concentration = 0.0
183 unit = "mg/dL"
184 if len(data) >= offset + 2:
185 glucose_concentration = IEEE11073Parser.parse_sfloat(data, offset)
186 # Determine unit based on flags
187 unit = "mmol/L" if GlucoseMeasurementFlags.GLUCOSE_CONCENTRATION_UNITS_MMOL_L in flags else "mg/dL"
188 offset += 2
190 # Parse optional type and sample location (1 byte) if present
191 glucose_type = None
192 sample_location = None
193 if GlucoseMeasurementFlags.TYPE_SAMPLE_LOCATION_PRESENT in flags and len(data) >= offset + 1:
194 type_sample = data[offset]
195 glucose_type_val = BitFieldUtils.extract_bit_field(
196 type_sample,
197 GlucoseMeasurementBits.GLUCOSE_TYPE_START_BIT,
198 GlucoseMeasurementBits.GLUCOSE_TYPE_BIT_WIDTH,
199 )
200 sample_location_val = BitFieldUtils.extract_bit_field(
201 type_sample,
202 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_START_BIT,
203 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH,
204 )
206 glucose_type = GlucoseType(glucose_type_val)
207 sample_location = SampleLocation(sample_location_val)
209 offset += 1
211 # Parse optional sensor status annotation (2 bytes) if present
212 sensor_status = None
213 if GlucoseMeasurementFlags.SENSOR_STATUS_ANNUNCIATION_PRESENT in flags and len(data) >= offset + 2:
214 sensor_status = DataParser.parse_int16(data, offset, signed=False)
216 # Validate sensor status against Glucose Feature if available
217 if ctx is not None and sensor_status is not None:
218 feature_char = self.get_context_characteristic(ctx, GlucoseFeatureCharacteristic)
219 if feature_char and feature_char.parse_success and feature_char.value is not None:
220 self._validate_sensor_status_against_feature(sensor_status, feature_char.value)
222 # Create result with all parsed values
223 return GlucoseMeasurementData(
224 sequence_number=sequence_number,
225 base_time=base_time,
226 glucose_concentration=glucose_concentration,
227 unit=unit,
228 flags=flags,
229 time_offset_minutes=time_offset_minutes,
230 glucose_type=glucose_type,
231 sample_location=sample_location,
232 sensor_status=sensor_status,
233 )
235 def encode_value(self, data: GlucoseMeasurementData) -> bytearray: # pylint: disable=too-many-locals,too-many-branches # Complex medical data encoding
236 """Encode glucose measurement value back to bytes.
238 Args:
239 data: GlucoseMeasurementData containing glucose measurement data
241 Returns:
242 Encoded bytes representing the glucose measurement
244 """
245 # Build flags based on available data
246 flags = GlucoseMeasurementFlags(0)
247 if data.time_offset_minutes is not None:
248 flags |= GlucoseMeasurementFlags.TIME_OFFSET_PRESENT
249 if data.unit == "mmol/L":
250 flags |= GlucoseMeasurementFlags.GLUCOSE_CONCENTRATION_UNITS_MMOL_L
251 if data.glucose_type is not None or data.sample_location is not None:
252 flags |= GlucoseMeasurementFlags.TYPE_SAMPLE_LOCATION_PRESENT
253 if data.sensor_status is not None:
254 flags |= GlucoseMeasurementFlags.SENSOR_STATUS_ANNUNCIATION_PRESENT
256 # Validate ranges
257 if not 0 <= data.sequence_number <= 0xFFFF:
258 raise ValueError(f"Sequence number {data.sequence_number} exceeds uint16 range")
260 # Start with flags, sequence number, and base time
261 result = bytearray([int(flags)])
262 result.extend(DataParser.encode_int16(data.sequence_number, signed=False))
263 result.extend(IEEE11073Parser.encode_timestamp(data.base_time))
265 # Add optional time offset
266 if data.time_offset_minutes is not None:
267 if not SINT16_MIN <= data.time_offset_minutes <= SINT16_MAX:
268 raise ValueError(f"Time offset {data.time_offset_minutes} exceeds sint16 range")
269 result.extend(DataParser.encode_int16(data.time_offset_minutes, signed=True))
271 # Add glucose concentration using IEEE-11073 SFLOAT
272 result.extend(IEEE11073Parser.encode_sfloat(data.glucose_concentration))
274 # Add optional type and sample location
275 if data.glucose_type is not None or data.sample_location is not None:
276 glucose_type = data.glucose_type or 0
277 sample_location = data.sample_location or 0
278 type_sample = BitFieldUtils.merge_bit_fields(
279 (
280 glucose_type,
281 GlucoseMeasurementBits.GLUCOSE_TYPE_START_BIT,
282 GlucoseMeasurementBits.GLUCOSE_TYPE_BIT_WIDTH,
283 ),
284 (
285 sample_location,
286 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_START_BIT,
287 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH,
288 ),
289 )
290 result.append(type_sample)
292 # Add optional sensor status
293 if data.sensor_status is not None:
294 if not 0 <= data.sensor_status <= 0xFFFF:
295 raise ValueError(f"Sensor status {data.sensor_status} exceeds uint16 range")
296 result.extend(DataParser.encode_int16(data.sensor_status, signed=False))
298 return result
300 def _validate_sensor_status_against_feature(self, sensor_status: int, feature_data: GlucoseFeatureData) -> None:
301 """Validate sensor status bits against supported Glucose Features.
303 Args:
304 sensor_status: Raw sensor status bitmask from measurement
305 feature_data: GlucoseFeatureData from Glucose Feature characteristic
307 Raises:
308 ValueError: If reported sensor status bits are not supported by device features
310 """
311 # Sensor status bits correspond to Glucose Feature bits
312 # Check each status bit against corresponding feature support
313 if (sensor_status & GlucoseFeatures.LOW_BATTERY_DETECTION) and not feature_data.low_battery_detection:
314 raise ValueError("Low battery status reported but not supported by Glucose Feature")
315 if (
316 sensor_status & GlucoseFeatures.SENSOR_MALFUNCTION_DETECTION
317 ) and not feature_data.sensor_malfunction_detection:
318 raise ValueError("Sensor malfunction status reported but not supported by Glucose Feature")
319 if (sensor_status & GlucoseFeatures.SENSOR_SAMPLE_SIZE) and not feature_data.sensor_sample_size:
320 raise ValueError("Sensor sample size status reported but not supported by Glucose Feature")
321 if (
322 sensor_status & GlucoseFeatures.SENSOR_STRIP_INSERTION_ERROR
323 ) and not feature_data.sensor_strip_insertion_error:
324 raise ValueError("Sensor strip insertion error status reported but not supported by Glucose Feature")
325 if (sensor_status & GlucoseFeatures.SENSOR_STRIP_TYPE_ERROR) and not feature_data.sensor_strip_type_error:
326 raise ValueError("Sensor strip type error status reported but not supported by Glucose Feature")
327 if (sensor_status & GlucoseFeatures.SENSOR_RESULT_HIGH_LOW) and not feature_data.sensor_result_high_low:
328 raise ValueError("Sensor result high-low status reported but not supported by Glucose Feature")
329 if (
330 sensor_status & GlucoseFeatures.SENSOR_TEMPERATURE_HIGH_LOW
331 ) and not feature_data.sensor_temperature_high_low:
332 raise ValueError("Sensor temperature high-low status reported but not supported by Glucose Feature")
333 if (sensor_status & GlucoseFeatures.SENSOR_READ_INTERRUPT) and not feature_data.sensor_read_interrupt:
334 raise ValueError("Sensor read interrupt status reported but not supported by Glucose Feature")
335 if (sensor_status & GlucoseFeatures.GENERAL_DEVICE_FAULT) and not feature_data.general_device_fault:
336 raise ValueError("General device fault status reported but not supported by Glucose Feature")
337 if (sensor_status & GlucoseFeatures.TIME_FAULT) and not feature_data.time_fault:
338 raise ValueError("Time fault status reported but not supported by Glucose Feature")
339 if (sensor_status & GlucoseFeatures.MULTIPLE_BOND_SUPPORT) and not feature_data.multiple_bond_support:
340 raise ValueError("Multiple bond status reported but not supported by Glucose Feature")