class documentation

class Bluetooth:

Constructor: Bluetooth(storage)

View In Hierarchy

A class to manage Bluetooth functionality as both central and peripheral device.

This class provides a unified interface for: - Central mode: Scan for, connect to, and communicate with BLE peripherals - Peripheral mode: Advertise, accept connections, and communicate with BLE centrals

Example (Peripheral mode):

bt = Bluetooth() bt.start_peripheral(name="MyDevice") bt.on_write(lambda data: print("Received:", data)) while True:

if bt.is_peripheral_connected:
bt.send("Hello from peripheral!")

time.sleep(1)

Example (Central mode):
bt = Bluetooth() bt.on_notify(lambda data: print("Received:", data)) bt.scan(callback=my_scan_callback) # After finding device... bt.connect(addr_type, addr) bt.write("Hello from central!")
Method __del__ Clean up Bluetooth resources.
Method __init__ Initialize Bluetooth.
Method advertise Start or stop BLE advertising to make this device discoverable.
Method callback.setter Set the Bluetooth callback function.
Method connect Connect to a BLE peripheral device (central mode).
Method decode_name Decode device name from advertising data.
Method decode_services Decode service UUIDs from advertising data.
Method disconnect Disconnect from a device.
Method discover_characteristics Discover characteristics for a service.
Method discover_services Discover services on the connected peripheral.
Method is_device_paired Check if a device address is in the paired devices list.
Method is_uart_ready Check if UART service is fully discovered and ready (central mode).
Method load_paired_devices Load paired devices from storage.
Method on_notify Set callback for when data is received from a peripheral (central mode).
Method on_scan Set callback for scan results (central mode).
Method on_write Set callback for when data is received from a central (peripheral mode).
Method pair Initiate pairing/bonding with the connected device.
Method passkey_reply Reply to a passkey request during pairing.
Method read Read data from a characteristic.
Method register Register the device as a GATT server with UART service.
Method remove_paired_device Remove a paired device from storage.
Method save_paired_device Save a paired device to storage.
Method scan Start scanning for BLE devices (central mode).
Method scan_for_uart_devices Scan for devices advertising the UART service (central mode).
Method scan_stop Stop an ongoing scan.
Method send Send data to all connected central devices (peripheral mode).
Method start_peripheral Start as a BLE peripheral (GATT server) with UART service.
Method stop_peripheral Stop peripheral mode (stop advertising).
Method subscribe Subscribe to notifications from a characteristic (central mode).
Method write Write data to the connected peripheral (central mode).
Property callback Get the current Bluetooth callback.
Property central_connections Get the set of connected central device handles (peripheral mode).
Property characteristics Get discovered characteristics.
Property connected_address Get the address of the connected device.
Property is_connected Check if connected to a peripheral (central mode).
Property is_pairing Check if currently in pairing process.
Property is_peripheral_connected Check if any central is connected (peripheral mode).
Property is_scanning Check if Bluetooth is currently scanning.
Property mac_address Get the MAC address of this Bluetooth device.
Property passkey Get the current passkey during pairing (if any).
Property services Get discovered services.
Method __irq Handle Bluetooth IRQ events for both central and peripheral modes.
Method _advertising_payload Generate advertising payload.
Method _start_advertising Start advertising with the registered payload.
Instance Variable _adv_payload Undocumented
Instance Variable _ble Undocumented
Instance Variable _callback Undocumented
Instance Variable _central_connections Undocumented
Instance Variable _characteristics Undocumented
Instance Variable _conn_handle Undocumented
Instance Variable _connected Undocumented
Instance Variable _connected_addr Undocumented
Instance Variable _end_handle Undocumented
Instance Variable _notify_callback Undocumented
Instance Variable _pairing Undocumented
Instance Variable _passkey Undocumented
Instance Variable _peripheral_registered Undocumented
Instance Variable _peripheral_rx_handle Undocumented
Instance Variable _peripheral_tx_handle Undocumented
Instance Variable _rx_handle Undocumented
Instance Variable _scan_callback Undocumented
Instance Variable _scanning Undocumented
Instance Variable _services Undocumented
Instance Variable _start_handle Undocumented
Instance Variable _storage Undocumented
Instance Variable _tx_handle Undocumented
Instance Variable _write_callback Undocumented
def __del__(self):

Clean up Bluetooth resources.

def __init__(self, storage=None):

Initialize Bluetooth.

