Using Raspberry Pi 3’s Bluetooth in Docker
In my previous post, I talked about how I set up my new Raspberry Pi 3 with Ansible to lay a foundation that included Docker. In the first project I wanted to tackle with my Pi, I needed to use Bluetooth. Since I’ve never used Bluetooth before, I had to do some digging. With this post, I hope to save other people like me some time. Most will still be relevant even if Docker isn’t involved.
The Project
Since the Raspberry Pi 3 has onboard Bluetooth, I figured a good introductory project would include detecting when me and other family members are at my house. With IFTTT, I can easily trigger a multitude of things, including setting my thermostat to away.
Docker
Once I got Docker running, the next step is to find a Docker image that will run on ARM. Most Docker images won’t work since they’re built for other architectures. Thankfully, resin.io has some public images to get us started. I chose to run resin/rpi-raspbian:jessie. Running it is as simple as docker run -it --net host resin/rpi-raspbian:jessie.
Installation
From here, I needed to install a whole bunch of things: Bluetooth libraries and tools, Python, and other dependencies that were a bit of a pain to track down. While the Pi 3 is much more powerful than its predecessors, the amount of things that need to be compiled makes installing things take a little while.
The first step is to retrieve new lists of packages (apt-get update). Then, it’s a long list of packages: apt-get install -y build-essential bluez bluez-tools python-dev python-pip libglib2.0-dev libboost-python-dev libboost-thread-dev libbluetooth-dev. From left to right, I’m installing build tools for all the compiling, the official Linux Bluetooth stack Bluez, Python, and a lot of dependencies for the Python packages I’ll be installing. Those Python packages are PyBluez and gattlib (pip install pybluez gattlib), which gives us Bluetooth support.
Execution
With PyBluez, my goal of determining whether I’m at home is actually very easy. To get my mobile’s Bluetooth address, I needed to put it into discovery mode. Then in a Python shell,
Now that I have the address and name of my device, I can save that for later. As long I keep Bluetooth on, I can look it up whenever I want.
Putting It All Together
Installation of all those dependencies can take a while. To alleviate that, I’ve built all of them into a Docker image geowa4/rpi-blue-python. From here, I will likely run this program on a timer and write the number of known inhabitants to Adafruit IO or directly to IFTTT’s Maker channel to do something useful.