3

I'm trying to automate the pairing of my headset to my ubuntu16 machine.

I took this nice script and tried it, but it didn't work. I played around a bit, and found out that I can just work with this minimal script:

#!/usr/bin/expect -f

set prompt '#' set address [lindex $argv 0]

spawn bluetoothctl &> /dev/null expect -re $prompt send "\nconnect <my_mac_addr>\r" sleep 10

I save this as a ./bluetooth.sh and run it with ./bluetooth.sh & and it works like a charm. However, I get this annoying bluetoothctl output:

[NEW] Controller *** ### [default]
[NEW] Device *** A
[NEW] Device *** B
[NEW] Device *** C
[bluetooth]# 

I tried removing it with the redirection I added to the spawn command, but it didn't help as you can see...

Removing the expect would work, but I'm not sure this is the way to go...

2 Answers2

3

You don't really need to use expect and can give commands to bluetoothctl directly as arguments.

# ...
bluetoothctl -- power on
bluetoothctl -- connect $mac
# ...

For a more complete example, here is the full Bash script that I use in Ubuntu 20.04 for my BT radio :

#!/bin/bash

mac="90:03:B7:17:00:08" # DEH-4400BT

if [ "$1" = "off" ]; then bluetoothctl -- disconnect exit $? fi

turn on bluetooth in case it's off

rfkill unblock bluetooth

bluetoothctl -- power on bluetoothctl -- connect $mac

Use it as default output for PulseAudio

sink=$(pactl list short sinks | grep bluez | awk '{print $2}')

if [ -n "$sink" ]; then pacmd set-default-sink "$sink" && echo "OK default sink : $sink" else echo could not find bluetooth sink exit 1 fi

This assumes the destination $mac is already paired of course.

mivk
  • 5,811
0

Capture the output and strip the prompts...

typeset -a OUTPUT

clean_line () { local LINE

while read LINE;do echo ${LINE} | perl -pe 's/\x1b[[0-9;][mG]//g; s/[.]#?//g; s/\x0d\x1b\x20\x0d\x1b\x5b\x4b//g; s/^ //g' done }

coproc bluetoothctl echo -e 'agent on\nconnect 00:0C:8A:FE:ED:18\nexit' >&p OUTPUT=("${(f)$(cat <&p | clean_line)}")

NDX=0 for L in ${OUTPUT};do ((NDX++)) printf "%d) %s\n" ${NDX} ${L} done

YMOZ
  • 125