Parameters
storage:StorageStorage instance for saving paired device keys. Defaults to None.
def advertise(self, interval_us=None, name='Picoware'):

Start or stop BLE advertising to make this device discoverable.

Parameters
interval_us:intAdvertising interval in microseconds. None stops advertising. Defaults to None.
name:strDevice name to advertise. Defaults to "Picoware".
Returns
boolTrue if advertising started or stopped successfully.
def callback(self, func: callable):

Set the Bluetooth callback function.

The callback receives (event, data) where event is one of the _IRQ_* constants.

Parameters
func:callableThe callback function to set.
def connect(self, addr_type, addr, timeout_ms=10000, auto_discover=True):

Connect to a BLE peripheral device (central mode).

Parameters
addr_type:intAddress type (0 = public, 1 = random).
addr:bytesDevice address as bytes.
timeout_ms:intConnection timeout in milliseconds. Defaults to 10000.
auto_discover:boolWhether to automatically discover services. Defaults to True.
Returns
boolTrue if the connection was initiated successfully.
def decode_name(self, adv_data) -> str:

Decode device name from advertising data.

Parameters
adv_data:bytesRaw advertising data bytes.
Returns
strThe device name or empty string if not found.
def decode_services(self, adv_data) -> list:

Decode service UUIDs from advertising data.

Parameters
adv_data:bytesRaw advertising data bytes.
Returns
listList of UUID objects found in the advertising data.
def disconnect(self, conn_handle=None):

Disconnect from a device.

Works for both modes: - Central mode: Disconnects from the connected peripheral - Peripheral mode: Disconnects a specific central if conn_handle provided

Parameters
conn_handle:intConnection handle to disconnect. Uses the current connection if None. Defaults to None.
def discover_characteristics(self, start_handle, end_handle):

Discover characteristics for a service.

Results are delivered via callback with _IRQ_GATTC_CHARACTERISTIC_RESULT events.

Parameters
start_handle:intService start handle.
end_handle:intService end handle.
Returns
boolTrue if discovery was initiated.
def discover_services(self):

Discover services on the connected peripheral.

Results will be delivered via callback with _IRQ_GATTC_SERVICE_RESULT events.

def is_device_paired(self, addr: str) -> bool:

Check if a device address is in the paired devices list.

Parameters
addr:strThe device address to check.
Returns
boolTrue if the device is paired.
def is_uart_ready(self) -> bool:

Check if UART service is fully discovered and ready (central mode).

Returns
boolTrue if both TX and RX handles are discovered
def load_paired_devices(self) -> dict:

Load paired devices from storage.

Returns
dictDictionary of paired devices {addr: {name, paired}}
def on_notify(self, callback):

Set callback for when data is received from a peripheral (central mode).

The callback receives the data bytes as its argument.

Parameters
callback:callableFunction to call with received data.
def on_scan(self, callback):

Set callback for scan results (central mode).

The callback receives (addr_type, addr, name, rssi, adv_data) per device.

Parameters
callback:callableFunction to call for each scan result.
def on_write(self, callback):

Set callback for when data is received from a central (peripheral mode).

The callback receives the data bytes as its argument.

Parameters
callback:callableFunction to call with received data.
def pair(self):

Initiate pairing/bonding with the connected device.

Call this after connecting to establish an encrypted bond. The device will be remembered for future connections.

def passkey_reply(self, accept=True, passkey=None):

Reply to a passkey request during pairing.

Parameters
accept:boolWhether to accept the pairing. Defaults to True.
passkey:intThe passkey to use for input actions. Defaults to None.
def read(self, handle):

Read data from a characteristic.

Result is delivered via callback with _IRQ_GATTC_READ_RESULT event.

Parameters
handle:intCharacteristic handle to read from.
Returns
boolTrue if the read was initiated.
def register(self):

Register the device as a GATT server with UART service.

This allows the device to accept incoming connections and provide services/characteristics to connected centrals.

Returns
boolTrue if registration successful
def remove_paired_device(self, addr: str):

Remove a paired device from storage.

Parameters
addr:strDevice address string to remove.
Returns
boolTrue if the device was removed.
def save_paired_device(self, addr: str, name: str = ''):

Save a paired device to storage.

Parameters
addr:strDevice address string.
name:strDevice name. Defaults to "".
Returns
boolTrue if the device was saved.
def scan(self, duration_ms=5000, interval_us=30000, window_us=30000, active=True, callback=None):

