API documentation

Generic

Service & Discovery Helpers

bt_manager.serviceuuids.SERVICES
data dict SERVICES:
 

A dictionary of service UUIDs which allows all bluetooth standard-based services to be keyed by either their short-form name or their UUID16 value.

Example:

SERVICES['AudioSource'] shall return a BTUUID16

denoting the A2DP audio source profile UUID.

SERVICES['110A'] shall return the same BTUUID16

denoting the A2DP audio source profile UUID.

bt_manager.attributes.ATTRIBUTES
data dict ATTRIBUTES:
 

A dictionary of attribute dictionaries which allows all bluetooth standard-based attribute sets associated with a given service UUID to be found.

Example:

ATTRIBUTES['*'] shall return a dictionary of the universal

service attributes.

ATTRIBUTES['*']['0000'] shall return the universal service

attribute name string for attribute 0000 which is ServiceRecordHandle in this instance.

ATTRIBUTES['110A'] shall return the audio source service

attributes dictionary.

class bt_manager.uuid.BTUUID(uuid=None, uuid16=None, uuid32=None, name=None, desc=None)[source]

This class encapsulates a UUID (universally unique identifier) which is a 128-bit value. It is represented as a hex string of the form ZZZZYYYY-BBBB-BBBB-BBBB-VVVVVVVVVVVV although typically UUIDs are referenced only by the 16-bit YYYY part since this is generally sufficient to uniquely identify the services/protocols that form part of the bluetooth standard.

When creating a UUID as 16-bits only, the YYYY nibbles are set accordingly with the remaining nibbles set automatically using the base UUID which is 00000000-0000-1000-8000-00805F9B34FB.

When creating a UUID as 32-bits, the uppermost 8 nibbles shall be set instead.

Otherwise a fully qualified 128-bit UUID is assumed to be provided.

For ease of use, optionally, a human readable name and description can be provided with the UUID. It is encouraged that this is done as UUIDs are otherwise hard to read.

Parameters:
  • uuid (str) – Optional full 128-bit UUID string of the form ZZZZYYYY-BBBB-BBBB-BBBB-VVVVVVVVVVVV
  • uuid16 (str) – Optional 16-bit UUID string of the form YYYY. Base UUID is used to populate unset bits.
  • uuid32 (str) – Optional 32-bit UUID string of the form ZZZZYYYY. Base UUID is used to populate unset bits.
  • name (str) – Optional string providing a unique name for the UUID.
  • desc (str) – Optional string providing a description of the UUID.
Raises BTUUIDNotSpecifiedException:
 

if neither a uuid, uuid16 nor uuid32 is provided.

uuid16[source]

Returns the 16-bit part of the UUID string i.e., given a UUID of the form ZZZZYYYY-BBBB-BBBB-BBBB-VVVVVVVVVVVV it shall return YYYY

uuid32[source]

Returns the 32-bit part of the UUID string i.e., given a UUID of the form ZZZZYYYY-BBBB-BBBB-BBBB-VVVVVVVVVVVV it shall return ZZZZYYYY

class bt_manager.uuid.BTUUID16(uuid, name, desc=None)[source]

Shortened-form UUID allowing only 16-bit UUID to be created. Refer to BTUUID for details.

class bt_manager.uuid.BTUUID32(uuid, name, desc=None)[source]

Shortened-form UUID allowing only 32-bit UUID to be created. Refer to BTUUID for details.

bt_manager.uuid.BASE_UUID = <uuid:00000000-0000-1000-8000-00805F9B34FB name:BASE_UUID desc:Base Universally Unique Identifier>
Data BASE_UUID:The base UUID which takes the value of 00000000-0000-1000-8000-00805F9B34FB
class bt_manager.discovery.BTDiscoveryInfo(text)[source]

Parser for XML discovery service record obtained from the bluetooth service discovery procedure.

The XML parser recursively and iteratively translates all known service UUIDs and attribute UUIDs to their human readable form thus allowing a BTDiscoveryInfo instance to be printed e.g., for debugging purposes.

Parameters:text (str) – An XML service record return as part of the device service discovery procedure.

Note

A dictionary of XML service records is obtained by executing the BTDevice.discover_services() method.

Device Identification

class bt_manager.cod.BTCoD(cod)[source]

Bluetooth class of device decoder for providing a human readable form of the device class value.

The class of device is a 24-bit number allowing different types of bluetooth devices to be described consistently and succinctly using a hierarchical scheme.

  • Major Service: The major services that the

    device supports. Several values can be OR’d together to form a device supporting multiple major services e.g., telephony, networking and audio could be the combined service set for a device.

  • Major Device: The form-factor or major type of device

    which may only take a single value e.g., Laptop, Toy, Health Device, Phone, etc.

  • Minor Device: The minor function of the device whose

    range of values depends on the major function e.g., Car audio, SmartPhone, etc.

Parameters:cod (integer) – 24-bit integer value representing the class of device.

Note

The class of device may be obtained from both the BTAdapter and BTDevice classes using the Class attribute.

major_device_class[source]

Return the major device class property decoded e.g., Computer, Audio/Video, Toy, etc.

major_service_class[source]

Return the major service class property decoded e.g., Audio, Telephony, etc

minor_device_class[source]

Return the minor device class property decoded e.g., Scanner, Printer, Loudspeaker, Camera, etc.

Vendor Identification

bt_manager.vendors.VENDORS
data dict VENDOR:
 

A dictionary of vendor IDs which allows all registered bluetooth vendors to be keyed by their unique vendor ID to obtain the vendor name string.

Example:

VENDORS[2] shall return Intel Corp.

VENDORS[25] shall return Broadcom Corporation

Note

The device vendor ID can be obtained from the BTDevice class’ Vendor attribute following the service discovery procedure.

Bluetooth Interfaces & Services

Interface

Inheritance diagram of bt_manager.interface

class bt_manager.interface.BTInterface(path, addr)[source]

Bases: bt_manager.interface.BTSimpleInterface

Wrapper around DBus to encapsulated a BT interface entry point e.g., an adapter, a device, etc.

Parameters:
  • path (str) – Object path pertaining to the interface to open e.g., ‘/org/bluez/985/hci0’
  • addr (str) – dbus address of the interface instance to open e.g., ‘org.bluez.Adapter’

Note

This class should always be sub-classed with a concrete implementation of a bluez interface which has both signals and properties.

SIGNAL_PROPERTY_CHANGED = u'PropertyChanged'
Signal PropertyChanged(sig_name, user_arg, prop_name, prop_value):
 Signal notifying when a property has changed.
add_signal_receiver(callback_fn, signal, user_arg)[source]

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

get_property(name=None)[source]

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)[source]

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)[source]

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.interface.BTSimpleInterface(path, addr)[source]

