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
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
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
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 = 0x00
    RANDOM_DEVICE_ADDRESS = 0x01
    PUBLIC_IDENTITY_ADDRESS = 0x02
    RANDOM_IDENTITY_ADDRESS = 0x03

    ADDRESS_TYPE_NAMES = {
        PUBLIC_DEVICE_ADDRESS: 'PUBLIC_DEVICE_ADDRESS',
        RANDOM_DEVICE_ADDRESS: 'RANDOM_DEVICE_ADDRESS',
        PUBLIC_IDENTITY_ADDRESS: 'PUBLIC_IDENTITY_ADDRESS',
        RANDOM_IDENTITY_ADDRESS: 'RANDOM_IDENTITY_ADDRESS',
    }

    # 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)}

    @staticmethod
    def address_type_name(address_type):
        return name_or_number(Address.ADDRESS_TYPE_NAMES, address_type)

    @staticmethod
    def from_string_for_transport(string, transport):
        if transport == BT_BR_EDR_TRANSPORT:
            address_type = Address.PUBLIC_DEVICE_ADDRESS
        else:
            address_type = Address.RANDOM_DEVICE_ADDRESS
        return Address(string, address_type)

    @staticmethod
    def parse_address(data, offset):
        # Fix the type to a default value. This is used for parsing type-less Classic
        # addresses
        return Address.parse_address_with_type(
            data, offset, Address.PUBLIC_DEVICE_ADDRESS
        )

    @staticmethod
    def parse_random_address(data, offset):
        return Address.parse_address_with_type(
            data, offset, Address.RANDOM_DEVICE_ADDRESS
        )

    @staticmethod
    def parse_address_with_type(data, offset, address_type):
        return offset + 6, Address(data[offset : offset + 6], address_type)

    @staticmethod
    def parse_address_preceded_by_type(data, offset):
        address_type = data[offset - 1]
        return Address.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: int = 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.
        '''
        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
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
def __init__(
    self, address: Union[bytes, str], address_type: int = 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.
    '''
    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
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
@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
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
@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
2082
2083
2084
2085
2086
2087
2088
2089
2090
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
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
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
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
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
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
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

    @staticmethod
    def command(fields=(), return_parameters_fields=()):
        '''
        Decorator used to declare and register subclasses
        '''

        def inner(cls):
            cls.name = cls.__name__.upper()
            cls.op_code = key_with_value(cls.command_names, cls.name)
            if cls.op_code is None:
                raise KeyError(f'command {cls.name} not found in command_names')
            cls.fields = fields
            cls.return_parameters_fields = return_parameters_fields

            # Patch the __init__ method to fix the op_code
            if fields is not None:

                def init(self, parameters=None, **kwargs):
                    return HCI_Command.__init__(self, cls.op_code, parameters, **kwargs)

                cls.__init__ = init

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

            return cls

        return inner

    @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(op_code, parameters)

        # Create a new instance
        if (fields := getattr(cls, 'fields', None)) is not None:
            self = cls.__new__(cls)
            HCI_Command.__init__(self, op_code, parameters)
            HCI_Object.init_from_bytes(self, parameters, 0, fields)
            return self

        return cls.from_parameters(parameters)  # type: ignore

    @staticmethod
    def command_name(op_code):
        name = HCI_Command.command_names.get(op_code)
        if name is not None:
            return 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, op_code=-1, parameters=None, **kwargs):
        # Since the legacy implementation relies on an __init__ injector, typing always
        # complains that positional argument op_code is not passed, so here sets a
        # default value to allow building derived HCI_Command without op_code.
        assert op_code != -1
        super().__init__(HCI_Command.command_name(op_code))
        if (fields := getattr(self, 'fields', None)) and kwargs:
            HCI_Object.init_from_fields(self, fields, kwargs)
            if parameters is None:
                parameters = HCI_Object.dict_to_bytes(kwargs, fields)
        self.op_code = op_code
        self.parameters = parameters

    def __bytes__(self):
        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 fields := getattr(self, 'fields', None):
            result += ':\n' + HCI_Object.format_fields(self.__dict__, fields, '  ')
        else:
            if self.parameters:
                result += f': {self.parameters.hex()}'
        return result

command(fields=(), return_parameters_fields=()) staticmethod

Decorator used to declare and register subclasses

Source code in bumble/hci.py
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
@staticmethod
def command(fields=(), return_parameters_fields=()):
    '''
    Decorator used to declare and register subclasses
    '''

    def inner(cls):
        cls.name = cls.__name__.upper()
        cls.op_code = key_with_value(cls.command_names, cls.name)
        if cls.op_code is None:
            raise KeyError(f'command {cls.name} not found in command_names')
        cls.fields = fields
        cls.return_parameters_fields = return_parameters_fields

        # Patch the __init__ method to fix the op_code
        if fields is not None:

            def init(self, parameters=None, **kwargs):
                return HCI_Command.__init__(self, cls.op_code, parameters, **kwargs)

            cls.__init__ = init

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

        return cls

    return inner

HCI_Disconnect_Command

Bases: HCI_Command

See Bluetooth spec @ 7.1.6 Disconnect Command

Source code in bumble/hci.py
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
@HCI_Command.command(
    [
        ('connection_handle', 2),
        ('reason', {'size': 1, 'mapper': HCI_Constant.error_name}),
    ]
)
class HCI_Disconnect_Command(HCI_Command):
    '''
    See Bluetooth spec @ 7.1.6 Disconnect Command
    '''