Package: btsocket
A Python library to interact with Bluez Bluetooth Management API on Linux.
At this time it should be seen as a very early stage proof of concept.
If you are new to Bluetooth this might not be the best library to start withOverviewThis library aims to offer assistance to accessing theBlueZ Bluetooth
Management APIusing Python.
With themgmtAPI there are no commands for reading and writing data on a
connected device.
This library has to have root privilege to access most things.Three LevelsThis library has tried to split things in to the how, what and when. The aim
is by keeping the transport, protocol, and programming paradigm separate a
plug and play approach can be taken. For example, if the Python bug in sockets
gets fixed, just that part can be updated without too much disruption.
It should also be possible to use different programming paradigms (models)
for how commands and responses are handled and still use the socket and
protocol pieces.Socket (How)This library came into being because of a Bug in Python as documented at:https://bugs.python.org/issue36132Python currently does not allow any way to initialize hci_channel, so you
cannot use auser channelsocket and so insteadbtmgmt_socketinbtsocket/btmgmt_socket.pyaccesses theuser channelby using the
underlying libc socket.Protocol (What)The filebtsocket/btmgmt_protocol.pyis to assist in encoding and decoding
the binary format that is used to communicateThis module assists in encoding and decoding the binary dataProgramming Paradigm (When)Handling communication with the sockets can be done a number of different ways
and there are trade-offs for each of them. Initially this library is supporting
two types. A procedural approach withbtsocket/btmgmt_sync.pyand
a callback (or event-driven) approach withbtsocket/btmgmt_callback.py.For actions like turning the controller on and off then these can be done
with either methodology. For listening for async events like the discovery
of devices, then only the callback model is practical.CommandsFor the vast majority of the commands, the process of creating the
mgmt socket is required to have the CAP_NET_ADMIN capability
(e.g. root/sudo would have this).The documentation for commands is at:https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/mgmt-api.txtThat documentation has been used to auto-generate parts ofbtmgmt_protocol.pyTo take one command as an example; powered command:Set Powered Command
===================

    Command Code:           0x0005
    Controller Index:       <controller id>
    Command Parameters:     Powered (1 Octet)
    Return Parameters:      Current_Settings (4 Octets)To power-on adapter at index zero, the following command would be sent with the
synchronous APIfrombtsocketimportbtmgmt_syncresponse=btmgmt_sync.send('SetPowered',0,1)The format of thesendcommand is :response = send(<command_name>, <adapter index>, <positional paramters>)The command name is taken from the heading in the documentation with the spaces
and the word “Command” removed. A typical response is given below:Response(
    header=<
        event_code=CommandCompleteEvent,
        controller_idx=0,
        param_len=7>,
    event_frame=<
        command_opcode=SetPowered,
        status=Success>,
    cmd_response_frame=<
        current_settings=2752>)An example of the Python to access the values in the response is:print(response.event_frame.command_opcode,response.event_frame.status)Callbacks on EventsThe structure for running with callbacks on events is below.Getting the event loop and running until complete should be familiar to
regular users of asyncio.mgmt = btmgmt_callback.Mgmt()sets up the sockets and the readers and writers
to the sockets.mgmt.add_event_callbacktakes two arguments, the first is the btmgmt event
and the second is the callback function to use when that event is detected.mgmt.sendis how to send commands and is similar to the synchronous API
except it doesn’t get a response. You will have to add an event callback to
access the response.
The command(s) are not sent untilmgmt.start()as this is what
starts the writers and readers of the sockets.frombtsocketimportbtmgmt_callbackfrombtsocketimportbtmgmt_protocoldefdevice_found(response,mgmt_obj):print('New device found',response.event_frame.address)# To exit set running to Falsemgmt_obj.stop()defapp():mgmt=btmgmt_callback.Mgmt()mgmt.add_event_callback(btmgmt_protocol.Events.DeviceFoundEvent,device_found)mgmt.send('StartDiscovery',0,[btmgmt_protocol.AddressType.LEPublic,btmgmt_protocol.AddressType.LERandom,btmgmt_protocol.AddressType.BREDR])mgmt.start()if__name__=='__main__':app()There are more examples in the examples folder