Wrapper around dbus to encapsulated a BT simple interface entry point (i.e., has no signals or properties).

Parameters:
  • path (str) – Object path pertaining to the interface to open e.g., ‘/org/bluez/985/hci0’
  • addr (str) – dbus address of the interface instance to open e.g., ‘org.bluez.Adapter’

Note

This class should always be sub-classed with a concrete implementation of a bluez interface which has no signals or properties.

class bt_manager.interface.Signal(signal, user_callback, user_arg)[source]

Encapsulation of user callback wrapper for signals fired by dbus. This allows us to prepend the signal name and the user callback argument.

Parameters:
  • signal (str) – Signal name
  • user_callback (func) – User-defined callback function to call when the signal triggers
  • user_arg – User-defined callback argument to be passed as callback function
signal_handler(*args)[source]

Method to call in order to invoke the user callback.

Parameters:args – list of signal-dependent arguments
Returns:
bt_manager.interface.translate_to_dbus_type(typeof, value)[source]

Helper function to map values from their native Python types to Dbus types.

Parameters:
  • typeof (type) – Target for type conversion e.g., ‘dbus.Dictionary’
  • value – Value to assign using type ‘typeof’
Returns:

‘value’ converted to type ‘typeof’

Return type:

typeof

Manager

Inheritance diagram of bt_manager.manager

class bt_manager.manager.BTManager[source]

Bases: bt_manager.interface.BTInterface

Wrapper around dbus to encapsulate the org.bluez.manager interface which notionally is used to manage available bluetooth adapters.

Properties :
  • Adapters(list{str}) [readonly]: List of adapter object paths.

See also BTAdapter

SIGNAL_ADAPTER_ADDED = u'AdapterAdded'
Signal AdapterAdded(signal_name, user_arg, object_path):
 Signal notifying when an adapter is added.
SIGNAL_ADAPTER_REMOVED = u'AdapterRemoved'
Signal AdapterRemoved(signal_name, user_arg, object_path):
 Signal notifying when an adapter is removed. .. note: In case all adapters are removed this signal will not be emitted. The AdapterRemoved signal has to be used to detect that no default adapter is selected or available anymore.
SIGNAL_DEFAULT_ADAPTER_CHANGED = u'DefaultAdapterChanged'
Signal DefaultAdapterChanged(signal_name, user_arg, object_path):
 Signal notifying when the default adapter has been changed.
add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

default_adapter()[source]

Obtain the default BT adapter object path.

Returns:

Object path of default adapter

Return type:

str

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.NoSuchAdapter
find_adapter(pattern)[source]

Returns object path for the specified adapter.

Parameters:

pattern (str) – Valid patterns are “hci0” or “00:11:22:33:44:55”.

Returns:

Object path of adapter

Return type:

str

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.NoSuchAdapter
get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
list_adapters()[source]

Returns list of adapter object paths under /org/bluez

Returns:

List of object paths or each adapter attached

Return type:

list

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.Failed
  • dbus.Exception – org.bluez.Error.OutOfMemory
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments

Adapter

Inheritance diagram of bt_manager.adapter

class bt_manager.adapter.BTAdapter(adapter_path=None, adapter_id=None)[source]

Bases: bt_manager.interface.BTInterface

Wrapper around dbus to encapsulate org.bluez.adapter interface.

Parameters:
  • adapter_path (str) – Object path to bluetooth adapter. If not given, can use adapter_id instead.
  • adapter_id (str) – Adapter’s MAC address to look-up to find path e.g., ‘11:22:33:44:55:66’
Properties :
  • Address(str) [readonly]: The Bluetooth device address

    of the adapter.

  • Name(str) [readonly]: The Bluetooth system name

    (pretty hostname). This property is either a static system default or controlled by an external daemon providing access to the pretty hostname configuration.

  • Alias(str) [readwrite]: The Bluetooth friendly name.

    This value can be changed. In case no alias is set, it will return the system provided name. Setting an empty string as alias will convert it back to the system provided name. When resetting the alias with an empty string, the property will default back to system name. On a well configured system, this property never needs to be changed since it defaults to the system name and provides the pretty hostname. Only if the local name needs to be different from the pretty hostname, this property should be used as last resort.

  • Class(uint32) [readonly]: The Bluetooth class of

    device. This property represents the value that is either automatically configured by DMI/ACPI information or provided as static configuration.

  • Powered(boolean) [readwrite]: Switch an adapter on or

    off. This will also set the appropriate connectable state of the controller. The value of this property is not persistent. After restart or unplugging of the adapter it will reset back to false.

  • Discoverable(boolean) [readwrite]: Switch an adapter

    to discoverable or non-discoverable to either make it visible or hide it. This is a global setting and should only be used by the settings application. If DiscoverableTimeout is set to a non-zero value then the system will set this value back to false after the timer expired. In case the adapter is switched off, setting this value will fail. When changing the Powered property the new state of this property will be updated via a BTInterface.SIGNAL_PROPERTY_CHANGED signal. For any new adapter this settings defaults to false.

  • Pairable(boolean) [readwrite]: Switch an adapter to

    pairable or non-pairable. This is a global setting and should only be used by the settings application.

  • PairableTimeout(uint32) [readwrite]:

    The pairable timeout in seconds. A value of zero means that the timeout is disabled and it will stay in pairable mode forever. The default value for pairable timeout should be disabled (value 0).

  • DiscoverableTimeout(uint32) [readwrite]:

    The discoverable timeout in seconds. A value of zero means that the timeout is disabled and it will stay in discoverable/limited mode forever. The default value for the discoverable timeout should be 180 seconds (3 minutes).

  • Discovering(boolean) [readonly]:

    Indicates that a device discovery procedure is active.

  • UUIDs(array{str}) [readonly]:

    List of 128-bit UUIDs that represents the available local services.

  • Modalias(str) [readonly, optional]:

    Local Device ID information in modalias format used by the kernel and udev.

See also: BTManager

SIGNAL_DEVICE_CREATED = u'DeviceCreated'
Signal DeviceCreated(signal_name, user_arg, device_path):
 Signal notifying when a new device is created
SIGNAL_DEVICE_DISAPPEARED = u'DeviceDisappeared'
Signal DeviceDisappeared(signal_name, user_arg, device_path):
 Signal notifying when a device is now out-of-range
SIGNAL_DEVICE_FOUND = u'DeviceFound'
Signal DeviceFound(signal_name, user_arg, device_path):
 Signal notifying when a new device has been found
SIGNAL_DEVICE_REMOVED = u'DeviceRemoved'
Signal DeviceRemoved(signal_name, user_arg, device_path):
 Signal notifying when a device has been removed
add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

create_paired_device(dev_id, agent_path, capability, cb_notify_device, cb_notify_error)[source]

Creates a new object path for a remote device. This method will connect to the remote device and retrieve all SDP records and then initiate the pairing.

