Skip to content

Bumble Python API

Classes

Address

Bluetooth Address (see Bluetooth spec Vol 6, Part B - 1.3 DEVICE ADDRESS) NOTE: the address bytes are stored in little-endian byte order here, so address[0] is the LSB of the address, address[5] is the MSB.

Source code in bumble/hci.py
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
class Address:
    '''
    Bluetooth Address (see Bluetooth spec Vol 6, Part B - 1.3 DEVICE ADDRESS)
    NOTE: the address bytes are stored in little-endian byte order here, so
    address[0] is the LSB of the address, address[5] is the MSB.
    '''

    PUBLIC_DEVICE_ADDRESS = AddressType.PUBLIC_DEVICE
    RANDOM_DEVICE_ADDRESS = AddressType.RANDOM_DEVICE
    PUBLIC_IDENTITY_ADDRESS = AddressType.PUBLIC_IDENTITY
    RANDOM_IDENTITY_ADDRESS = AddressType.RANDOM_IDENTITY

    # Type declarations
    NIL: Address
    ANY: Address
    ANY_RANDOM: Address

    # pylint: disable-next=unnecessary-lambda
    ADDRESS_TYPE_SPEC = {'size': 1, 'mapper': lambda x: Address.address_type_name(x)}

    @classmethod
    def address_type_name(cls: type[Self], address_type: int) -> str:
        return AddressType(address_type).name

    @classmethod
    def from_string_for_transport(
        cls: type[Self], string: str, transport: PhysicalTransport
    ) -> Self:
        if transport == PhysicalTransport.BR_EDR:
            address_type = Address.PUBLIC_DEVICE_ADDRESS
        else:
            address_type = Address.RANDOM_DEVICE_ADDRESS
        return cls(string, address_type)

    @classmethod
    def parse_address(cls: type[Self], data: bytes, offset: int) -> tuple[int, Self]:
        # Fix the type to a default value. This is used for parsing type-less Classic
        # addresses
        return cls.parse_address_with_type(data, offset, Address.PUBLIC_DEVICE_ADDRESS)

    @classmethod
    def parse_random_address(
        cls: type[Self], data: bytes, offset: int
    ) -> tuple[int, Self]:
        return cls.parse_address_with_type(data, offset, Address.RANDOM_DEVICE_ADDRESS)

    @classmethod
    def parse_address_with_type(
        cls: type[Self], data: bytes, offset: int, address_type: AddressType
    ) -> tuple[int, Self]:
        return offset + 6, cls(data[offset : offset + 6], address_type)

    @classmethod
    def parse_address_preceded_by_type(
        cls: type[Self], data: bytes, offset: int
    ) -> tuple[int, Self]:
        address_type = AddressType(data[offset - 1])
        return cls.parse_address_with_type(data, offset, address_type)

    @classmethod
    def generate_static_address(cls) -> Address:
        '''Generates Random Static Address, with the 2 most significant bits of 0b11.

        See Bluetooth spec, Vol 6, Part B - Table 1.2.
        '''
        address_bytes = secrets.token_bytes(6)
        address_bytes = address_bytes[:5] + bytes([address_bytes[5] | 0b11000000])
        return Address(
            address=address_bytes, address_type=Address.RANDOM_DEVICE_ADDRESS
        )

    @classmethod
    def generate_private_address(cls, irk: bytes = b'') -> Address:
        '''Generates Random Private MAC Address.

        If IRK is present, a Resolvable Private Address, with the 2 most significant
        bits of 0b01 will be generated. Otherwise, a Non-resolvable Private Address,
        with the 2 most significant bits of 0b00 will be generated.

        See Bluetooth spec, Vol 6, Part B - Table 1.2.

        Args:
            irk: Local Identity Resolving Key(IRK), in little-endian. If not set, a
            non-resolvable address will be generated.
        '''
        if irk:
            prand = crypto.generate_prand()
            address_bytes = crypto.ah(irk, prand) + prand
        else:
            address_bytes = secrets.token_bytes(6)
            address_bytes = address_bytes[:5] + bytes([address_bytes[5] & 0b00111111])

        return Address(
            address=address_bytes, address_type=Address.RANDOM_DEVICE_ADDRESS
        )

    def __init__(
        self,
        address: Union[bytes, str],
        address_type: AddressType = RANDOM_DEVICE_ADDRESS,
    ) -> None:
        '''
        Initialize an instance. `address` may be a byte array in little-endian
        format, or a hex string in big-endian format (with optional ':'
        separators between the bytes).
        If the address is a string suffixed with '/P', `address_type` is ignored and
        the type is set to PUBLIC_DEVICE_ADDRESS.
        '''
        if isinstance(address, bytes):
            self.address_bytes = address
        else:
            # Check if there's a '/P' type specifier
            if address.endswith('P'):
                address_type = Address.PUBLIC_DEVICE_ADDRESS
                address = address[:-2]

            if len(address) == 12 + 5:
                # Form with ':' separators
                address = address.replace(':', '')

            self.address_bytes = bytes(reversed(bytes.fromhex(address)))

        if len(self.address_bytes) != 6:
            raise InvalidArgumentError('invalid address length')

        self.address_type = address_type

    def clone(self):
        return Address(self.address_bytes, self.address_type)

    @property
    def is_public(self):
        return self.address_type in (
            self.PUBLIC_DEVICE_ADDRESS,
            self.PUBLIC_IDENTITY_ADDRESS,
        )

    @property
    def is_random(self):
        return not self.is_public

    @property
    def is_resolved(self):
        return self.address_type in (
            self.PUBLIC_IDENTITY_ADDRESS,
            self.RANDOM_IDENTITY_ADDRESS,
        )

    @property
    def is_resolvable(self):
        return self.address_type == self.RANDOM_DEVICE_ADDRESS and (
            self.address_bytes[5] >> 6 == 1
        )

    @property
    def is_static(self):
        return self.is_random and (self.address_bytes[5] >> 6 == 3)

    def to_string(self, with_type_qualifier=True):
        '''
        String representation of the address, MSB first, with an optional type
        qualifier.
        '''
        result = ':'.join([f'{x:02X}' for x in reversed(self.address_bytes)])
        if not with_type_qualifier or not self.is_public:
            return result
        return result + '/P'

    def __bytes__(self):
        return self.address_bytes

    def __hash__(self):
        return hash(self.address_bytes)

    def __eq__(self, other):
        return (
            isinstance(other, Address)
            and self.address_bytes == other.address_bytes
            and self.is_public == other.is_public
        )

    def __str__(self):
        return self.to_string()

    def __repr__(self):
        return f'Address({self.to_string(False)}/{self.address_type_name(self.address_type)})'

