Automatically connect to a device through Bluetooth

Version 3

    This document will try to exemplify how to create a service that automatically connects an Edison board to an already paired device on boot.


    Before we begin we have to set up the Edison and the device, so in case you haven’t paired the device to your Edison follow these steps:


         1. Enter the command: rfkill unblock bluetooth.


         2. Enter the command: bluetoothctl.


         3. Enter the command: agent DisplayYesNo.


         4. Enter the command: default-agent.


         5. Enter the command: scan on.

             *Wait until you find your device’s MAC address and copy it. Make sure to make your device visible from its settings.


         6. Enter the command: scan off.


         7. Enter the command: pair XX:XX:XX:XX:XX:XX. Where XX:XX:XX:XX:XX:XX represents your device's MAC address.


    *The command exit to closes the bluetoothctl environment.


    Now that the Edison and the device are paired we can get started. The final result of this document will be that your Edison will set up its Bluetooth interface and try to connect to the device previously paired.  In this document we will create a system.d service and a shell script, to set everything automatically.


         1. We will start by creating a shell script. This script  will be very simple and it will contain all the commands that you would use to connect your board manually:


    rfkill unblock bluetooth
    sleep 1
    bluetoothctl << EOF
    connect XX:XX:XX:XX:XX:XX
    sleep 1


    *Remember that XX:XX:XX:XX:XX:XX represents your device's MAC address.


         2. Save the script wherever you want but remember it must end with the .sh extension. Give the file executable rights with the command “chmod +x”.


         3. Now that the shell script is done, we can create the service that will call it. It is also a very simple service, the main feature of this service is that it will set to wait until all other services have been loaded and then it’ll start:


    Description=Sets up the Edison's Bluetooth interface and connects it to a paired device.


         4. Make sure to change the path in ‘ExecStart’ to where you stored your shell script. Name the service whatever you like but remember to add the extension ‘.service’. Store your service in /lib/systemd/system/.


         5. Now you can enable the service with “systemctl enable YOUR_SERVICE.service”.


         6. When you reboot your board the service should automatically connect your Edison to your Bluetooth device.