If a previously create_device() was used successfully, this method will only initiate the pairing.

Compared to create_device() this method will fail if the pairing already exists, but not if the object path already has been created. This allows applications to use create_device() first and then, if needed, use create_paired_device() to initiate pairing.

The agent object path is assumed to reside within the process (D-Bus connection instance) that calls this method. No separate registration procedure is needed for it and it gets automatically released once the pairing operation is complete.

Parameters:
  • dev_id (str) – New device MAC address create e.g., ‘11:22:33:44:55:66’
  • agent_path (str) – Path used when creating the bluetooth agent e.g., ‘/test/agent’
  • capability (str) – Pairing agent capability e.g., ‘DisplayYesNo’, etc
  • cb_notify_device (func) – Callback on success. The callback is called with the new device’s object path as an argument.
  • cb_notify_error (func) – Callback on error. The callback is called with the error reason.
Returns:

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.Failed
find_device(dev_id)[source]

Returns the object path of device for given address. The device object needs to be first created via create_device() or create_paired_device()

Parameters:

dev_id (str) – Device MAC address to look-up e.g., ‘11:22:33:44:55:66’

Returns:

Device object path e.g., ‘/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE’

Return type:

str

Raises:
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
list_devices()[source]

Returns list of device object paths.

Returns:

List of device object paths

Return type:

list

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.Failed
  • dbus.Exception – org.bluez.Error.OutOfMemory
register_agent(path, capability)[source]

This registers the adapter wide agent.

The object path defines the path the of the agent that will be called when user input is needed.

If an application disconnects from the bus all of its registered agents will be removed.

Parameters:
  • path (str) – Freely definable path for agent e.g., ‘/test/agent’
  • capability (str) – The capability parameter can have the values “DisplayOnly”, “DisplayYesNo”, “KeyboardOnly” and “NoInputNoOutput” which reflects the input and output capabilities of the agent. If an empty string is used it will fallback to “DisplayYesNo”.
Returns:

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.AlreadyExists
remove_device(dev_path)[source]

This removes the remote device object at the given path. It will remove also the pairing information.

Parameters:

dev_path (str) – Device object path to remove e.g., ‘/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE’

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.Failed
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
start_discovery()[source]

This method starts the device discovery session. This includes an inquiry procedure and remote device name resolving. Use stop_discovery() to release the sessions acquired.

This process will start emitting SIGNAL_DEVICE_FOUND and SIGNAL_PROPERTY_CHANGED ‘discovering’ signals.

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.NotReady
  • dbus.Exception – org.bluez.Error.Failed
stop_discovery()[source]

This method will cancel any previous start_discovery() transaction.

Note that a discovery procedure is shared between all discovery sessions thus calling py:meth:stop_discovery will only release a single session.

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.NotReady
  • dbus.Exception – org.bluez.Error.Failed
  • dbus.Exception – org.bluez.Error.NotAuthorized
unregister_agent(path)[source]

This unregisters the agent that has been previously registered. The object path parameter must match the same value that has been used on registration.

Parameters:path (str) – Previously defined path for agent e.g., ‘/test/agent’
Returns:
Raises dbus.Exception:
 org.bluez.Error.DoesNotExist

Device

Inheritance diagram of bt_manager.device

class bt_manager.device.BTDevice(*args, **kwargs)[source]

Bases: bt_manager.device.BTGenericDevice

Wrapper around dbus to encapsulate the org.bluez.Device interface. Refer to BTGenericDevice for init arguments.

Properties :
  • Address(str) [readonly]: The Bluetooth device address of the

    remote device.

  • Name(str) [readonly]: The Bluetooth remote name. This value can

    not be changed. Use the Alias property instead.

  • Icon(str) [readonly]: Proposed icon name according to the

    freedesktop.org icon naming specification.

  • Class(str) [readonly]: The Bluetooth class of device of the remote

    device.

  • UUIDs(list{str}) [readonly]: List of 128-bit UUIDs that represents

    the available remote services.

  • Paired(boolean) [readonly]: Indicates if the remote device is paired.

  • Connected(boolean) [readonly]: Indicates if the remote device is

    connected.

  • Trusted(boolean) [readwrite]: Indicates if the remote device is

    trusted.

  • Alias(str) [readwrite]: The name alias for the remote device. The

    alias can be used to have a different friendly name for the remote device. In case no alias is set, it will return the remote device name. Setting an empty string as alias will convert it back to the remote device name. When reseting the alias with an empty string, the emitted :py:attr`.SIGNAL_PROPERTY_CHANGED` signal will show the remote name again.

  • Nodes(list{str}) [readonly]: List of device node object paths.

  • Adapter(str) [readonly]: The object path of the adpater the device

    belongs to.

  • LegacyPairing(boolean) [readonly]: Set to true if the device only

    supports the pre-2.1 pairing mechanism. This property is useful in the :py:attr`.SIGNAL_DEVICE_FOUND` signal to anticipate whether legacy or simple pairing will occur. Note that this property can exhibit false-positives in the case of Bluetooth 2.1 (or newer) devices that have disabled Extended Inquiry Response support.

  • Blocked(boolean) [readonly]: Set to true if the device is blocked.

  • Product(uint16) [readonly]: Product code identifier.

  • Vendor(uint16) [readonly]: Product vendor identifier.

  • Services(list{str}) [readonly]: TBD.

SIGNAL_DISCONNECT_REQUESTED = u'DisconnectRequested'
Signal DisconnectRequested(signal_name, user_arg):
 This signal will be sent when a low level disconnection to a remote device has been requested. The actual disconnection will happen 2 seconds later.
SIGNAL_NODE_CREATED = u'NodeCreated'
Signal NodeCreated(signal_name, user_arg, node_path):
 Signal notifying when a new device node has been created.
SIGNAL_NODE_REMOVED = u'NodeRemoved'
Signal NodeRemoved(signal_name, user_arg, node_path):
 Signal notifying when a device node has been removed.
add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

cancel_discovery()[source]

This method will cancel any previous discover_services() transaction.

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.NotReady
  • dbus.Exception – org.bluez.Error.Failed
  • dbus.Exception – org.bluez.Error.NotAuthorized
disconnect()[source]

This method disconnects a specific remote device by terminating the low-level ACL connection. The use of this method should be restricted to administrator use.

A SIGNAL_DISCONNECT_REQUESTED signal will be sent and the actual disconnection will only happen 2 seconds later. This enables upper-level applications to terminate their connections gracefully before the ACL connection is terminated.

Returns:
Raises dbus.Exception:
 org.bluez.Error.NotConnected
discover_services(pattern=u'')[source]

This method starts the service discovery to retrieve remote service records.

Refer to BTDiscoveryInfo to decode each XML service record.

Parameters:

