CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygatt

Python Bluetooth LE (Low Energy) and GATT Library providing cross-platform BLE operations with multiple backends

Pending
Overview
Eval results
Files

backend-management.mddocs/

Backend Management

Core backend lifecycle and configuration operations for initializing and managing BLE adapters. The BLEBackend class provides the abstract interface that both BGAPI and GATTTool backends implement.

Capabilities

Backend Lifecycle

Initialize and manage backend resources including USB connections, CLI processes, and cleanup operations.

def start(self):
    """
    Initialize and start the backend resources.
    
    For BGAPI: Opens serial connection to USB adapter
    For GATTTool: Starts gatttool subprocess and initializes CLI
    
    Raises:
        BGAPIError: BGAPI backend initialization failed
        BLEError: General backend startup failure
    """

def stop(self):
    """
    Stop and free all backend resources.
    
    Disconnects all active connections and cleans up background processes.
    Must be called to prevent resource leaks.
    """

def supports_unbonded(self) -> bool:
    """
    Check if backend supports unbonded (unauthenticated) communication.
    
    Returns:
        bool: True if unbonded communication supported
    """

Device Connection

Connect to BLE devices using MAC addresses with configurable connection parameters and address types.

def connect(self, address: str, timeout: float = 5.0, **kwargs) -> BLEDevice:
    """
    Connect to a BLE device by MAC address.
    
    Args:
        address: BLE MAC address (e.g., '01:23:45:67:89:ab')
        timeout: Connection timeout in seconds (default: 5.0)
        address_type: BLEAddressType.public or BLEAddressType.random
        **kwargs: Backend-specific connection parameters
    
    Returns:
        BLEDevice: Connected device instance
    
    Raises:
        NotConnectedError: Connection failed
        BLEError: General connection error
    """

Usage Example:

import pygatt

adapter = pygatt.BGAPIBackend()
adapter.start()

# Connect with random address type
device = adapter.connect('01:23:45:67:89:ab', 
                        address_type=pygatt.BLEAddressType.random,
                        timeout=10.0)

# BGAPI-specific connection parameters
device = adapter.connect('01:23:45:67:89:ab',
                        interval_min=60,
                        interval_max=76,
                        supervision_timeout=100,
                        latency=0)

Device Scanning

Discover nearby BLE devices with configurable scan parameters and filtering options.

def scan(self, *args, **kwargs) -> list:
    """
    Perform BLE device scan to discover nearby devices.
    
    Args:
        timeout: Scan duration in seconds
        **kwargs: Backend-specific scan parameters
    
    Returns:
        list: List of discovered device dictionaries containing:
            - 'address': Device MAC address
            - 'name': Device name (may be None)
            - 'rssi': Signal strength
    
    Raises:
        BLEError: Scan operation failed
    """

def filtered_scan(self, name_filter: str = "", *args, **kwargs) -> list:
    """
    Scan for BLE devices and filter by device name.
    
    Args:
        name_filter: String that must be contained in device name
        **kwargs: Same as scan() method
    
    Returns:
        list: Filtered list of devices matching name filter
    """

Usage Example:

import pygatt

adapter = pygatt.GATTToolBackend()
adapter.start()

# Basic scan
devices = adapter.scan(timeout=10)
for device in devices:
    print(f"Found: {device['address']} - {device['name']} (RSSI: {device['rssi']})")

# Filtered scan for specific device types
fitness_trackers = adapter.filtered_scan("Fitbit", timeout=10)

Bond Management

Manage stored device bonds and pairing information for encrypted connections.

def clear_bond(self, address: str = None):
    """
    Clear stored bonding information for a device or all devices.
    
    Args:
        address: Specific device MAC address to unbond, or None for all devices
    
    Note:
        BGAPI: Clears bonds from adapter's internal storage
        GATTTool: Uses bluetoothctl to remove system-level bonds
    """

Usage Example:

# Clear bond for specific device
adapter.clear_bond('01:23:45:67:89:ab')

# Clear all bonds
adapter.clear_bond()

Backend Selection

BGAPI Backend

Best for cross-platform development and applications requiring:

  • Windows/macOS/Linux compatibility
  • USB dongle deployment
  • Stable, predictable behavior
  • Advanced BGAPI protocol features
adapter = pygatt.BGAPIBackend()

GATTTool Backend

Best for Linux-based applications requiring:

  • Native BlueZ integration
  • System-level Bluetooth management
  • Development/debugging capabilities
  • No additional hardware requirements
adapter = pygatt.GATTToolBackend()

Error Handling

Common backend management errors and their typical causes:

  • BGAPIError: USB device not found, driver issues, permissions
  • BLEError: Bluetooth adapter not available, system configuration
  • NotConnectedError: Device out of range, address type mismatch, device busy

Install with Tessl CLI

npx tessl i tessl/pypi-pygatt

docs

backend-management.md

bgapi-backend.md

device-operations.md

error-handling.md

gatttool-backend.md

index.md

utilities.md

tile.json