Linux bluetooth connection setup from the system’s start

  1. Multichannel keyboard that needed a pin entered (Logitech K480).
  2. JBL Flip Essential 2 bluetooth speaker.

With the keyboard, scan and connect via cli:

bluetoothctl

From the [bluetooth], turn on power, turn on agent and start scanning for devices.

[bluetooth] power on
[bluetooth] agent on
[bluetooth] scan on

Next, pair your keyboard:

pair <mac_address_of_the_keyboard>

When you get prompted a code type it with the keyboard that you are pairing and press enter with it.

At this point, I got a pairing success message. This pairing process also worked with the Blueman applet. But for some reason it was not permanent with my Logitech K480 keyboard. When pairing was done via cli it was permanent and survived a computer reboot. I suspect this being because the gui never asked for any pin, whereas the cli did.

Finally from the cli, I connected my keyboard with:

connect <mac_address_of_the_keyboard>

In the end the cli process was so stable and nice, that I ended up pairing and connecting all my devices via it. Blueman that I had used previously, got removed.

When pairing and connecting was done, I needed to get my bluetooth devices connecting from the system’s startup(automatically). Here is a bash script together with a systemd file to accomplish that:

sudo nano /opt/bluetooth.sh

Script content example:

#!/bin/bash

bluetoothctl trust C8:56:1D:6W:8E:B5
bluetoothctl disconnect C8:56:1D:6W:8E:B5

until bluetoothctl connect C8:56:1D:6W:8E:B5; do echo "Try again"; sleep 6; done

bluetoothctl trust A8:55:1A:6A:5E:B0
bluetoothctl disconnect A8:55:1A:6A:5E:B0

until bluetoothctl connect A8:55:1A:6A:5E:B0; do echo "Try again"; sleep 6; done

#Pulseaudio had trouble seeing the bluetooth speaker. This fixes it.

pactl load-module module-bluetooth-discover

#Keyboard
#C8:56:1D:6W:8E:B5

#Speaker
#A8:55:1A:6A:5E:B0

#Script ends.

Note. The until blocks make sure that the connection establishment is being tried until successful.

Make executable:

sudo chmod +x /opt/bluetooth.sh

Systemd file example:

[Unit]
Description=Bluetooth from the start, blue.service.

#After=network.target

[Service]
Type=oneshot
ExecStart=/opt/bluetooth.sh
RemainAfterExit=true

#ExecStop=/opt/foo/teardown-foo.sh

StandardOutput=journal

[Install]
WantedBy=multi-user.target

Finally, I copied the systemd file to the right place and enabled it during the system startup.

sudo cp blue.service /etc/systemd/system/blue.service
sudo systemctl enable blue

After this, I rebooted and everything was working fine. Note. This solution worked but systemd displayed the blue.service falsely as failed – on the blue service’s status.