GATT Layer API Reference¶
The GATT layer provides the fundamental building blocks for Bluetooth characteristic parsing.
Overview¶
The GATT layer consists of:
- Characteristic parsers - 70+ implementations for standard characteristics
- Service definitions - Organize characteristics into services
- Validation logic - Ensure data integrity
- Exception types - Clear error reporting
Base Classes¶
BaseCharacteristic¶
Bases: ABC
Base class for all GATT characteristics.
Automatically resolves UUID, unit, and value_type from Bluetooth SIG YAML specifications. Supports manual overrides via _manual_unit and _manual_value_type attributes.
Note: This class intentionally has >20 public methods as it provides the complete characteristic API including parsing, validation, UUID resolution, registry interaction, and metadata access. The methods are well-organized by functionality.
Validation Attributes (optional class-level declarations): min_value: Minimum allowed value for parsed data max_value: Maximum allowed value for parsed data expected_length: Exact expected data length in bytes min_length: Minimum required data length in bytes max_length: Maximum allowed data length in bytes allow_variable_length: Whether variable length data is acceptable expected_type: Expected Python type for parsed values
Example usage in subclasses
class ExampleCharacteristic(BaseCharacteristic): '''Example showing validation attributes usage.'''
# Declare validation constraints as class attributes
expected_length = 2
min_value = 0
max_value = 65535 # UINT16_MAX
expected_type = int
def decode_value(self, data: bytearray) -> int:
# Just parse - validation happens automatically in parse_value
return DataParser.parse_int16(data, 0, signed=False)
Before: BatteryLevelCharacteristic with hardcoded validation¶
class BatteryLevelCharacteristic(BaseCharacteristic):¶
def decode_value(self, data: bytearray) -> int:¶
if not data:¶
raise ValueError("Battery level data must be at least 1 byte")¶
level = data[0]¶
if not 0 <= level <= PERCENTAGE_MAX:¶
raise ValueError(f"Battery level must be 0-100, got {level}")¶
return level¶
After: BatteryLevelCharacteristic with declarative validation¶
class BatteryLevelCharacteristic(BaseCharacteristic):¶
expected_length = 1¶
min_value = 0¶
max_value = 100 # PERCENTAGE_MAX¶
expected_type = int¶
¶
def decode_value(self, data: bytearray) -> int:¶
return data[0] # Validation happens automatically¶
Initialize characteristic with structured configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info
|
CharacteristicInfo | None
|
Complete characteristic information (optional for SIG characteristics) |
None
|
validation
|
ValidationConfig | None
|
Validation constraints configuration (optional) |
None
|
Source code in src/bluetooth_sig/gatt/characteristics/base.py
decode_value
¶
Parse the characteristic's raw value.
If _template is set, uses the template's decode_value method. Otherwise, subclasses must override this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytearray
|
Raw bytes from the characteristic read |
required |
ctx
|
CharacteristicContext | None
|
Optional context information for parsing |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Parsed value in the appropriate type |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If no template is set and subclass doesn't override |
Source code in src/bluetooth_sig/gatt/characteristics/base.py
encode_value
¶
Encode the characteristic's value to raw bytes.
If _template is set , uses the template's encode_value method. Otherwise, subclasses must override this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Dataclass instance or value to encode |
required |
Returns:
| Type | Description |
|---|---|
bytearray
|
Encoded bytes for characteristic write |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is invalid for encoding |
NotImplementedError
|
If no template is set and subclass doesn't override |
Source code in src/bluetooth_sig/gatt/characteristics/base.py
All characteristic implementations inherit from BaseCharacteristic.
BaseService¶
Base class for all GATT services.
Automatically resolves UUID, name, and summary from Bluetooth SIG specifications. Follows the same pattern as BaseCharacteristic for consistency.
Initialize service with structured configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
info
|
ServiceInfo | None
|
Complete service information (optional for SIG services) |
None
|
validation
|
ServiceValidationConfig | None
|
Validation constraints configuration (optional) |
None
|
Source code in src/bluetooth_sig/gatt/services/base.py
info
property
¶
info: ServiceInfo
Return the resolved service information for this instance.
The info property provides all metadata about the service, including UUID, name, and description.
supported_characteristics
property
¶
Get the set of characteristic UUIDs supported by this service.
__post_init__
¶
Initialize service with resolved information.
Source code in src/bluetooth_sig/gatt/services/base.py
get_characteristic
¶
Get a characteristic by UUID.
get_characteristic_status
¶
get_characteristic_status(characteristic_name: CharacteristicName) -> ServiceCharacteristicInfo | None
Get detailed status of a specific characteristic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
characteristic_name
|
CharacteristicName
|
CharacteristicName enum |
required |
Returns:
| Type | Description |
|---|---|
ServiceCharacteristicInfo | None
|
CharacteristicInfo if characteristic is expected by this service, None otherwise |
Source code in src/bluetooth_sig/gatt/services/base.py
get_characteristics_schema
classmethod
¶
Get the TypedDict schema for this service's characteristics.
Override this method to provide strong typing for characteristics. If not implemented, falls back to get_expected_characteristics().
Returns:
| Type | Description |
|---|---|
type | None
|
TypedDict class defining the service's characteristics, or None |
Source code in src/bluetooth_sig/gatt/services/base.py
get_class_uuid
classmethod
¶
Get the UUID for this service class without instantiation.
Returns:
| Type | Description |
|---|---|
BluetoothUUID
|
BluetoothUUID for this service class |
Raises:
| Type | Description |
|---|---|
UUIDResolutionError
|
If UUID cannot be resolved |
Source code in src/bluetooth_sig/gatt/services/base.py
get_conditional_characteristics
classmethod
¶
Get characteristics that are required only under certain conditions.
Returns:
| Type | Description |
|---|---|
ServiceCharacteristicCollection
|
ServiceCharacteristicCollection mapping characteristic name to CharacteristicSpec |
Override in subclasses to specify conditional characteristics.
Source code in src/bluetooth_sig/gatt/services/base.py
get_expected_characteristic_uuids
¶
Get the set of expected characteristic UUIDs for this service.
Source code in src/bluetooth_sig/gatt/services/base.py
get_expected_characteristics
classmethod
¶
Get the expected characteristics for this service from the service_characteristics dict.
Looks for a 'service_characteristics' class attribute containing a dictionary of CharacteristicName -> required flag, and automatically builds CharacteristicSpec objects.
Returns:
| Type | Description |
|---|---|
ServiceCharacteristicCollection
|
ServiceCharacteristicCollection mapping characteristic name to CharacteristicSpec |
Source code in src/bluetooth_sig/gatt/services/base.py
get_missing_characteristics
¶
Get detailed information about missing characteristics.
Returns:
| Type | Description |
|---|---|
dict[CharacteristicName, ServiceCharacteristicInfo]
|
Dict mapping characteristic name to ServiceCharacteristicInfo |
Source code in src/bluetooth_sig/gatt/services/base.py
get_optional_characteristics
classmethod
¶
Get the optional characteristics for this service by name and class.
Returns:
| Type | Description |
|---|---|
ServiceCharacteristicCollection
|
ServiceCharacteristicCollection mapping characteristic name to CharacteristicSpec |
Source code in src/bluetooth_sig/gatt/services/base.py
get_required_characteristic_keys
classmethod
¶
Get the set of required characteristic keys from the schema.
Override this method when using strongly-typed characteristics. If not implemented, falls back to get_required_characteristics().keys().
Returns:
| Type | Description |
|---|---|
set[CharacteristicName]
|
Set of required characteristic field names |
Source code in src/bluetooth_sig/gatt/services/base.py
get_required_characteristic_uuids
¶
Get the set of required characteristic UUIDs for this service.
Source code in src/bluetooth_sig/gatt/services/base.py
get_required_characteristics
classmethod
¶
Get the required characteristics for this service from the characteristics dict.
Automatically filters the characteristics dictionary for required=True entries.
Returns:
| Type | Description |
|---|---|
ServiceCharacteristicCollection
|
ServiceCharacteristicCollection mapping characteristic name to CharacteristicSpec |
Source code in src/bluetooth_sig/gatt/services/base.py
get_service_completeness_report
¶
Get a comprehensive report about service completeness.
Returns:
| Type | Description |
|---|---|
ServiceCompletenessReport
|
ServiceCompletenessReport with detailed service status information |
Source code in src/bluetooth_sig/gatt/services/base.py
has_minimum_functionality
¶
Check if service has minimum required functionality.
Returns:
| Type | Description |
|---|---|
bool
|
True if service has all required characteristics and is usable |
Source code in src/bluetooth_sig/gatt/services/base.py
matches_uuid
classmethod
¶
Check if this service matches the given UUID.
Source code in src/bluetooth_sig/gatt/services/base.py
process_characteristics
¶
Process the characteristics for this service (default implementation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
characteristics
|
ServiceDiscoveryData
|
Dict mapping UUID to characteristic info |
required |
Source code in src/bluetooth_sig/gatt/services/base.py
validate_bluetooth_sig_compliance
classmethod
¶
Validate compliance with Bluetooth SIG service specification.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of compliance issues found |
Override in subclasses to provide service-specific validation.
Source code in src/bluetooth_sig/gatt/services/base.py
validate_service
¶
Validate the completeness and health of this service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strict
|
bool
|
If True, missing optional characteristics are treated as warnings |
False
|
Returns:
| Type | Description |
|---|---|
ServiceValidationResult
|
ServiceValidationResult with detailed status information |
Source code in src/bluetooth_sig/gatt/services/base.py
All service definitions inherit from BaseGattService.
Registries¶
CharacteristicRegistry¶
Encapsulates all GATT characteristic registry operations.
Use CharacteristicRegistry to register custom characteristics.
GattServiceRegistry¶
Registry for all supported GATT services.
Use GattServiceRegistry to register custom services.
Common Characteristic Examples¶
Battery Level¶
from bluetooth_sig.gatt.characteristics import BatteryLevelCharacteristic
char = BatteryLevelCharacteristic()
value = char.decode_value(bytearray([85]))
print(f"Battery: {value}%") # Battery: 85%
Temperature¶
from bluetooth_sig.gatt.characteristics import TemperatureCharacteristic
char = TemperatureCharacteristic()
value = char.decode_value(bytearray([0x64, 0x09]))
print(f"Temperature: {value}°C") # Temperature: 24.36°C
Humidity¶
from bluetooth_sig.gatt.characteristics import HumidityCharacteristic
char = HumidityCharacteristic()
value = char.decode_value(bytearray([0x3A, 0x13]))
print(f"Humidity: {value}%") # Humidity: 49.42%
Exceptions¶
InsufficientDataError¶
Raised when data is too short for the characteristic.
from bluetooth_sig.gatt.exceptions import InsufficientDataError
try:
char.decode_value(bytearray([])) # Empty
except InsufficientDataError as e:
print(f"Error: {e}")
ValueRangeError¶
Raised when value is outside valid range.
from bluetooth_sig.gatt.exceptions import ValueRangeError
try:
char.decode_value(bytearray([150])) # > 100%
except ValueRangeError as e:
print(f"Error: {e}")
See Also¶
- Core API - High-level
BluetoothSIGTranslatorAPI - Supported Characteristics - Full list
- Architecture - Design details
- Adding Characteristics - Custom implementations