Start scanning for BLE devices (central mode).

Parameters
duration_ms:intHow long to scan in milliseconds. Defaults to 5000; 0 scans continuously.
interval_us:intScan interval in microseconds. Defaults to 30000.
window_us:intScan window in microseconds. Defaults to 30000.
active:boolWhether to request scan response data. Defaults to True.
callback:callableOptional callback for scan results (addr_type, addr, name, rssi, adv_data). Defaults to None.
Returns
boolTrue if the scan started successfully.
def scan_for_uart_devices(self, callback, duration_ms=5000):

Scan for devices advertising the UART service (central mode).

Parameters
callback:callableFunction called with (addr_type, addr, name) per UART device found.
duration_ms:intScan duration in milliseconds. Defaults to 5000.
Returns
boolTrue if the scan started.
def scan_stop(self):

Stop an ongoing scan.

def send(self, data):

Send data to all connected central devices (peripheral mode).

Sends a notification to all connected centrals.

Parameters
data:bytes or strData to send.
Returns
boolTrue if sent to at least one central.
def start_peripheral(self, name='Picoware', interval_us=500000):

Start as a BLE peripheral (GATT server) with UART service.

Registers the UART service and starts advertising so central devices can connect and communicate.

Parameters
name:strDevice name to advertise. Defaults to "Picoware".
interval_us:intAdvertising interval in microseconds. Defaults to 500000.
Returns
boolTrue if started successfully.
def stop_peripheral(self):

Stop peripheral mode (stop advertising).

Returns
boolTrue if stopped successfully
def subscribe(self, handle=None, notify=True):

Subscribe to notifications from a characteristic (central mode).

Parameters
handle:intCharacteristic value handle. Uses the UART TX handle if None. Defaults to None.
notify:boolTrue for notifications, False to unsubscribe. Defaults to True.
Returns
boolTrue if the subscription request was sent.
def write(self, data, handle=None, response=False):

Write data to the connected peripheral (central mode).

Parameters
data:bytes or strData to write.
handle:intCharacteristic handle to write to. Uses the UART RX handle if None. Defaults to None.
response:boolWhether to request a write response. Defaults to False.
Returns
boolTrue if the write was initiated.
@property
callback =

Get the current Bluetooth callback.

@property
central_connections: set =

Get the set of connected central device handles (peripheral mode).

@property
characteristics: list =

Get discovered characteristics.

@property
connected_address: str =

Get the address of the connected device.

@property
is_connected: bool =

Check if connected to a peripheral (central mode).

@property
is_pairing: bool =

Check if currently in pairing process.

@property
is_peripheral_connected: bool =

Check if any central is connected (peripheral mode).

@property
is_scanning: bool =

Check if Bluetooth is currently scanning.

@property
mac_address: str =

Get the MAC address of this Bluetooth device.

@property
passkey: int =

Get the current passkey during pairing (if any).

@property
services: list =

Get discovered services.

def __irq(self, event, data):

Handle Bluetooth IRQ events for both central and peripheral modes.

Parameters
event:intThe IRQ event constant.
data:tupleEvent-specific data.
def _advertising_payload(self, name=None, services=None, appearance=0):

Generate advertising payload.

Parameters
name:strDevice name to advertise. Defaults to None.
services:listList of service UUIDs to advertise. Defaults to None.
appearance:intDevice appearance code. Defaults to 0.
Returns
bytearrayThe advertising payload.
def _start_advertising(self, interval_us=500000):

Start advertising with the registered payload.

Parameters
interval_us:intAdvertising interval in microseconds. Defaults to 500000.
_adv_payload =

Undocumented

_ble =

Undocumented

_callback =

Undocumented

_central_connections: set =

Undocumented

_characteristics: list =

Undocumented

_conn_handle =

Undocumented

_connected: bool =

Undocumented

_connected_addr =

Undocumented

_end_handle =

Undocumented

_notify_callback =

Undocumented

_pairing: bool =

Undocumented

_passkey =

Undocumented

_peripheral_registered: bool =

Undocumented

_peripheral_rx_handle =

Undocumented

_peripheral_tx_handle =

Undocumented

_rx_handle =

Undocumented

_scan_callback =

Undocumented

_scanning: bool =

Undocumented

_services: list =

Undocumented

_start_handle =

Undocumented

_storage =

Undocumented

_tx_handle =

Undocumented

_write_callback =

Undocumented