Coverage for src / bluetooth_sig / gatt / characteristics / glucose_measurement.py: 80%
161 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-11 20:14 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-11 20:14 +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[GlucoseMeasurementData]):
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 _optional_dependencies = [GlucoseFeatureCharacteristic]
142 min_length: int = 12 # Ensured consistency with GlucoseMeasurementData
143 max_length: int = 17 # Ensured consistency with GlucoseMeasurementData
144 allow_variable_length: bool = True # Variable optional fields
146 def _decode_value(self, data: bytearray, ctx: CharacteristicContext | None = None) -> GlucoseMeasurementData: # pylint: disable=too-many-locals
147 """Parse glucose measurement data according to Bluetooth specification.
149 Format: Flags(1) + Sequence Number(2) + Base Time(7) + [Time Offset(2)] +
150 Glucose Concentration(2) + [Type-Sample Location(1)] + [Sensor Status(2)].
152 Args:
153 data: Raw bytearray from BLE characteristic.
154 ctx: Optional CharacteristicContext providing surrounding context (may be None).
156 Returns:
157 GlucoseMeasurementData containing parsed glucose measurement data with metadata.
159 Raises:
160 ValueError: If data format is invalid.
162 """
163 if len(data) < 12:
164 raise ValueError("Glucose Measurement data must be at least 12 bytes")
166 flags = GlucoseMeasurementFlags(data[0])
167 offset = 1
169 # Parse sequence number (2 bytes)
170 sequence_number = DataParser.parse_int16(data, offset, signed=False)
171 offset += 2
173 # Parse base time (7 bytes) - IEEE-11073 timestamp
174 base_time = IEEE11073Parser.parse_timestamp(data, offset)
175 offset += 7
177 # Parse optional time offset (2 bytes) if present
178 time_offset_minutes = None
179 if GlucoseMeasurementFlags.TIME_OFFSET_PRESENT in flags and len(data) >= offset + 2:
180 time_offset_minutes = DataParser.parse_int16(data, offset, signed=True) # signed
181 offset += 2
183 # Parse glucose concentration (2 bytes) - IEEE-11073 SFLOAT
184 glucose_concentration = 0.0
185 unit = "mg/dL"
186 if len(data) >= offset + 2:
187 glucose_concentration = IEEE11073Parser.parse_sfloat(data, offset)
188 # Determine unit based on flags
189 unit = "mmol/L" if GlucoseMeasurementFlags.GLUCOSE_CONCENTRATION_UNITS_MMOL_L in flags else "mg/dL"
190 offset += 2
192 # Parse optional type and sample location (1 byte) if present
193 glucose_type = None
194 sample_location = None
195 if GlucoseMeasurementFlags.TYPE_SAMPLE_LOCATION_PRESENT in flags and len(data) >= offset + 1:
196 type_sample = data[offset]
197 glucose_type_val = BitFieldUtils.extract_bit_field(
198 type_sample,
199 GlucoseMeasurementBits.GLUCOSE_TYPE_START_BIT,
200 GlucoseMeasurementBits.GLUCOSE_TYPE_BIT_WIDTH,
201 )
202 sample_location_val = BitFieldUtils.extract_bit_field(
203 type_sample,
204 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_START_BIT,
205 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH,
206 )
208 glucose_type = GlucoseType(glucose_type_val)
209 sample_location = SampleLocation(sample_location_val)
211 offset += 1
213 # Parse optional sensor status annotation (2 bytes) if present
214 sensor_status = None
215 if GlucoseMeasurementFlags.SENSOR_STATUS_ANNUNCIATION_PRESENT in flags and len(data) >= offset + 2:
216 sensor_status = DataParser.parse_int16(data, offset, signed=False)
218 # Validate sensor status against Glucose Feature if available
219 if ctx is not None and sensor_status is not None:
220 feature_value = self.get_context_characteristic(ctx, GlucoseFeatureCharacteristic)
221 if feature_value is not None:
222 self._validate_sensor_status_against_feature(sensor_status, feature_value)
224 # Create result with all parsed values
225 return GlucoseMeasurementData(
226 sequence_number=sequence_number,
227 base_time=base_time,
228 glucose_concentration=glucose_concentration,
229 unit=unit,
230 flags=flags,
231 time_offset_minutes=time_offset_minutes,
232 glucose_type=glucose_type,
233 sample_location=sample_location,
234 sensor_status=sensor_status,
235 )
237 def _encode_value(self, data: GlucoseMeasurementData) -> bytearray: # pylint: disable=too-many-locals,too-many-branches # Complex medical data encoding
238 """Encode glucose measurement value back to bytes.
240 Args:
241 data: GlucoseMeasurementData containing glucose measurement data
243 Returns:
244 Encoded bytes representing the glucose measurement
246 """
247 # Build flags based on available data
248 flags = GlucoseMeasurementFlags(0)
249 if data.time_offset_minutes is not None:
250 flags |= GlucoseMeasurementFlags.TIME_OFFSET_PRESENT
251 if data.unit == "mmol/L":
252 flags |= GlucoseMeasurementFlags.GLUCOSE_CONCENTRATION_UNITS_MMOL_L
253 if data.glucose_type is not None or data.sample_location is not None:
254 flags |= GlucoseMeasurementFlags.TYPE_SAMPLE_LOCATION_PRESENT
255 if data.sensor_status is not None:
256 flags |= GlucoseMeasurementFlags.SENSOR_STATUS_ANNUNCIATION_PRESENT
258 # Validate ranges
259 if not 0 <= data.sequence_number <= 0xFFFF:
260 raise ValueError(f"Sequence number {data.sequence_number} exceeds uint16 range")
262 # Start with flags, sequence number, and base time
263 result = bytearray([int(flags)])
264 result.extend(DataParser.encode_int16(data.sequence_number, signed=False))
265 result.extend(IEEE11073Parser.encode_timestamp(data.base_time))
267 # Add optional time offset
268 if data.time_offset_minutes is not None:
269 if not SINT16_MIN <= data.time_offset_minutes <= SINT16_MAX:
270 raise ValueError(f"Time offset {data.time_offset_minutes} exceeds sint16 range")
271 result.extend(DataParser.encode_int16(data.time_offset_minutes, signed=True))
273 # Add glucose concentration using IEEE-11073 SFLOAT
274 result.extend(IEEE11073Parser.encode_sfloat(data.glucose_concentration))
276 # Add optional type and sample location
277 if data.glucose_type is not None or data.sample_location is not None:
278 glucose_type = data.glucose_type or 0
279 sample_location = data.sample_location or 0
280 type_sample = BitFieldUtils.merge_bit_fields(
281 (
282 glucose_type,
283 GlucoseMeasurementBits.GLUCOSE_TYPE_START_BIT,
284 GlucoseMeasurementBits.GLUCOSE_TYPE_BIT_WIDTH,
285 ),
286 (
287 sample_location,
288 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_START_BIT,
289 GlucoseMeasurementBits.GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH,
290 ),
291 )
292 result.append(type_sample)
294 # Add optional sensor status
295 if data.sensor_status is not None:
296 if not 0 <= data.sensor_status <= 0xFFFF:
297 raise ValueError(f"Sensor status {data.sensor_status} exceeds uint16 range")
298 result.extend(DataParser.encode_int16(data.sensor_status, signed=False))
300 return result
302 def _validate_sensor_status_against_feature(self, sensor_status: int, feature_data: GlucoseFeatureData) -> None:
303 """Validate sensor status bits against supported Glucose Features.
305 Args:
306 sensor_status: Raw sensor status bitmask from measurement
307 feature_data: GlucoseFeatureData from Glucose Feature characteristic
309 Raises:
310 ValueError: If reported sensor status bits are not supported by device features
312 """
313 # Sensor status bits correspond to Glucose Feature bits
314 # Check each status bit against corresponding feature support
315 if (sensor_status & GlucoseFeatures.LOW_BATTERY_DETECTION) and not feature_data.low_battery_detection:
316 raise ValueError("Low battery status reported but not supported by Glucose Feature")
317 if (
318 sensor_status & GlucoseFeatures.SENSOR_MALFUNCTION_DETECTION
319 ) and not feature_data.sensor_malfunction_detection:
320 raise ValueError("Sensor malfunction status reported but not supported by Glucose Feature")
321 if (sensor_status & GlucoseFeatures.SENSOR_SAMPLE_SIZE) and not feature_data.sensor_sample_size:
322 raise ValueError("Sensor sample size status reported but not supported by Glucose Feature")
323 if (
324 sensor_status & GlucoseFeatures.SENSOR_STRIP_INSERTION_ERROR
325 ) and not feature_data.sensor_strip_insertion_error:
326 raise ValueError("Sensor strip insertion error status reported but not supported by Glucose Feature")
327 if (sensor_status & GlucoseFeatures.SENSOR_STRIP_TYPE_ERROR) and not feature_data.sensor_strip_type_error:
328 raise ValueError("Sensor strip type error status reported but not supported by Glucose Feature")
329 if (sensor_status & GlucoseFeatures.SENSOR_RESULT_HIGH_LOW) and not feature_data.sensor_result_high_low:
330 raise ValueError("Sensor result high-low status reported but not supported by Glucose Feature")
331 if (
332 sensor_status & GlucoseFeatures.SENSOR_TEMPERATURE_HIGH_LOW
333 ) and not feature_data.sensor_temperature_high_low:
334 raise ValueError("Sensor temperature high-low status reported but not supported by Glucose Feature")
335 if (sensor_status & GlucoseFeatures.SENSOR_READ_INTERRUPT) and not feature_data.sensor_read_interrupt:
336 raise ValueError("Sensor read interrupt status reported but not supported by Glucose Feature")
337 if (sensor_status & GlucoseFeatures.GENERAL_DEVICE_FAULT) and not feature_data.general_device_fault:
338 raise ValueError("General device fault status reported but not supported by Glucose Feature")
339 if (sensor_status & GlucoseFeatures.TIME_FAULT) and not feature_data.time_fault:
340 raise ValueError("Time fault status reported but not supported by Glucose Feature")
341 if (sensor_status & GlucoseFeatures.MULTIPLE_BOND_SUPPORT) and not feature_data.multiple_bond_support:
342 raise ValueError("Multiple bond status reported but not supported by Glucose Feature")