Skip to content

Instantly share code, notes, and snippets.

@EHfive
Forked from hxss/20-bt-auto-enable-a2dp.rules
Last active March 8, 2021 08:21
Show Gist options
  • Save EHfive/c4f1218a75f95b076f0387403246de78 to your computer and use it in GitHub Desktop.
Save EHfive/c4f1218a75f95b076f0387403246de78 to your computer and use it in GitHub Desktop.
Udev service for temporary solve bug 92102 https://bugs.freedesktop.org/show_bug.cgi?id=92102
# /etc/udev/rules.d/20-bt-auto-enable-a2dp.rules
# hxss
SUBSYSTEM=="bluetooth", ACTION=="add", RUN+="/home/replace-it/bt-auto-enable-a2dp.sh"
#!/bin/sh
# Dependencies:
# * bluez-tools
# * expect
# * perl
export PATH='/usr/bin:/usr/local/bin:/usr/sbin:/usr/local/sbin:'$PATH
function enable_a2dp() {
# run connect command in bluetoothctl and wait for resolve of services
expect <<< "
spawn bluetoothctl
send \"connect $mac\r\"
log_user 0
expect -re \".*Device $mac ServicesResolved: yes\"
"
# enable card in pulseaudio
a2dp_profiles=(
'a2dp_sink_ldac'
'a2dp_sink_aptx_hd'
'a2dp_sink_aptx'
'a2dp_sink_aac'
'a2dp_sink_sbc'
'a2dp_sink' )
for profile in "${a2dp_profiles[@]}"
do
if [[ `pactl list cards | grep ${profile}` ]]; then
pactl set-card-profile $pulsecard ${profile} && break
fi
done
logger -p info "mac $mac enabled"
headsetname=`bt-device -l | perl -ne '/(.*) \('$mac'\)/ and print "$1\n"'`
notify-send 'Headset connected' "$headsetname" --icon=blueman-headset
}
function search_headsets() {
sleep 1
# in all added devices
for mac in `bt-device -l | perl -ne '/.*\((.*)\)/ and print "$1\n"'`
do
# search for connected device with AudioSink service
if [[ `bt-device -i $mac | perl -00 -ne '/.*Trusted: 1.*\n\s*Blocked: 0.*\n\s*Connected: 1\n\s*UUIDs: .*AudioSink.*/ and print "1\n"'` ]]; then
logger -p info "found mac: $mac"
# convert mac to pulse card name
pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`
enable_a2dp
fi
done
echo "search done"
}
logger -p info "${BASH_SOURCE[0]}"
# get script owner name
user=`stat -c %U $0`
if [ "$user" == `whoami` ]; then
# if script runned by owner - start main function
search_headsets
elif [ "`w -hs $user`" ]; then
# else if user session exist(to prevent running on system startup) - run script from user
machinectl shell $user@.host ${BASH_SOURCE[0]}
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment