WelcomeWelcome | FAQFAQ | DownloadsDownloads | WikiWiki

Author Topic: Start Bluetooth and connect to Bluetooth speaker using BlueALSA in PiCore  (Read 1307 times)

Offline CNK

  • Wiki Author
  • Sr. Member
  • *****
  • Posts: 283
These scripts have been tested on a Raspberry Pi Zero W and a Raspberry Pi Zero 2 W for connecting to a Bluetooth speaker automatically using BlueALSA in PiCore 13.

Start Bluetooth and BlueALSA daemon:
You can remove the tce-load line if you're loading these extensions in onboot.lst. When running the first time, make sure the extensions have already been downloaded ("tce-load -w alsa bluez-alsa").

Run this script as root, or with "sudo".
Code: [Select]
#!/bin/ash
# Init Bluetooth.
# Run as root.

sudo -u tc tce-load -i alsa bluez-alsa
modprobe hci_uart
/usr/local/etc/init.d/bluez start
bluealsa -S &

# firmware upload command sometimes times out on the first attempt
until hciattach -t 10 /dev/ttyAMA0 bcm43xx 921600 noflow
do
  echo Retrying hciattach
done
sleep 2
bluetoothctl power on
bluetoothctl scan on &

Try increasing the delays in "sleep 2" or "hciattach -t 10" if it's not working.

Connect to Bluetooth speaker:
This expects a file at /home/tc/btdev_audio.lst containing a new-line separated list of devices that can be connected to (it will only connect to the first one detected). Devices can be identified by either their device name (which might be in the manual), or their mac address.

Create a file like this at /etc/asound.conf and add /etc/asound.conf to your /opt/.filetool.lst:
Code: [Select]
defaults.bluealsa.service "org.bluealsa"
defaults.bluealsa.device ""
defaults.bluealsa.profile "a2dp"

pcm.!default {
 type plug
 slave {
 pcm "bluealsa"
 }
}

Then run this (as root), which will fill in the "device" section above for the speaker that it connects to:
Code: [Select]
#!/bin/ash
# Connect to bluetooth device with mac or ID listed in file
# Run as root.

if [ -s /home/tc/btdev_audio.lst ]
then
echo Searching for bluetooth speakers...
dev=
while [ -z "$dev" ]
do
  sleep 1
  dev="`bluetoothctl devices | grep -f /home/tc/btdev_audio.lst`"
done
mac=`expr "$dev" : 'Device \(..:..:..:..:..:..\) '`
bluetoothctl pair $mac
bluetoothctl connect $mac
sed -i "s/defaults.bluealsa.device \".*\"/defaults.bluealsa.device \"$mac\"/" /etc/asound.conf
fi

As I found out the hard way, you need to either modify /usr/local/etc/dbus-1/system.d/bluealsa.conf (and add it to /opt/.filetool.lst) to allow the "staff" group to access Bluetooth audio, or create an "audio" group and add users to that. Otherwise you'll only be able to play through the speaker from programs running as root.

Test:
The aplay program is an easy basic test, it plays a wav file (here named test.wav):
Code: [Select]
tce-load -i alsa-utils
aplay test.wav

If it's not working, check that "bluealsa" is listed in the output of the command "aplay -L", otherwise maybe the bluealsa daemon failed to start.