Enable Bluetooth after waking up from sleep

After purchasing a new Kinesis Advantage 360 Pro I also got me a TP-Link UB 500 bluetooth dongle. It works fairly good although I do experience some tiny intermittent connection loss from time to time, which becomes obvious as dunst is spitting out notifications about the device losing connection and reconnecting instantly. What was more cumbersome was that the keyboard did not reconnect after continueing from sleep.

The solution was adding a script for systemd to run. Place the following in a file at /usr/lib/systemd/system-sleep/bluetooth

#!/bin/sh
# jeroenb, 2024-02-01
# Unload the btusb module, restart the bluetooth service and reload the module again
# post = after the computer wakes up
case "$1" in
  pre)
    systemctl stop
  post)
    modprobe -r btusb
    sleep 1
    service bluetooth restart
    sleep 1
    modprobe btusb
    ;;
esac

Afterwars, make the script executable:

sudo chmod +x /lib/systemd/system-sleep/bluetooth

More on Github.