pattern (str) – can be used to specify specific UUIDs. An empty string will look for the public browse group.

Returns:

a dictionary with the record handles as keys and the service record in XML format as values. The key is uint32 and the value a string for this dictionary.

Return type:

dict

Raises:
  • dbus.Exception – org.bluez.Error.NotReady
  • dbus.Exception – org.bluez.Error.Failed
  • dbus.Exception – org.bluez.Error.InProgress
get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.device.BTGenericDevice(addr, dev_path=None, adapter_path=None, adapter_id=None, dev_id=None)[source]

Bases: bt_manager.interface.BTInterface

Generic BT device which has its own interface bus address but is associated with a BT adapter.

Parameters:
  • addr (str) – Interface address e.g., ‘org.bluez.Device’
  • dev_path (str) – Optional fully qualified device object path e.g., ‘/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE’
  • adapter_path (str) – Optional fully qualified adapter object path if using dev_id e.g., ‘/org/bluez/985/hci0’
  • adapter_id (str) – Optional adapter device ID if using dev_id e.g. ‘hci0’ or ‘11:22:33:44:55:66’
  • dev_id (str) – Optional device ID to look-up object path e.g. ‘11:22:33:44:55:66’
Raises BTDeviceNotSpecifiedException:
 

if the device address was not specified unambiguously.

Note

This class should always be sub-classed with a concrete implementation of a bluez interface.

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments

Agent

Inheritance diagram of bt_manager.agent

class bt_manager.agent.BTAgent(path=u'/test/agent', auto_authorize_connections=True, default_pin_code=u'0000', default_pass_key=0, cb_notify_on_release=None, cb_notify_on_authorize=None, cb_notify_on_request_pin_code=None, cb_notify_on_request_pass_key=None, cb_notify_on_display_pass_key=None, cb_notify_on_request_confirmation=None, cb_notify_on_confirm_mode_change=None, cb_notify_on_cancel=None)[source]

Bases: dbus.service.Object

Simple BT device pairing agent.

A bluetooth pairing agent is responsible for admitting new devices onto the system and registering them for subsequent use. The procedure is abstracted away into a service object that implements a few procedures depending on the type of pairing scheme in use.

Different pairing schemes are required since some devices do not have displays or keypads allowing them to enter passkeys or confirm passkeys.

The SSP (Secure Simple Pairing) schemes that can be supported using this agent are:

  • Just works: No user interaction required.

  • Numeric comparison: A pass key is displayed which

    the receiving device must confirm with a binary yes/no response.

  • Passkey entry: A pass key must be entered manually

    which the receiving device must confirm by also entering the same pass key.

The pairing scheme selected will be dependent on the capability of the agent which is defined when the agent is registered via the BTAdapter.register_agent() method.

See also: BTAdapter

Introspect(object_path, connection)

Return a string of XML encoding this object’s supported interfaces, methods and signals.

add_to_connection(connection, path)

Make this object accessible via the given D-Bus connection and object path.

Parameters :
connection : dbus.connection.Connection

Export the object on this connection. If the class attribute SUPPORTS_MULTIPLE_CONNECTIONS is False (default), this object can only be made available on one connection; if the class attribute is set True by a subclass, the object can be made available on more than one connection.

path : dbus.ObjectPath or other str

Place the object at this object path. If the class attribute SUPPORTS_MULTIPLE_OBJECT_PATHS is False (default), this object can only be made available at one object path; if the class attribute is set True by a subclass, the object can be made available with more than one object path.

Raises ValueError:
 

if the object’s class attributes do not allow the object to be exported in the desired way.

Since :

0.82.0

connection

The Connection on which this object is available. Access raises AttributeError if there is no Connection, or more than one Connection.

Changed in 0.82.0: AttributeError can be raised.

locations

An iterable over tuples representing locations at which this object is available.

Each tuple has at least two items, but may have more in future versions of dbus-python, so do not rely on their exact length. The first two items are the dbus.connection.Connection and the object path.

Since :0.82.0
remove_from_connection(connection=None, path=None)

Make this object inaccessible via the given D-Bus connection and object path. If no connection or path is specified, the object ceases to be accessible via any connection or path.

Parameters :
connection : dbus.connection.Connection or None

Only remove the object from this Connection. If None, remove from all Connections on which it’s exported.

path : dbus.ObjectPath or other str, or None

Only remove the object from this object path. If None, remove from all object paths.

Raises LookupError:
 

if the object was not exported on the requested connection or path, or (if both are None) was not exported at all.

Since :

0.81.1

Media

Inheritance diagram of bt_manager.media

class bt_manager.media.BTMedia(adapter_id=None)[source]

Bases: bt_manager.interface.BTSimpleInterface

Wrapper around dbus to encapsulate org.bluez.Media interface.

The media interface allows media endpoints to be established in accordance with the capabilities of a specific media service profile.

For example, an A2DP media endpoint could be created allowing data from a remote device to be streamed to/from the sender.

Each media endpoint is associated with a service object instance that implements the required behaviours of the endpoint. The service object must be created at a given path before it is registered.

See also: GenericEndpoint

register_endpoint(path, properties)[source]

Register a local end point to sender, the sender can register as many end points as it likes.

The properties dictionary parameter may take the following fields:

  • UUID(str): UUID of the profile which the endpoint is

    for e.g., SERVICES['AudioSource']

  • Codec(byte): Assigned mumber of codec that the

    endpoint implements. The values should match the profile specification which is indicated by the UUID e.g., A2DP_CODECS['SBC']

  • Capabilities(array{byte}): Capabilities blob, it is used

    as it is so the size and byte order must match.

See also: A2DP_CODECS and SERVICES

If the sender disconnects the end points are automatically unregistered.

Param :

str path: a freely definable path name for registering the endpoint e.g., ‘/endpoint/a2dpsource’.

Param :

dict properties: a dictionary defining the endpoints properties which may contain.

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.InvalidArguments
  • dbus.Exception – org.bluez.Error.NotSupported
unregister_endpoint(path)[source]

Unregister sender end point.

Param :str path: a freely definable path name previously used for registering via register_endpoint()
Returns:
class bt_manager.media.BTMediaTransport(path, fd=None, adapter_id=None, dev_path=None, dev_id=None)[source]

Bases: bt_manager.interface.BTInterface

Wrapper around dbus to encapsulate the org.bluez.MediaTransport interface.

A media transport instance provides a mechanism by which data streamed to/from a device can be sent/received via the L2 transport.

This is done by acquiring a transport file descriptor object which then allows the underlying file to be read from or written to.

When finished, the file descriptor should be closed using a normal UNIX close() operation before releasing the media transport back again.

Warning

The media transport interface does not implement any CODECs and should be regarded as providing direct access to the underlying data transport.

