Skip to content

Instantly share code, notes, and snippets.

@mwvent
Created January 30, 2019 14:49
Show Gist options
  • Save mwvent/0d4e75a226bee1e621daadcee55adf2f to your computer and use it in GitHub Desktop.
Save mwvent/0d4e75a226bee1e621daadcee55adf2f to your computer and use it in GitHub Desktop.
Bluetooth Speaker Auto connect service - for running in BG when autologging in on Kodi, replace USERGID and USERNAME with autologin user
#/etc/systemd/system/bluetoothbulb_connector.service
[Unit]
Description=BluetoothBulbConnector
After=network.target
[Path]
PathExists=/run/user/1000
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=USERNAME
WorkingDirectory=/home/USERNAME
ExecStart=/home/USERNAME/Scripts/bluetoothbulb_connector_service/bluetoothbulb_connector_service.sh
Restart=always
#!/bin/bash
# /home/USERNAME/Scripts/bluetoothbulb_connector_service/bluetoothbulb_connector_service.sh
LIGHTMAC=F4:4E:FD:B2:7C:36
LIGHTSINKNAME_MAC="F4_4E_FD_B2_7C_36"
LIGHTSINKNAME=""
ISCONNECTED=1
while :; do
HCIDEVICE=$(hcitool dev | grep -v "Devices" | column -t | cut -d " " -f1 | head -n1)
export PULSE_SERVER=$(DISPLAY=:0 xprop -root PULSE_SERVER | cut -d '"' -f2)
export XDG_RUNTIME_DIR="/run/user/USERGID"
LIGHTSINKNAME=$(pacmd list-sinks | grep "$LIGHTSINKNAME_MAC" | grep "name" | cut -d "<" -f2 | cut -d ">" -f1)
if [ -z "$LIGHTSINKNAME" ]; then
if [ "$ISCONNECTED" -eq 1 ]; then
echo "Bulb connection down - trying to reconnect"
ISCONNECTED=0
fi
echo "scan on
pair $LIGHTMAC
connect $LIGHTMAC" | bluetoothctl &> /dev/null
sleep 2
LIGHTSINKNAME=$(pacmd list-sinks | grep "$LIGHTSINKNAME_MAC" | grep "name" | cut -d "<" -f2 | cut -d ">" -f1)
if [ ! -z "$LIGHTSINKNAME" ]; then
echo "Reconnected to bulb"
ISCONNECTED=1
pacmd set-default-sink $LIGHTSINKNAME
for playing in $(pacmd list-sink-inputs | awk '$1 == "index:" {print $2}'); do
pacmd move-sink-input $playing $LIGHTSINKNAME >/dev/null 2>&1
done
fi
fi
sleep 2
done
#/etc/systemd/system/bluetoothbulb_connector.path
[Path]
PathExists=/run/user/USERGID
Unit=bluetoothbulb_connector.service
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment