Coverage for src / bluetooth_sig / gatt / characteristics / glucose_measurement.py: 80%

160 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-18 11:17 +0000

1"""Glucose Measurement characteristic implementation.""" 

2 

3from __future__ import annotations 

4 

5from datetime import datetime 

6from enum import IntEnum, IntFlag 

7from typing import Any, ClassVar 

8 

9import msgspec 

10 

11from ..constants import SINT16_MAX, SINT16_MIN, UINT16_MAX 

12from ..context import CharacteristicContext 

13from .base import BaseCharacteristic 

14from .glucose_feature import GlucoseFeatureCharacteristic, GlucoseFeatureData, GlucoseFeatures 

15from .utils import BitFieldUtils, DataParser, IEEE11073Parser 

16 

17 

18class GlucoseMeasurementBits: 

19 """Glucose measurement bit field constants.""" 

20 

21 # pylint: disable=missing-class-docstring,too-few-public-methods 

22 

23 # Glucose Measurement bit field constants 

24 GLUCOSE_TYPE_SAMPLE_MASK = 0x0F # 4-bit mask for type and sample location 

25 GLUCOSE_TYPE_START_BIT = 4 # Glucose type in high 4 bits 

26 GLUCOSE_TYPE_BIT_WIDTH = 4 

27 GLUCOSE_SAMPLE_LOCATION_START_BIT = 0 # Sample location in low 4 bits 

28 GLUCOSE_SAMPLE_LOCATION_BIT_WIDTH = 4 

29 

30 

31class GlucoseType(IntEnum): 

32 """Glucose sample type enumeration as per Bluetooth SIG specification.""" 

33 

34 CAPILLARY_WHOLE_BLOOD = 1 

35 CAPILLARY_PLASMA = 2 

36 VENOUS_WHOLE_BLOOD = 3 

37 VENOUS_PLASMA = 4 

38 ARTERIAL_WHOLE_BLOOD = 5 

39 ARTERIAL_PLASMA = 6 

40 UNDETERMINED_WHOLE_BLOOD = 7 

41 UNDETERMINED_PLASMA = 8 

42 INTERSTITIAL_FLUID = 9 

43 CONTROL_SOLUTION = 10 

44 # Values 11-15 (0xB-0xF) are Reserved for Future Use 

45 

46 def __str__(self) -> str: 

47 """Return human-readable glucose type name.""" 

48 names = { 

49 self.CAPILLARY_WHOLE_BLOOD: "Capillary Whole blood", 

50 self.CAPILLARY_PLASMA: "Capillary Plasma", 

51 self.VENOUS_WHOLE_BLOOD: "Venous Whole blood", 

52 self.VENOUS_PLASMA: "Venous Plasma", 

53 self.ARTERIAL_WHOLE_BLOOD: "Arterial Whole blood", 

54 self.ARTERIAL_PLASMA: "Arterial Plasma", 

55 self.UNDETERMINED_WHOLE_BLOOD: "Undetermined Whole blood", 

56 self.UNDETERMINED_PLASMA: "Undetermined Plasma", 

57 self.INTERSTITIAL_FLUID: "Interstitial Fluid (ISF)", 

58 self.CONTROL_SOLUTION: "Control Solution", 

59 } 

60 return names[self] 

61 

62 

63class SampleLocation(IntEnum): 

64 """Sample location enumeration as per Bluetooth SIG specification.""" 

65 

66 # Value 0 is Reserved for Future Use 

67 FINGER = 1 

68 ALTERNATE_SITE_TEST = 2 

69 EARLOBE = 3 

70 CONTROL_SOLUTION = 4 

71 # Values 5-14 (0x5-0xE) are Reserved for Future Use 

72 NOT_AVAILABLE = 15 

73 

74 def __str__(self) -> str: 

75 """Return human-readable sample location name.""" 

76 names = { 

77 self.FINGER: "Finger", 

78 self.ALTERNATE_SITE_TEST: "Alternate Site Test (AST)", 

79 self.EARLOBE: "Earlobe", 

80 self.CONTROL_SOLUTION: "Control solution", 

81 self.NOT_AVAILABLE: "Sample Location value not available", 

82 } 

83 return names[self] 

84 

85 

86class GlucoseMeasurementFlags(IntFlag): 

87 """Glucose Measurement flags as per Bluetooth SIG specification.""" 

88 

89 TIME_OFFSET_PRESENT = 0x01 

90 GLUCOSE_CONCENTRATION_UNITS_MMOL_L = 0x02 

91 TYPE_SAMPLE_LOCATION_PRESENT = 0x04 

92 SENSOR_STATUS_ANNUNCIATION_PRESENT = 0x08 

93 

94 

95class GlucoseMeasurementData(msgspec.Struct, frozen=True, kw_only=True): # pylint: disable=too-few-public-methods,too-many-instance-attributes 

96 """Parsed glucose measurement data.""" 

97 

98 sequence_number: int 

99 base_time: datetime 