Param :str path: [Optional] Absolute object path to the device’s file descriptor node carrying the media transport.
Param :str dev_path: [Optional] Device’s object path. The file descriptor node will be provided via fd argument.
Param :int fd: [Optional] File number for the file descriptor node associated with the device given by either dev_path or dev_id
Param :str adapter_id: [Optional] Adapter identifier from which to look-up the dev_id
Param :str dev_id: [Optional] Device identifier of the form e.g., ‘11:22:33:44:55:66’.
Raises BTDeviceNotSpecifiedException:
 if the device path could not be determined unambiguously from the supplied parameters.
Properties :
  • Device(str) [readonly]: Device object which the transport

    is connected to.

  • UUID(str) [readonly]: UUID of the profile which the

    transport is for.

  • Codec(byte) [readonly]: Assigned mumber of codec that the

    transport support. The value should match the profile specification which is indicated by the UUID.

  • Configuration(byte) [readonly]: Configuration blob, it is

    used as it is so the size and byte order must match.

  • Delay(uint16) [readwrite]: Optional. Transport delay in

    1/10 of milisecond, this property is only writeable when the transport was acquired by the sender.

  • NREC(boolean) [readwrite]: Optional. Indicates if echo

    cancelling and noise reduction functions are active in the transport, this property is only writeable when the transport was acquired by the sender.

  • InbandRingtone(boolean) [readwrite]: Optional. Indicates

    if the transport support sending ringtones, this property is only writeable when the transport was acquired by the sender.

  • Routing(str) [readonly]: Optional. Indicates where is the

    transport being routed and may be ‘HCI’ or ‘PCM’.

acquire(access_type)[source]

Acquire transport file descriptor and the MTU for read and/or write respectively. Possible access_type:

  • “r” : Read only access
  • “w” : Write only access
  • “rw”: Read and write access
Parameters:access_type (str) – as defined above.
Returns:A tuple of the form (fd, write_mtu, read_mtu)
Return type:tuple
add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
release(access_type)[source]

Releases file descriptor.

Possible access_type:

  • “r” : Read only access
  • “w” : Write only access
  • “rw”: Read and write access
Parameters:access_type (str) – as defined above.
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.media.GenericEndpoint(path)[source]

Bases: dbus.service.Object

Generic media endpoint service object class.

Note

GenericEndpoint can’t be directly instantiated. It should be sub-classed and provides a template for implementing an endpoint service object.

Parameters:path (str) – Freely definable object path for the media endpoint e.g., ‘/endpoint/a2dpsink’.
ClearConfiguration()[source]

Called by bluez to let us know that the audio streaming process has been reset, for whatever reason, and we should now perform clean-up.

Returns:
Introspect(object_path, connection)

Return a string of XML encoding this object’s supported interfaces, methods and signals.

Release()[source]

Called by bluez to let us know our registration has been released and the endpoint no longer exists

Returns:
SelectConfiguration(caps)[source]

Initiates negotiations of the capabilities which should be resolved by this method.

Parameters:caps (dict) – Dictionary of device’s capabilities for resolving capability negotiation by comparing to own capabilities.
Return config:The resolved configuration to be used for the media transport.
Return type:array{byte}
SetConfiguration(transport, config)[source]

Provides a path to the media transport to use and the active configuration that was negotiated.

Parameters:
  • transport (str) – Path to a device’s file descriptor node which can be used to acquire the media transport e.g., ‘/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE/fd0’
  • config (array{byte}) – The configuration being used for the media transport.

See also: BTMediaTransport

add_to_connection(connection, path)

Make this object accessible via the given D-Bus connection and object path.

Parameters :
connection : dbus.connection.Connection

Export the object on this connection. If the class attribute SUPPORTS_MULTIPLE_CONNECTIONS is False (default), this object can only be made available on one connection; if the class attribute is set True by a subclass, the object can be made available on more than one connection.

path : dbus.ObjectPath or other str

Place the object at this object path. If the class attribute SUPPORTS_MULTIPLE_OBJECT_PATHS is False (default), this object can only be made available at one object path; if the class attribute is set True by a subclass, the object can be made available with more than one object path.

Raises ValueError:
 

if the object’s class attributes do not allow the object to be exported in the desired way.

Since :

0.82.0

connection

The Connection on which this object is available. Access raises AttributeError if there is no Connection, or more than one Connection.

Changed in 0.82.0: AttributeError can be raised.

get_properties()[source]

Returns the properties of the endpoint. These should be initialized by a suitable subclass implementation by setting the properties class attribute.

Return properties:
 dictionary of endpoint’s capabilties
Return type:dict
locations

An iterable over tuples representing locations at which this object is available.

Each tuple has at least two items, but may have more in future versions of dbus-python, so do not rely on their exact length. The first two items are the dbus.connection.Connection and the object path.

Since :0.82.0
remove_from_connection(connection=None, path=None)

Make this object inaccessible via the given D-Bus connection and object path. If no connection or path is specified, the object ceases to be accessible via any connection or path.

Parameters :
connection : dbus.connection.Connection or None

Only remove the object from this Connection. If None, remove from all Connections on which it’s exported.

path : dbus.ObjectPath or other str, or None

Only remove the object from this object path. If None, remove from all object paths.

Raises LookupError:
 

if the object was not exported on the requested connection or path, or (if both are None) was not exported at all.

Since :

0.81.1

Audio

Inheritance diagram of bt_manager.audio

class bt_manager.audio.BTAudio(*args, **kwargs)[source]

Bases: bt_manager.device.BTGenericDevice

Wrapper around dbus to encapsulate the org.bluez.Audio interface.

Properties :
  • State(str) [readonly]: Possible values: “disconnected”,

    “connecting”, “connected” with possible state transitions:

    • “disconnected” -> “connecting” Either an incoming or outgoing connection attempt ongoing.
    • “connecting” -> “disconnected” Connection attempt failed
    • “connecting” -> “connected” Successfully connected
    • “connected” -> “disconnected” Disconnected from the remote device

See also: BTGenericDevice for setup params.

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

connect()[source]

Connect all supported audio profiles on the device.

Returns:

Note

This may invoke any registered media endpoints where media profiles are compatible.

disconnect()[source]

Disconnect all audio profiles on the device

Returns:

Note

This may release any registered media endpoints where media profiles are compatible.

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.audio.BTAudioSink(*args, **kwargs)[source]

Bases: bt_manager.audio.BTAudio

Wrapper around dbus to encapsulate the org.bluez.AudioSink interface

  • Connected(boolean) [readonly]: Indicates if a stream is

    setup to a A2DP sink on the remote device.

  • Playing(boolean) [readonly]: Indicates if a stream is

    active to a A2DP sink on the remote device.

See also: BTAudio

SIGNAL_CONNECTED = u'Connected'
Signal Connected(signal_name, user_arg):
 Sent when a successful connection has been made to the remote A2DP Sink
