Coverage for src / bluetooth_sig / gatt / characteristics / alert_status.py: 52%

31 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-11 20:14 +0000

1"""Alert Status characteristic implementation.""" 

2 

3from __future__ import annotations 

4 

5import msgspec 

6 

7from ..context import CharacteristicContext 

8from .base import BaseCharacteristic 

9from .utils import DataParser 

10 

11 

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

13 """Parsed data from Alert Status characteristic.""" 

14 

15 ringer_state: bool 

16 vibrate_state: bool 

17 display_alert_status: bool 

18 

19 

20class AlertStatusCharacteristic(BaseCharacteristic[AlertStatusData]): 

21 """Alert Status characteristic (0x2A3F). 

22 

23 org.bluetooth.characteristic.alert_status 

24 

25 The Alert Status characteristic defines the Status of alert. 

26 Bit 0: Ringer State (0=not active, 1=active) 

27 Bit 1: Vibrate State (0=not active, 1=active) 

28 Bit 2: Display Alert Status (0=not active, 1=active) 

29 Bits 3-7: Reserved for future use 

30 """ 

31 

32 expected_length: int = 1 

33 

34 # Bit masks for alert status flags 

35 RINGER_STATE_MASK = 0x01 # Bit 0 

36 VIBRATE_STATE_MASK = 0x02 # Bit 1 

37 DISPLAY_ALERT_STATUS_MASK = 0x04 # Bit 2 

38 

39 def _decode_value(self, data: bytearray, ctx: CharacteristicContext | None = None) -> AlertStatusData: 

40 """Parse alert status data according to Bluetooth specification. 

41 

42 Args: 

43 data: Raw bytearray from BLE characteristic. 

44 ctx: Optional CharacteristicContext (unused) 

45 

46 Returns: 

47 AlertStatusData containing parsed alert status flags. 

48 

49 Raises: 

50 ValueError: If data format is invalid. 

51 

52 """ 

53 if len(data) < 1: 

54 raise ValueError("Alert Status data must be at least 1 byte") 

55 

56 status_byte = DataParser.parse_int8(data, 0, signed=False) 

57 

58 # Extract bit fields according to specification 

59 ringer_state = bool(status_byte & self.RINGER_STATE_MASK) 

60 vibrate_state = bool(status_byte & self.VIBRATE_STATE_MASK) 

61 display_alert_status = bool(status_byte & self.DISPLAY_ALERT_STATUS_MASK) 

62 

63 return AlertStatusData( 

64 ringer_state=ringer_state, 

65 vibrate_state=vibrate_state, 

66 display_alert_status=display_alert_status, 

67 ) 

68 

69 def _encode_value(self, data: AlertStatusData) -> bytearray: 

70 """Encode AlertStatusData back to bytes. 

71 

72 Args: 

73 data: AlertStatusData instance to encode 

74 

75 Returns: 

76 Encoded bytes representing the alert status 

77 

78 """ 

79 status_byte = 0 

80 if data.ringer_state: 

81 status_byte |= self.RINGER_STATE_MASK 

82 if data.vibrate_state: 

83 status_byte |= self.VIBRATE_STATE_MASK 

84 if data.display_alert_status: 

85 status_byte |= self.DISPLAY_ALERT_STATUS_MASK 

86 

87 return bytearray([status_byte])