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

bgapi-backend.mddocs/

BGAPI Backend

BGAPI-specific backend implementation for USB dongles with advanced configuration options and low-level protocol access. The BGAPIBackend provides cross-platform BLE connectivity using Bluegiga/Silicon Labs USB adapters like the BLED112.

Capabilities

Initialization and Configuration

Initialize BGAPI backend with USB serial port configuration and communication parameters.

def __init__(self, serial_port: str = None, receive_queue_timeout: float = 0.1):
    """
    Initialize BGAPI backend.
    
    Args:
        serial_port: Specific COM port (Windows) or device path (Linux/macOS)
                    None for auto-discovery
        receive_queue_timeout: Internal queue timeout in seconds
    """

def start(self, reset: bool = True, delay_after_reset_s: float = 1):
    """
    Start BGAPI backend with optional device reset.
    
    Args:
        reset: Reset USB adapter on startup (recommended)
        delay_after_reset_s: Wait time after reset before operations
    
    Raises:
        BGAPIError: USB device not found or initialization failed
    """

Usage Example:

import pygatt

# Auto-discover USB adapter
adapter = pygatt.BGAPIBackend()

# Specify COM port (Windows)
adapter = pygatt.BGAPIBackend(serial_port='COM9')

# Specify device path (Linux)
adapter = pygatt.BGAPIBackend(serial_port='/dev/ttyACM0')

# Start with custom reset timing
adapter.start(reset=True, delay_after_reset_s=2.0)

Device Information

Retrieve adapter hardware information and configuration status.

def get_mac(self) -> str:
    """
    Get the MAC address of the BGAPI adapter.
    
    Returns:
        str: Adapter MAC address in format 'XX:XX:XX:XX:XX:XX'
    
    Raises:
        BGAPIError: Failed to retrieve MAC address
    """

Usage Example:

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

mac = adapter.get_mac()
print(f"Adapter MAC: {mac}")

Advanced Scanning

Configure detailed scan parameters for optimized device discovery with active/passive scanning modes.

def scan(self, timeout: int = 10, scan_interval: int = 75, scan_window: int = 50, 
         active: bool = True, discover_mode=None, scan_cb=None, **kwargs) -> list:
    """
    Perform BLE scan with advanced BGAPI parameters.
    
    Args:
        timeout: Scan duration in seconds
        scan_interval: Time between scan starts (0.625ms units, range: 4-16384)
        scan_window: Scan duration per interval (0.625ms units, ≤ scan_interval)
        active: Active scanning (requests scan response) vs passive
        discover_mode: GAP discovery mode (limited, general, observation)
        scan_cb: Optional callback for real-time scan results
                callback(address, name, rssi, advertisement_data)
    
    Returns:
        list: Discovered devices with extended advertisement data
    
    Raises:
        BGAPIError: Scan configuration or execution failed
    """

Usage Example:

import pygatt

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

# High-frequency active scan
devices = adapter.scan(timeout=15, 
                      scan_interval=50,  # 31.25ms
                      scan_window=25,    # 15.625ms
                      active=True)

# Real-time scan callback
def scan_callback(address, name, rssi, ad_data):
    print(f"Found: {address} ({name}) RSSI: {rssi}")

adapter.scan(timeout=10, scan_cb=scan_callback)

Advanced Connection

Establish connections with precise connection interval and timing parameters.

def connect(self, address: str, timeout: int = 5, address_type=BLEAddressType.public,
           interval_min: int = 60, interval_max: int = 76, 
           supervision_timeout: int = 100, latency: int = 0) -> BGAPIBLEDevice:
    """
    Connect to device with advanced BGAPI connection parameters.
    
    Args:
        address: Device MAC address
        timeout: Connection timeout in seconds
        address_type: BLEAddressType.public or BLEAddressType.random
        interval_min: Minimum connection interval (1.25ms units, range: 6-3200)
        interval_max: Maximum connection interval (1.25ms units, range: 6-3200)
        supervision_timeout: Connection supervision timeout (10ms units, range: 10-3200)
        latency: Slave latency (number of intervals, range: 0-500)
    
    Returns:
        BGAPIBLEDevice: Connected device with BGAPI-specific features
    
    Raises:
        BGAPIError: Connection failed
        NotConnectedError: Device unreachable
    """

Usage Example:

# Low-latency connection for real-time applications
device = adapter.connect('01:23:45:67:89:ab',
                        interval_min=6,     # 7.5ms
                        interval_max=12,    # 15ms
                        supervision_timeout=100,  # 1s
                        latency=0)

# Power-optimized connection
device = adapter.connect('01:23:45:67:89:ab',
                        interval_min=80,    # 100ms
                        interval_max=120,   # 150ms
                        supervision_timeout=400,  # 4s
                        latency=4)

Characteristic Discovery

Perform comprehensive GATT service and characteristic discovery with detailed attribute information.

