Coverage for src/bluetooth_sig/gatt/characteristics/voltage_statistics.py: 88%

42 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-30 00:10 +0000

1"""Voltage Statistics characteristic implementation.""" 

2 

3from __future__ import annotations 

4 

5import msgspec 

6 

7from ...types.gatt_enums import ValueType 

8from ..constants import UINT16_MAX 

9from ..context import CharacteristicContext 

10from .base import BaseCharacteristic 

11 

12 

13class VoltageStatisticsData(msgspec.Struct, frozen=True, kw_only=True): # pylint: disable=too-few-public-methods 

14 """Data class for voltage statistics.""" 

15 

16 minimum: float # Minimum voltage in Volts 

17 maximum: float # Maximum voltage in Volts 

18 average: float # Average voltage in Volts 

19 

20 def __post_init__(self) -> None: 

21 """Validate voltage statistics data.""" 

22 # Validate logical order 

23 if self.minimum > self.maximum: 

24 raise ValueError(f"Minimum voltage {self.minimum} V cannot be greater than maximum {self.maximum} V") 

25 if not self.minimum <= self.average <= self.maximum: 

26 raise ValueError( 

27 f"Average voltage {self.average} V must be between " 

28 f"minimum {self.minimum} V and maximum {self.maximum} V" 

29 ) 

30 

31 # Validate range for uint16 with 1/64 V resolution (0 to ~1024 V) 

32 max_voltage_value = UINT16_MAX / 64.0 # ~1024 V 

33 for name, voltage in [ 

34 ("minimum", self.minimum), 

35 ("maximum", self.maximum), 

36 ("average", self.average), 

37 ]: 

38 if not 0.0 <= voltage <= max_voltage_value: 

39 raise ValueError( 

40 f"{name.capitalize()} voltage {voltage} V is outside valid range (0.0 to {max_voltage_value:.2f} V)" 

41 ) 

42 

43 

44class VoltageStatisticsCharacteristic(BaseCharacteristic): 

45 """Voltage Statistics characteristic (0x2B1A). 

46 

47 org.bluetooth.characteristic.voltage_statistics 

48 

49 Voltage Statistics characteristic. 

50 

51 Provides statistical voltage data over time. 

52 """ 

53 

54 # Override since decode_value returns structured VoltageStatisticsData 

55 _manual_value_type: ValueType | str | None = ValueType.DICT 

56 

57 def decode_value(self, data: bytearray, ctx: CharacteristicContext | None = None) -> VoltageStatisticsData: 

58 """Parse voltage statistics data (3x uint16 in units of 1/64 V). 

59 

60 Args: 

61 data: Raw bytes from the characteristic read. 

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

63 

64 Returns: 

65 VoltageStatisticsData with 'minimum', 'maximum', and 'average' voltage values in Volts. 

66 

67 # `ctx` is intentionally unused for this characteristic; mark as used for linters. 

68 del ctx 

69 Raises: 

70 ValueError: If data is insufficient. 

71 

72 """ 

73 if len(data) < 6: 

74 raise ValueError("Voltage statistics data must be at least 6 bytes") 

75 

76 # Convert 3x uint16 (little endian) to voltage statistics in Volts 

77 min_voltage_raw = int.from_bytes(data[:2], byteorder="little", signed=False) 

78 max_voltage_raw = int.from_bytes(data[2:4], byteorder="little", signed=False) 

79 avg_voltage_raw = int.from_bytes(data[4:6], byteorder="little", signed=False) 

80 

81 return VoltageStatisticsData( 

82 minimum=min_voltage_raw / 64.0, 

83 maximum=max_voltage_raw / 64.0, 

84 average=avg_voltage_raw / 64.0, 

85 ) 

86 

87 def encode_value(self, data: VoltageStatisticsData) -> bytearray: 

88 """Encode voltage statistics value back to bytes. 

89 

90 Args: 

91 data: VoltageStatisticsData instance with 'minimum', 'maximum', and 'average' voltage values in Volts 

92 

93 Returns: 

94 Encoded bytes representing the voltage statistics (3x uint16, 1/64 V resolution) 

95 

96 """ 

97 if not isinstance(data, VoltageStatisticsData): 

98 raise TypeError(f"Voltage statistics data must be a VoltageStatisticsData, got {type(data).__name__}") 

99 

100 # Convert Volts to raw values (multiply by 64 for 1/64 V resolution) 

101 min_voltage_raw = round(data.minimum * 64) 

102 max_voltage_raw = round(data.maximum * 64) 

103 avg_voltage_raw = round(data.average * 64) 

104 

105 # Validate range for uint16 (0 to UINT16_MAX) 

106 # pylint: disable=duplicate-code 

107 # NOTE: This uint16 validation and encoding pattern is shared with VoltageSpecificationCharacteristic. 

108 # Both characteristics encode voltage values using the same 1/64V resolution and uint16 little-endian format 

109 # per Bluetooth SIG spec. Consolidation not practical as each has different field structures (2 vs 3 values). 

110 for name, value in [ 

111 ("minimum", min_voltage_raw), 

112 ("maximum", max_voltage_raw), 

113 ("average", avg_voltage_raw), 

114 ]: 

115 if not 0 <= value <= UINT16_MAX: 

116 raise ValueError(f"Voltage {name} value {value} exceeds uint16 range") 

117 

118 # Encode as 3 uint16 values (little endian) 

119 result = bytearray() 

120 result.extend(min_voltage_raw.to_bytes(2, byteorder="little", signed=False)) 

121 result.extend(max_voltage_raw.to_bytes(2, byteorder="little", signed=False)) 

122 result.extend(avg_voltage_raw.to_bytes(2, byteorder="little", signed=False)) 

123 

124 return result