SIGNAL_DISCONNECTED = u'Disconnected'
Signal Disconnected(signal_name, user_arg):
 Sent when the device has been disconnected from.
SIGNAL_PLAYING = u'Playing'
Signal Playing(signal_name, user_arg):
 Sent when a stream with remote device is started.
SIGNAL_STOPPED = u'Stopped'
Signal Stopped(signal_name, user_arg):
 Sent when a stream with remote device is suspended.
add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

connect()

Connect all supported audio profiles on the device.

Returns:

Note

This may invoke any registered media endpoints where media profiles are compatible.

disconnect()

Disconnect all audio profiles on the device

Returns:

Note

This may release any registered media endpoints where media profiles are compatible.

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
is_connected()[source]

Returns True if a stream is setup to a A2DP sink on the remote device, False otherwise.

Return Connected:
 state of Connected attribute
Return type:boolean
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.audio.BTAudioSource(*args, **kwargs)[source]

Bases: bt_manager.audio.BTAudio

Wrapper around dbus to encapsulate the org.bluez.AudioSource interface.

See also: BTAudio

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

connect()

Connect all supported audio profiles on the device.

Returns:

Note

This may invoke any registered media endpoints where media profiles are compatible.

disconnect()

Disconnect all audio profiles on the device

Returns:

Note

This may release any registered media endpoints where media profiles are compatible.

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
class bt_manager.audio.SBCAudioCodec(uuid, path)[source]

Bases: bt_manager.media.GenericEndpoint

SBCAudioCodec is an implementation of a media endpoint that provides common functionality enabling SBC audio source and SBC audio sink media endpoints to be established.

Since certain procedures are specific to whether or not the endpoint is a source or sink, in particular the trigger points for when the media transport is acquired/release, these parts are left to their respective sub-classes.

SBCAudioCodec handles the following steps in establishing an endpoint:

  • Populates properties with the capabilities of the codec.

  • SelectConfiguration: computes and returns best SBC codec

    configuration parameters based on device capabilities

  • SetConfiguration: a sub-class notifier function is called

  • ClearConfiguration: nothing is done

  • Release: nothing

In additional to endpoint establishment, the class also has transport read and write functions which will handle the required SBC media encoding/decoding and RTP encapsulation.

The user may also register for transport ready events which allows transport read and write operations to be properly synchronized.

See also: SBCAudioSink and SBCAudioSource

Introspect(object_path, connection)

Return a string of XML encoding this object’s supported interfaces, methods and signals.

add_to_connection(connection, path)

Make this object accessible via the given D-Bus connection and object path.

Parameters :
connection : dbus.connection.Connection

Export the object on this connection. If the class attribute SUPPORTS_MULTIPLE_CONNECTIONS is False (default), this object can only be made available on one connection; if the class attribute is set True by a subclass, the object can be made available on more than one connection.

path : dbus.ObjectPath or other str

Place the object at this object path. If the class attribute SUPPORTS_MULTIPLE_OBJECT_PATHS is False (default), this object can only be made available at one object path; if the class attribute is set True by a subclass, the object can be made available with more than one object path.

Raises ValueError:
 

if the object’s class attributes do not allow the object to be exported in the desired way.

Since :

0.82.0

close_transport()[source]

Forcibly close previously acquired media transport.

Note

The user should first make sure any transport event handlers are unregistered first.

connection

The Connection on which this object is available. Access raises AttributeError if there is no Connection, or more than one Connection.

Changed in 0.82.0: AttributeError can be raised.

get_properties()

Returns the properties of the endpoint. These should be initialized by a suitable subclass implementation by setting the properties class attribute.

Return properties:
 dictionary of endpoint’s capabilties
Return type:dict
locations

An iterable over tuples representing locations at which this object is available.

Each tuple has at least two items, but may have more in future versions of dbus-python, so do not rely on their exact length. The first two items are the dbus.connection.Connection and the object path.

Since :0.82.0
read_transport()[source]

Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed.

Return data:Payload data that has been decoded, with RTP encapsulation removed.
Return type:array{byte}
register_transport_ready_event(user_cb, user_arg)[source]

Register for transport ready events. The transport ready event is raised via a user callback. If the endpoint is configured as a source, then the user may then call write_transport() in order to send data to the associated sink. Otherwise, if the endpoint is configured as a sink, then the user may call read_transport() to read from the associated source instead.

Parameters:
  • user_cb (func) – User defined callback function. It must take one parameter which is the user’s callback argument.
  • user_arg – User defined callback argument.
Returns:

See also: unregister_transport_ready_event()

remove_from_connection(connection=None, path=None)

Make this object inaccessible via the given D-Bus connection and object path. If no connection or path is specified, the object ceases to be accessible via any connection or path.

Parameters :
connection : dbus.connection.Connection or None

Only remove the object from this Connection. If None, remove from all Connections on which it’s exported.

path : dbus.ObjectPath or other str, or None

Only remove the object from this object path. If None, remove from all object paths.

Raises LookupError:
 

if the object was not exported on the requested connection or path, or (if both are None) was not exported at all.

Since :

0.81.1

unregister_transport_ready_event()[source]

Unregister previously registered transport ready events.

See also: register_transport_ready_event()

write_transport(data)[source]

Write data to media transport. The data is encoded using the SBC codec and RTP encapsulated before being written to the transport file descriptor.

Parameters:data (array{byte}) – Payload data to encode, encapsulate and send.
class bt_manager.audio.SBCAudioSink(path=u'/endpoint/a2dpsink')[source]

Bases: bt_manager.audio.SBCAudioCodec

SBC audio sink media endpoint

SBCAudioSink implies the BT adapter takes on the role of a sink and the external device is the source e.g., iPhone, media player.

Refer to SBCAudioCodec for basic overview of endpoint steps

Introspect(object_path, connection)

Return a string of XML encoding this object’s supported interfaces, methods and signals.

add_to_connection(connection, path)

Make this object accessible via the given D-Bus connection and object path.

Parameters :
connection : dbus.connection.Connection

Export the object on this connection. If the class attribute SUPPORTS_MULTIPLE_CONNECTIONS is False (default), this object can only be made available on one connection; if the class attribute is set True by a subclass, the object can be made available on more than one connection.

path : dbus.ObjectPath or other str

Place the object at this object path. If the class attribute SUPPORTS_MULTIPLE_OBJECT_PATHS is False (default), this object can only be made available at one object path; if the class attribute is set True by a subclass, the object can be made available with more than one object path.

Raises ValueError:
 

if the object’s class attributes do not allow the object to be exported in the desired way.

Since :

0.82.0

close_transport()

Forcibly close previously acquired media transport.

Note

The user should first make sure any transport event handlers are unregistered first.

connection

