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

41 statements  

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

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

2 

3from __future__ import annotations 

4 

5import msgspec 

6 

7from ..constants import UINT16_MAX 

8from ..context import CharacteristicContext 

9from .base import BaseCharacteristic 

10from .utils import DataParser 

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[VoltageStatisticsData]): 

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 expected_length: int = 6 # Minimum(2) + Maximum(2) + Average(2) 

55 min_length: int = 6 

56 

57 def _decode_value( 

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

59 ) -> VoltageStatisticsData: 

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

61 

62 Args: 

63 data: Raw bytes from the characteristic read. 

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

65 validate: Whether to validate ranges (default True) 

66 

67 Returns: 

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

69 

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

71 del ctx 

72 Raises: 

73 ValueError: If data is insufficient. 

74 

75 """ 

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

77 min_voltage_raw = DataParser.parse_int16(data, 0, signed=False) 

78 max_voltage_raw = DataParser.parse_int16(data, 2, signed=False) 

79 avg_voltage_raw = DataParser.parse_int16(data, 4, 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(DataParser.encode_int16(min_voltage_raw, signed=False)) 

121 result.extend(DataParser.encode_int16(max_voltage_raw, signed=False)) 

122 result.extend(DataParser.encode_int16(avg_voltage_raw, signed=False)) 

123 

124 return result