Connection Guide ================ Connections are another core part of ABle, here will will introduce some examples on how to use ABle to handle BLE connections. We modeled the API after the Berkeley Socket API, so if you have worked with sockets this should be familiar. .. Tip:: We highly suggest looking at the :doc:`getting started doc<./getting_started>` and the :doc:`advertising guide<./advertising>` before looking at this guide as you need to be setup and advertising before you can connect. Simple Connections ++++++++++++++++++ Using the stencil provided by the getting started guide, we can now accept connections after calling `listen()` on the peripheral. This will block on the `accept()` call until a central connects wait five seconds, then disconnect the central. .. code-block:: python3 # Start the peripheral server await able_peripheral.listen() while True: # Block here until a connection new_central = await able_peripheral.accept() print(f"New connection from {new_central}") # Wait 5 seconds then disconnect await asyncio.sleep(5) await new_central.close() .. Tip:: See the :doc:`development doc (todo Bernie)` for useful tools for testing this by leveraging your phone to scan for the peripheral and connect to it. Clientside Disconnecting ************************ Notice that the above demonstrates how a server (the peripheral) would disconnect using the `close()` method. If a central/client initiates the disconnect, any IO operation to that central will raise an exception and calling `central.close()` will log a warning and do nothing if the central already disconnected. (Dis)connect Callbacks ++++++++++++++++++++++ It is easy to define callbacks to fire whenever a central connects or disconnects with Able. Simply before calling `listen()` we can bind a callback function, let's define some callback functions. .. code-block:: python3 def connect_callback(callback_data): print("Connected to a central yippee!") def disconnect_callback(callback_data): print("Disconnected from a central :(") These functions will be passed an instance of `DeviceCallbackData` which can be used to get information regarding which central connected or disconnected. We can now add these callback functions to the peripheral. .. code-block:: python3 # Add user defined callbacks able_peripheral.add_connect_callback(connect_callback) able_peripheral.add_disconnect_callback(disconnect_callback) Now whenever a central connects or disconnects those callbacks will be called.