def discover_characteristics(self, connection_handle: int, timeout: int = 30) -> dict:
    """
    Discover all GATT characteristics on connected device.
    
    Args:
        connection_handle: BGAPI connection handle (internal)
        timeout: Discovery timeout in seconds
    
    Returns:
        dict: Complete characteristic mapping with descriptors
            {UUID: Characteristic(uuid, handle, descriptors)}
    
    Raises:
        BGAPIError: Discovery failed or timed out
    """

Bonding Configuration

Configure device bonding behavior and security settings.

def set_bondable(self, bondable: bool):
    """
    Enable or disable bonding mode on the adapter.
    
    Args:
        bondable: True to allow bonding, False to disable
    
    Note:
        Must be called before connecting to devices that require bonding
    """

def clear_bond(self, address: str = None):
    """
    Clear stored bonding information from adapter.
    
    Args:
        address: Specific device address, or None for all bonds
    
    Note:
        BGAPI stores bonds in adapter's internal flash memory
    """

Usage Example:

# Enable bonding for secure connections
adapter.set_bondable(True)

# Connect and bond with device
device = adapter.connect('01:23:45:67:89:ab')
device.bond(permanent=True)

# Later, clear specific bond
adapter.clear_bond('01:23:45:67:89:ab')

Low-Level Protocol Access

Direct access to BGAPI protocol commands for advanced applications and debugging.

def send_command(self, *args, **kwargs):
    """
    Send raw BGAPI command to adapter.
    
    Args:
        *args, **kwargs: Command-specific parameters
    
    Returns:
        Response packet data
    
    Raises:
        BGAPIError: Command failed or invalid
    """

def expect(self, expected, *args, **kwargs):
    """
    Send command and wait for specific response type.
    
    Args:
        expected: Expected response packet type
        *args, **kwargs: Command parameters
    
    Returns:
        Response packet matching expected type
    
    Raises:
        ExpectedResponseTimeout: Response not received within timeout
    """

def expect_any(self, expected_packet_choices, timeout: float = None, 
               assert_return_success: bool = True):
    """
    Wait for any of multiple expected response types.
    
    Args:
        expected_packet_choices: List of acceptable response types
        timeout: Wait timeout in seconds
        assert_return_success: Verify response indicates success
    
    Returns:
        First matching response packet
    
    Raises:
        ExpectedResponseTimeout: No expected response received
        BGAPIError: Response indicates error
    """

Advertising Control

Control adapter advertising behavior for peripheral mode applications.

def disable_advertising(self):
    """
    Disable BLE advertising on the adapter.
    
    Used when adapter should only operate in central mode.
    """

BGAPI Device Features

The BGAPIBLEDevice class extends BLEDevice with BGAPI-specific enhancements:

Enhanced Signal Monitoring

def get_rssi(self) -> int:
    """
    Get RSSI with BGAPI-specific retry logic.
    
    Handles BGAPI quirks for more reliable signal strength readings.
    
    Returns:
        int: RSSI in dBm, or None if unavailable
    """

Robust Bonding

def bond(self, permanent: bool = False):
    """
    Create bonded connection with BGAPI security features.
    
    Args:
        permanent: Store bond in adapter's flash memory
    
    Provides more reliable bonding than GATTTool backend.
    """

Hardware Compatibility

Supported Adapters

  • BLED112: Silicon Labs/Bluegiga USB BLE adapter
  • BLED113: Similar to BLED112 with different form factor
  • BGM11x Series: Silicon Labs Gecko modules with BGAPI firmware
  • Custom BGAPI devices: Any device implementing BGAPI protocol

USB Device Discovery

# Auto-discovery attempts to find BGAPI devices by VID/PID
BLED112_VENDOR_ID = 0x2458
BLED112_PRODUCT_ID = 0x0001

Manual Port Selection:

# Windows
adapter = pygatt.BGAPIBackend(serial_port='COM9')

# Linux
adapter = pygatt.BGAPIBackend(serial_port='/dev/ttyACM0')

# macOS
adapter = pygatt.BGAPIBackend(serial_port='/dev/cu.usbmodem1411')

Error Handling

BGAPI-specific exceptions and common error scenarios:

BGAPIError

Protocol-level errors from BGAPI commands:

try:
    adapter.start()
except pygatt.BGAPIError as e:
    print(f"BGAPI error: {e}")
    # Common causes: USB device not found, driver issues, permissions

ExpectedResponseTimeout

Command response timeouts:

try:
    device = adapter.connect('01:23:45:67:89:ab', timeout=5)
except pygatt.ExpectedResponseTimeout:
    print("Connection timeout - device may be out of range")

Common Issues

  • USB permissions: Linux may require udev rules or sudo
  • Driver conflicts: Ensure no other BGAPI applications are running
  • Port selection: Windows COM port numbers >10 may cause issues
  • Reset timing: Some adapters need longer reset delays

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