100 glucose_concentration: float 

101 unit: str 

102 flags: GlucoseMeasurementFlags 

103 time_offset_minutes: int | None = None 

104 glucose_type: GlucoseType | None = None 

105 sample_location: SampleLocation | None = None 

106 sensor_status: int | None = None 

107 

108 min_length: int = 12 # Aligned with GlucoseMeasurementCharacteristic 

109 max_length: int = 17 # Aligned with GlucoseMeasurementCharacteristic 

110 

111 def __post_init__(self) -> None: 

112 """Validate glucose measurement data.""" 

113 if self.unit not in ("mg/dL", "mmol/L"): 

114 raise ValueError(f"Glucose unit must be 'mg/dL' or 'mmol/L', got {self.unit}") 

115 

116 # Validate concentration range based on unit 

117 if self.unit == "mg/dL": 

118 # Allow any non-negative value (no SIG-specified range) 

119 if self.glucose_concentration < 0: 

120 raise ValueError(f"Glucose concentration must be non-negative, got {self.glucose_concentration}") 

121 # Allow any non-negative value (no SIG-specified range) 

122 elif self.glucose_concentration < 0: 

123 raise ValueError(f"Glucose concentration must be non-negative, got {self.glucose_concentration}") 

124 

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} 

129 

130 

131class GlucoseMeasurementCharacteristic(BaseCharacteristic[GlucoseMeasurementData]): 

132 """Glucose Measurement characteristic (0x2A18). 

133 

134 Used to transmit glucose concentration measurements with timestamps 

135 and status. Core characteristic for glucose monitoring devices. 

136 """ 

137 

138 _manual_unit: str = "mg/dL or mmol/L" # Unit depends on flags 

139 

140 _optional_dependencies: ClassVar[list[type[BaseCharacteristic[Any]]]] = [GlucoseFeatureCharacteristic] 

141 

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 

145 

146 def _decode_value( # pylint: disable=too-many-locals # Glucose spec with many optional fields 

147 self, data: bytearray, ctx: CharacteristicContext | None = None, *, validate: bool = True 

148 ) -> GlucoseMeasurementData: 

149 """Parse glucose measurement data according to Bluetooth specification. 

150 

151 Format: Flags(1) + Sequence Number(2) + Base Time(7) + [Time Offset(2)] + 

152 Glucose Concentration(2) + [Type-Sample Location(1)] + [Sensor Status(2)]. 

153 

154 Args: 

155 data: Raw bytearray from BLE characteristic. 

156 ctx: Optional CharacteristicContext providing surrounding context (may be None). 

157 validate: Whether to validate ranges (default True) 

158 

159 Returns: 

160 GlucoseMeasurementData containing parsed glucose measurement data with metadata. 

161 

162 Raises: 

163 ValueError: If data format is invalid. 

164 

165 """ 

166 flags = GlucoseMeasurementFlags(data[0]) 

167 offset = 1 

168 

169 # Parse sequence number (2 bytes) 

170 sequence_number = DataParser.parse_int16(data, offset, signed=False) 

171 offset += 2 

172 

173 # Parse base time (7 bytes) - IEEE-11073 timestamp 

174 base_time = IEEE11073Parser.parse_timestamp(data, offset) 

175 offset += 7 

176 

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 

182 

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 

191 

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 ) 

207 

208 glucose_type = GlucoseType(glucose_type_val) 

209 sample_location = SampleLocation(sample_location_val) 

210 

211 offset += 1 

212 

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) 

217 

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) 

223 

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 ) 

236 

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. 

239 

240 Args: 

241 data: GlucoseMeasurementData containing glucose measurement data 

242 

243 Returns: 

244 Encoded bytes representing the glucose measurement 

245 

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 

257 

258 # Validate ranges 

259 if not 0 <= data.sequence_number <= UINT16_MAX: 

260 raise ValueError(f"Sequence number {data.sequence_number} exceeds uint16 range") 

261 

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)) 

266 

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)) 

272 

273 # Add glucose concentration using IEEE-11073 SFLOAT 

274 result.extend(IEEE11073Parser.encode_sfloat(data.glucose_concentration)) 

275 

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) 

293 

294 # Add optional sensor status 

295 if data.sensor_status is not None: 

296 if not 0 <= data.sensor_status <= UINT16_MAX: 

297 raise ValueError(f"Sensor status {data.sensor_status} exceeds uint16 range") 

298 result.extend(DataParser.encode_int16(data.sensor_status, signed=False)) 

299 

300 return result 

301 

302 def _validate_sensor_status_against_feature(self, sensor_status: int, feature_data: GlucoseFeatureData) -> None: 

303 """Validate sensor status bits against supported Glucose Features. 

304 

305 Args: 

306 sensor_status: Raw sensor status bitmask from measurement 

307 feature_data: GlucoseFeatureData from Glucose Feature characteristic 

308 

309 Raises: 

310 ValueError: If reported sensor status bits are not supported by device features 

311 

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")