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

30 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-30 00:10 +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): 

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 # Bit masks for alert status flags 

33 RINGER_STATE_MASK = 0x01 # Bit 0 

34 VIBRATE_STATE_MASK = 0x02 # Bit 1 

35 DISPLAY_ALERT_STATUS_MASK = 0x04 # Bit 2 

36 

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

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

39 

40 Args: 

41 data: Raw bytearray from BLE characteristic. 

42 ctx: Optional CharacteristicContext (unused) 

43 

44 Returns: 

45 AlertStatusData containing parsed alert status flags. 

46 

47 Raises: 

48 ValueError: If data format is invalid. 

49 

50 """ 

51 if len(data) < 1: 

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

53 

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

55 

56 # Extract bit fields according to specification 

57 ringer_state = bool(status_byte & self.RINGER_STATE_MASK) 

58 vibrate_state = bool(status_byte & self.VIBRATE_STATE_MASK) 

59 display_alert_status = bool(status_byte & self.DISPLAY_ALERT_STATUS_MASK) 

60 

61 return AlertStatusData( 

62 ringer_state=ringer_state, 

63 vibrate_state=vibrate_state, 

64 display_alert_status=display_alert_status, 

65 ) 

66 

67 def encode_value(self, data: AlertStatusData) -> bytearray: 

68 """Encode AlertStatusData back to bytes. 

69 

70 Args: 

71 data: AlertStatusData instance to encode 

72 

73 Returns: 

74 Encoded bytes representing the alert status 

75 

76 """ 

77 status_byte = 0 

78 if data.ringer_state: 

79 status_byte |= self.RINGER_STATE_MASK 

80 if data.vibrate_state: 

81 status_byte |= self.VIBRATE_STATE_MASK 

82 if data.display_alert_status: 

83 status_byte |= self.DISPLAY_ALERT_STATUS_MASK 

84 

85 return bytearray([status_byte])