__init__(address, address_type=RANDOM_DEVICE_ADDRESS)

Initialize an instance. address may be a byte array in little-endian format, or a hex string in big-endian format (with optional ':' separators between the bytes). If the address is a string suffixed with '/P', address_type is ignored and the type is set to PUBLIC_DEVICE_ADDRESS.

Source code in bumble/hci.py
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
def __init__(
    self,
    address: Union[bytes, str],
    address_type: AddressType = RANDOM_DEVICE_ADDRESS,
) -> None:
    '''
    Initialize an instance. `address` may be a byte array in little-endian
    format, or a hex string in big-endian format (with optional ':'
    separators between the bytes).
    If the address is a string suffixed with '/P', `address_type` is ignored and
    the type is set to PUBLIC_DEVICE_ADDRESS.
    '''
    if isinstance(address, bytes):
        self.address_bytes = address
    else:
        # Check if there's a '/P' type specifier
        if address.endswith('P'):
            address_type = Address.PUBLIC_DEVICE_ADDRESS
            address = address[:-2]

        if len(address) == 12 + 5:
            # Form with ':' separators
            address = address.replace(':', '')

        self.address_bytes = bytes(reversed(bytes.fromhex(address)))

    if len(self.address_bytes) != 6:
        raise InvalidArgumentError('invalid address length')

    self.address_type = address_type

generate_private_address(irk=b'') classmethod

Generates Random Private MAC Address.

If IRK is present, a Resolvable Private Address, with the 2 most significant bits of 0b01 will be generated. Otherwise, a Non-resolvable Private Address, with the 2 most significant bits of 0b00 will be generated.

See Bluetooth spec, Vol 6, Part B - Table 1.2.

Parameters:

Name Type Description Default
irk bytes

Local Identity Resolving Key(IRK), in little-endian. If not set, a