The Connection on which this object is available. Access raises AttributeError if there is no Connection, or more than one Connection.

Changed in 0.82.0: AttributeError can be raised.

get_properties()

Returns the properties of the endpoint. These should be initialized by a suitable subclass implementation by setting the properties class attribute.

Return properties:
 dictionary of endpoint’s capabilties
Return type:dict
locations

An iterable over tuples representing locations at which this object is available.

Each tuple has at least two items, but may have more in future versions of dbus-python, so do not rely on their exact length. The first two items are the dbus.connection.Connection and the object path.

Since :0.82.0
read_transport()

Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed.

Return data:Payload data that has been decoded, with RTP encapsulation removed.
Return type:array{byte}
register_transport_ready_event(user_cb, user_arg)

Register for transport ready events. The transport ready event is raised via a user callback. If the endpoint is configured as a source, then the user may then call write_transport() in order to send data to the associated sink. Otherwise, if the endpoint is configured as a sink, then the user may call read_transport() to read from the associated source instead.

Parameters:
  • user_cb (func) – User defined callback function. It must take one parameter which is the user’s callback argument.
  • user_arg – User defined callback argument.
Returns:

See also: unregister_transport_ready_event()

remove_from_connection(connection=None, path=None)

Make this object inaccessible via the given D-Bus connection and object path. If no connection or path is specified, the object ceases to be accessible via any connection or path.

Parameters :
connection : dbus.connection.Connection or None

Only remove the object from this Connection. If None, remove from all Connections on which it’s exported.

path : dbus.ObjectPath or other str, or None

Only remove the object from this object path. If None, remove from all object paths.

Raises LookupError:
 

if the object was not exported on the requested connection or path, or (if both are None) was not exported at all.

Since :

0.81.1

unregister_transport_ready_event()

Unregister previously registered transport ready events.

See also: register_transport_ready_event()

write_transport(data)

Write data to media transport. The data is encoded using the SBC codec and RTP encapsulated before being written to the transport file descriptor.

Parameters:data (array{byte}) – Payload data to encode, encapsulate and send.
class bt_manager.audio.SBCAudioSource(path=u'/endpoint/a2dpsource')[source]

Bases: bt_manager.audio.SBCAudioCodec

SBC audio source media endpoint.

SBCAudioSource implies the adapter takes on the role of source and the external device is the sink e.g., speaker.

Refer to SBCAudioCodec for basic overview of endpoint steps

Introspect(object_path, connection)

Return a string of XML encoding this object’s supported interfaces, methods and signals.

add_to_connection(connection, path)

Make this object accessible via the given D-Bus connection and object path.

Parameters :
connection : dbus.connection.Connection

Export the object on this connection. If the class attribute SUPPORTS_MULTIPLE_CONNECTIONS is False (default), this object can only be made available on one connection; if the class attribute is set True by a subclass, the object can be made available on more than one connection.

path : dbus.ObjectPath or other str

Place the object at this object path. If the class attribute SUPPORTS_MULTIPLE_OBJECT_PATHS is False (default), this object can only be made available at one object path; if the class attribute is set True by a subclass, the object can be made available with more than one object path.

Raises ValueError:
 

if the object’s class attributes do not allow the object to be exported in the desired way.

Since :

0.82.0

close_transport()

Forcibly close previously acquired media transport.

Note

The user should first make sure any transport event handlers are unregistered first.

connection

The Connection on which this object is available. Access raises AttributeError if there is no Connection, or more than one Connection.

Changed in 0.82.0: AttributeError can be raised.

get_properties()

Returns the properties of the endpoint. These should be initialized by a suitable subclass implementation by setting the properties class attribute.

Return properties:
 dictionary of endpoint’s capabilties
Return type:dict
locations

An iterable over tuples representing locations at which this object is available.

Each tuple has at least two items, but may have more in future versions of dbus-python, so do not rely on their exact length. The first two items are the dbus.connection.Connection and the object path.

Since :0.82.0
read_transport()

Read data from media transport. The returned data payload is SBC decoded and has all RTP encapsulation removed.

Return data:Payload data that has been decoded, with RTP encapsulation removed.
Return type:array{byte}
register_transport_ready_event(user_cb, user_arg)

Register for transport ready events. The transport ready event is raised via a user callback. If the endpoint is configured as a source, then the user may then call write_transport() in order to send data to the associated sink. Otherwise, if the endpoint is configured as a sink, then the user may call read_transport() to read from the associated source instead.

Parameters:
  • user_cb (func) – User defined callback function. It must take one parameter which is the user’s callback argument.
  • user_arg – User defined callback argument.
Returns:

See also: unregister_transport_ready_event()

remove_from_connection(connection=None, path=None)

Make this object inaccessible via the given D-Bus connection and object path. If no connection or path is specified, the object ceases to be accessible via any connection or path.

Parameters :
connection : dbus.connection.Connection or None

Only remove the object from this Connection. If None, remove from all Connections on which it’s exported.

path : dbus.ObjectPath or other str, or None

Only remove the object from this object path. If None, remove from all object paths.

Raises LookupError:
 

if the object was not exported on the requested connection or path, or (if both are None) was not exported at all.

Since :

0.81.1

unregister_transport_ready_event()

Unregister previously registered transport ready events.

See also: register_transport_ready_event()

write_transport(data)

Write data to media transport. The data is encoded using the SBC codec and RTP encapsulated before being written to the transport file descriptor.

Parameters:data (array{byte}) – Payload data to encode, encapsulate and send.
bt_manager.codecs.A2DP_CODECS = {u'MPEG12': 1, u'SBC': 0, u'ATRAC': 3, u'MPEG24': 2}

Enumeration of codec types supported by A2DP profile

class bt_manager.codecs.SBCAllocationMethod[source]

Indicates how the bit pool is allocated to different subbands. Either it is based on the loudness of the sub band signal or on the signal to noise ratio.

class bt_manager.codecs.SBCBlocks[source]

The block size with which the stream has been encoded

class bt_manager.codecs.SBCChannelMode[source]

Indicate with which channel mode the frame has been encoded. The number of channels depends on this information.

class bt_manager.codecs.SBCCodec(config)[source]

Python cass wrapper around CFFI calls into the SBC codec implemented in C. The main API is defined by sbc.h with additional functions added to encapsulate an SBC payload as part of an RTP packet. The API extensions for RTP are designed to work directly with bluetooth media transport file descriptors for the A2DP profile. So, the basic idea is that this class is instantiated as part of a media endpoint implementation in order to encode or decode data carried on the media transport.

Note

You need two separate instantiations of this class if you wish to encode and decode at the same time. Although the class implementation is the same, the underlying C implementation requires separate sbc_t instances.

Parameters:config (namedtuple) – Media endpoint negotiated configuration parameters. These are not used directly by the codec here but translated to parameters usable by the codec. See SBCCodecConfig
decode(fd, mtu, max_len=2560)[source]

