Getting Started¶
This page is dedicated to writing your first file that uses ABle, we will go through some steps that will serve as a placeholder for templates in the rest of the programming guide.
Setup¶
We need to do a couple things to get started with developing with ABle, all the other examples will fit into this template so this is the place to be before looking at the other examples. First we need to import some much needed packages. Do note that your needs might not require all of the ABle modules, but we included them to be safe.
# Native libraries
import asyncio
import logging
# Able modules
from able.advertisement import ABleAdvertisement
from able.peripheral import ABlePeripheralServer
from able.central import ABleCentral
The next two imports are where some magic happen, you may have noticed that the ABleService and ABleCharacteristic top level classes are a little bland, that is because there are implementations of subclasses of those classes written for each platform ABle supports and you can import the one for your platform automatically from ABle.
from able import ABleCharacteristic
from able import ABleService
Once our main libraries are setup, let’s setup logging, Able uses the python loggers for all of it’s logging, so if you want to see what ABle is doing, let’s configure the loggers (feel free to change the format).
logging.basicConfig(
level=logging.DEBUG, format="[%(levelname)8s] (%(filename)s:%(lineno)s) %(message)s"
)
Main Loop¶
Now we have to dance with asyncio, because ABle uses asynchronous functions in it’s backends, we need to define our main() function to be async and run it in an event loop. For now main will be empty, but we’ll come back to that.
Caution
Calling asyncio.run() directly is only supported in Python 3.7+, in older versions of python you need to run asyncio.get_event_loop().run_until_complete(main())
async def main():
if __name__ == "__main__":
asyncio.run(main())
At this point, your code should have some imports, logging config, and a main function that will be ran but leaves a lot to be desired, let’s get that fixed in this last step. Update the body of the main function with the following code to initialize a BLE peripheral server and start it.
async def main():
# Create an able peripheral
able_peripheral = ABlePeripheralServer()
await able_peripheral.setup_peripheral_server()
... # Replace Me
# Start the server
await able_peripheral.listen()
At this point your file should be able to run, (if you experience some permissions issues check out our troubleshooting guide) but this server won’t advertise quite yet, let’s fix that in the advertising guide…
Warning
If running this script fails because of a DBus error talking about not allowed to own the service, check out the this section in the Troubleshooting guide: Ownership Error.