b''
Source code in bumble/hci.py
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
@classmethod
def generate_private_address(cls, irk: bytes = b'') -> Address:
    '''Generates Random Private MAC Address.

    If IRK is present, a Resolvable Private Address, with the 2 most significant
    bits of 0b01 will be generated. Otherwise, a Non-resolvable Private Address,
    with the 2 most significant bits of 0b00 will be generated.

    See Bluetooth spec, Vol 6, Part B - Table 1.2.

    Args:
        irk: Local Identity Resolving Key(IRK), in little-endian. If not set, a
        non-resolvable address will be generated.
    '''
    if irk:
        prand = crypto.generate_prand()
        address_bytes = crypto.ah(irk, prand) + prand
    else:
        address_bytes = secrets.token_bytes(6)
        address_bytes = address_bytes[:5] + bytes([address_bytes[5] & 0b00111111])

    return Address(
        address=address_bytes, address_type=Address.RANDOM_DEVICE_ADDRESS
    )

generate_static_address() classmethod

Generates Random Static Address, with the 2 most significant bits of 0b11.

See Bluetooth spec, Vol 6, Part B - Table 1.2.

Source code in bumble/hci.py
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
@classmethod
def generate_static_address(cls) -> Address:
    '''Generates Random Static Address, with the 2 most significant bits of 0b11.

    See Bluetooth spec, Vol 6, Part B - Table 1.2.
    '''
    address_bytes = secrets.token_bytes(6)
    address_bytes = address_bytes[:5] + bytes([address_bytes[5] | 0b11000000])
    return Address(
        address=address_bytes, address_type=Address.RANDOM_DEVICE_ADDRESS
    )

to_string(with_type_qualifier=True)

String representation of the address, MSB first, with an optional type qualifier.

Source code in bumble/hci.py
2219
2220
2221
2222
2223
2224
2225
2226
2227
def to_string(self, with_type_qualifier=True):
    '''
    String representation of the address, MSB first, with an optional type
    qualifier.
    '''
    result = ':'.join([f'{x:02X}' for x in reversed(self.address_bytes)])
    if not with_type_qualifier or not self.is_public:
        return result
    return result + '/P'

HCI_Packet

Abstract Base class for HCI packets

Source code in bumble/hci.py
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
class HCI_Packet:
    '''
    Abstract Base class for HCI packets
    '''

    hci_packet_type: ClassVar[int]

    @staticmethod
    def from_bytes(packet: bytes) -> HCI_Packet:
        packet_type = packet[0]

        if packet_type == HCI_COMMAND_PACKET:
            return HCI_Command.from_bytes(packet)

        if packet_type == HCI_ACL_DATA_PACKET:
            return HCI_AclDataPacket.from_bytes(packet)

        if packet_type == HCI_SYNCHRONOUS_DATA_PACKET:
            return HCI_SynchronousDataPacket.from_bytes(packet)

        if packet_type == HCI_EVENT_PACKET:
            return HCI_Event.from_bytes(packet)

        if packet_type == HCI_ISO_DATA_PACKET:
            return HCI_IsoDataPacket.from_bytes(packet)

        return HCI_CustomPacket(packet)

    def __init__(self, name):
        self.name = name

    def __bytes__(self) -> bytes:
        raise NotImplementedError

    def __repr__(self) -> str:
        return self.name

HCI Commands

HCI_Command

Bases: HCI_Packet

See Bluetooth spec @ Vol 2, Part E - 5.4.1 HCI Command Packet