Read the media transport descriptor, depay the RTP payload and decode the SBC frames into a byte array. The maximum number of bytes to be returned may be passed as an argument and all available bytes are returned to the caller.

Parameters:
  • fd (int) – Media transport file descriptor
  • mtu (int) – Media transport MTU size as returned when the media transport was acquired.
  • max_len (int) – Optional. Set maximum number of bytes to read.
Return data:

Decoded data bytes as an array.

Return type:

array{byte}

encode(fd, mtu, data)[source]

Encode the supplied data (byte array) and write to the media transport file descriptor encapsulated as RTP packets. The encoder will calculate the required number of SBC frames and encapsulate as RTP to fit the MTU size.

Parameters:
  • fd (int) – Media transport file descriptor
  • mtu (int) – Media transport MTU size as returned when the media transport was acquired.
  • data (array{byte}) – Data to encode and send over the media transport.
Returns:

class bt_manager.codecs.SBCCodecConfig

Bases: tuple

Named tuple collection of SBC A2DP audio profile properties

allocation_method

Alias for field number 2

block_length

Alias for field number 4

channel_mode

Alias for field number 0

count(value) → integer -- return number of occurrences of value
frequency

Alias for field number 1

index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

max_bitpool

Alias for field number 6

min_bitpool

Alias for field number 5

subbands

Alias for field number 3

class bt_manager.codecs.SBCSamplingFrequency[source]

Indicates with which sampling frequency the SBC frame has been encoded.

class bt_manager.codecs.SBCSubbands[source]

indicates the number of subbands with which the frame has been encoded

Headset

Inheritance diagram of bt_manager.headset

class bt_manager.headset.BTHeadset(*args, **kwargs)[source]

Bases: bt_manager.audio.BTAudio

Wrapper around Dbus to encapsulate the BT headset entity

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

cancel_call()[source]

Cancel the incoming call indication

connect()

Connect all supported audio profiles on the device.

Returns:

Note

This may invoke any registered media endpoints where media profiles are compatible.

disconnect()

Disconnect all audio profiles on the device

Returns:

Note

This may release any registered media endpoints where media profiles are compatible.

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
indicate_call()[source]

Indicate an incoming call on the headset connected to the stream. Will continue to ring the headset about every 3 seconds.

play()[source]

Open the audio connection to the headset

remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
stop()[source]

Close the audio connection

class bt_manager.headset.BTHeadsetGateway(*args, **kwargs)[source]

Bases: bt_manager.audio.BTAudio

Wrapper around Dbus to encapsulate the BT headset gateway entity

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

answer_call()[source]

It has to called only after Ring signal received.

call(dial_number)[source]

Dial a number. No number processing is done thus if AG would reject to dial it don’t blame me

connect()

Connect all supported audio profiles on the device.

Returns:

Note

This may invoke any registered media endpoints where media profiles are compatible.

disconnect()

Disconnect all audio profiles on the device

Returns:

Note

This may release any registered media endpoints where media profiles are compatible.

get_operator_name()[source]

Find out the name of the currently selected network operator by AG.

get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
get_subscriber_number()[source]

Get the voicecall subscriber number of AG

remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
send_dtmf(digits)[source]

Will send each digit in the ‘digits’ sequentially. Would send nothing if there is non-DTMF digit.

set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
terminate_call()[source]

Terminate call which is running or reject an incoming call. This has nothing with any 3-way situation incl. RaH. Just plain old PDH.

Input

Inheritance diagram of bt_manager.input

class bt_manager.input.BTInput(*args, **kwargs)[source]

Bases: bt_manager.device.BTGenericDevice

Wrapper around dbus to encapsulate the org.bluez.Input interface.

Properties :
  • Connected(boolean) [readonly]:

    Indicates if the device is connected.

See also: BTGenericDevice for setup params.

add_signal_receiver(callback_fn, signal, user_arg)

Add a signal receiver callback with user argument

See also remove_signal_receiver(), BTSignalNameNotRecognisedException

Parameters:
  • callback_fn (func) – User-defined callback function to call when signal triggers
  • signal (str) – Signal name e.g., BTInterface.SIGNAL_PROPERTY_CHANGED
  • user_arg – User-defined callback argument to be passed with callback function
Returns:

Raises BTSignalNameNotRecognisedException:
 

if the signal name is not registered

connect()[source]

Connect to the input device.

Returns:

Raises:
  • dbus.Exception – org.bluez.Error.AlreadyConnected
  • dbus.Exception – org.bluez.Error.ConnectionAttemptFailed
disconnect()[source]

Disconnect from the input device.

To abort a connection attempt in case of errors or timeouts in the client it is fine to call this method.

Returns:
Raises dbus.Exception:
 org.bluez.Error.Failed
get_property(name=None)

Helper to get a property value by name or all properties as a dictionary.

See also set_property()

Parameters:

name (str) – defaults to None which means all properties in the object’s dictionary are returned as a dict. Otherwise, the property name key is used and its value is returned.

Returns:

Property value by property key, or a dictionary of all properties

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments
remove_signal_receiver(signal)

Remove an installed signal receiver by signal name.

See also add_signal_receiver() exceptions.BTSignalNameNotRecognisedException

Parameters:signal (str) – Signal name to uninstall e.g., SIGNAL_PROPERTY_CHANGED
Returns:
Raises BTSignalNameNotRecognisedException:
 if the signal name is not registered
set_property(name, value)

Helper to set a property value by name, translating to correct dbus type

See also get_property()

Parameters:
  • name (str) – The property name in the object’s dictionary whose value shall be set.
  • value – Properties new value to be assigned.
Returns:

Raises:
  • KeyError – if the property key is not found in the object’s dictionary
  • dbus.Exception – org.bluez.Error.DoesNotExist
  • dbus.Exception – org.bluez.Error.InvalidArguments

Exceptions

class bt_manager.exceptions.BTSignalNameNotRecognisedException[source]

Exception raised for when a signal name is not recognized. Check the originating class for a list of supported signal names

class bt_manager.exceptions.BTDeviceNotSpecifiedException[source]

Exception raised for when a device is not specified

exception bt_manager.exceptions.BTRejectedException(*args, **kwargs)[source]

Bases: dbus.exceptions.DBusException

Exception raised to notify that the user rejected a pairing attempt.

exception bt_manager.exceptions.BTInvalidConfiguration(*args, **kwargs)[source]

Bases: dbus.exceptions.DBusException

Exception raised to denote an invalid configuration parameter

exception bt_manager.exceptions.BTIncompatibleTransportAccessType(*args, **kwargs)[source]

Bases: dbus.exceptions.DBusException

Exception raised when attempting to access a media transport file descriptor without correct access permissions.