Source code in bumble/hci.py
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
class HCI_Command(HCI_Packet):
    '''
    See Bluetooth spec @ Vol 2, Part E - 5.4.1 HCI Command Packet
    '''

    hci_packet_type = HCI_COMMAND_PACKET
    command_names: dict[int, str] = {}
    command_classes: dict[int, type[HCI_Command]] = {}
    op_code: int
    fields: Fields = ()
    return_parameters_fields: Fields = ()
    _parameters: bytes = b''

    _Command = TypeVar("_Command", bound="HCI_Command")

    @classmethod
    def command(cls, subclass: type[_Command]) -> type[_Command]:
        '''
        Decorator used to declare and register subclasses
        '''

        # Subclasses may set parameters as ClassVar, or inferred from class name.
        if not hasattr(subclass, 'name'):
            subclass.name = subclass.__name__.upper()
        if not hasattr(subclass, 'op_code'):
            op_code = key_with_value(subclass.command_names, subclass.name)
            if op_code is None:
                raise KeyError(f'command {subclass.name} not found in command_names')
            subclass.op_code = op_code

        if dataclasses.is_dataclass(subclass):
            subclass.fields = HCI_Object.fields_from_dataclass(subclass)

        # Register a factory for this class
        cls.command_classes[subclass.op_code] = subclass

        return subclass

    @staticmethod
    def command_map(symbols: dict[str, Any]) -> dict[int, str]:
        return {
            command_code: command_name
            for (command_name, command_code) in symbols.items()
            if command_name.startswith('HCI_') and command_name.endswith('_COMMAND')
        }

    @classmethod
    def register_commands(cls, symbols: dict[str, Any]) -> None:
        cls.command_names.update(cls.command_map(symbols))

    @staticmethod
    def from_bytes(packet: bytes) -> HCI_Command:
        op_code, length = struct.unpack_from('<HB', packet, 1)
        parameters = packet[4:]
        if len(parameters) != length:
            raise InvalidPacketError('invalid packet length')

        # Look for a registered class
        cls = HCI_Command.command_classes.get(op_code)
        if cls is None:
            # No class registered, just use a generic instance
            return HCI_Command(parameters, op_code=op_code)

        return cls.from_parameters(parameters)

    @classmethod
    def from_parameters(cls, parameters: bytes) -> HCI_Command:
        command = cls(**HCI_Object.dict_from_bytes(parameters, 0, cls.fields))
        command.parameters = parameters
        return command

    @classmethod
    def command_name(cls, op_code: int) -> str:
        if name := cls.command_names.get(op_code):
            return name
        if (subclass := cls.command_classes.get(op_code)) and subclass.name:
            return subclass.name
        return f'[OGF=0x{op_code >> 10:02x}, OCF=0x{op_code & 0x3FF:04x}]'

    @classmethod
    def create_return_parameters(cls, **kwargs):
        return HCI_Object(cls.return_parameters_fields, **kwargs)

    @classmethod
    def parse_return_parameters(cls, parameters):
        if not cls.return_parameters_fields:
            return None
        return_parameters = HCI_Object.from_bytes(
            parameters, 0, cls.return_parameters_fields
        )
        return_parameters.fields = cls.return_parameters_fields
        return return_parameters

    def __init__(
        self,
        parameters: Optional[bytes] = None,
        *,
        op_code: Optional[int] = None,
        **kwargs,
    ) -> None:
        # op_code should be set in cls.
        if op_code is not None:
            self.op_code = op_code
        super().__init__(HCI_Command.command_name(self.op_code))
        if self.fields and kwargs:
            HCI_Object.init_from_fields(self, self.fields, kwargs)
            if parameters is None:
                parameters = HCI_Object.dict_to_bytes(kwargs, self.fields)
        self.parameters = parameters or b''

    @property
    def parameters(self) -> bytes:
        if not self._parameters:
            self._parameters = HCI_Object.dict_to_bytes(self.__dict__, self.fields)
        return self._parameters

    @parameters.setter
    def parameters(self, parameters: bytes):
        self._parameters = parameters

    def __bytes__(self) -> bytes:
        parameters = b'' if self.parameters is None else self.parameters
        return (
            struct.pack('<BHB', HCI_COMMAND_PACKET, self.op_code, len(parameters))
            + parameters
        )

    def __str__(self):
        result = color(self.name, 'green')
        if self.fields:
            result += ':\n' + HCI_Object.format_fields(self.__dict__, self.fields, '  ')
        else:
            if self.parameters:
                result += f': {self.parameters.hex()}'
        return result

command(subclass) classmethod

Decorator used to declare and register subclasses

Source code in bumble/hci.py
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
@classmethod
def command(cls, subclass: type[_Command]) -> type[_Command]:
    '''
    Decorator used to declare and register subclasses
    '''

    # Subclasses may set parameters as ClassVar, or inferred from class name.
    if not hasattr(subclass, 'name'):
        subclass.name = subclass.__name__.upper()
    if not hasattr(subclass, 'op_code'):
        op_code = key_with_value(subclass.command_names, subclass.name)
        if op_code is None:
            raise KeyError(f'command {subclass.name} not found in command_names')
        subclass.op_code = op_code

    if dataclasses.is_dataclass(subclass):
        subclass.fields = HCI_Object.fields_from_dataclass(subclass)

    # Register a factory for this class
    cls.command_classes[subclass.op_code] = subclass

    return subclass

HCI_Disconnect_Command

Bases: HCI_Command

See Bluetooth spec @ 7.1.6 Disconnect Command

Source code in bumble/hci.py
2510
2511
2512
2513
2514
2515
2516
2517
2518
@HCI_Command.command
@dataclasses.dataclass
class HCI_Disconnect_Command(HCI_Command):
    '''
    See Bluetooth spec @ 7.1.6 Disconnect Command
    '''

    connection_handle: int = field(metadata=metadata(2))
    reason: int = field(metadata=metadata(STATUS_SPEC))