You are not logged in.

#1 2021-09-30 16:39:33

7thSon
Member
Registered: 2017-05-07
Posts: 178

[SOLVED] How to script device detection with bluetootctl scan

I'm trying to write a script that interacts with bluetoothctl so that I do these steps:

1. Disable one of 2 controllers (I have builtin BT as well as a dongle, I want to use the dongle)
2. Scan for devices, until a specific headset is found
3. Pair with the device after it's found
4. Trust the device after pairing

I'm especially looking at step 2 since the behavior of bluetoothctl makes it a bit tricky.
Running `bluetoothctl scan on` starts the application, but the output doesn't stop until I exit out with ctrl-c, and is not possible to grep.
Are there any methods/workarounds that I could use to be able to essentially do some equivalent of `bluetoothctl scan on | grep XX:XX:XX:XX:XX:XX`, so that I can wait only until the device is detected, and then proceed with the rest of the commands?
For instance, does bluetoothctl write the scan results to a temporary file that could be checked for the mac address?

Last edited by 7thSon (2021-09-30 17:23:53)

Offline

#2 2021-09-30 17:23:38

7thSon
Member
Registered: 2017-05-07
Posts: 178

Re: [SOLVED] How to script device detection with bluetootctl scan

I can answer my own question here after some lucky research.
The tool to use here is `expect`, which allows me to interact exactly like I want to with the bluetoothctl console:

#!/usr/bin/env bash

device="00:1B:66:88:1D:52"
/usr/bin/expect <(
	cat <<EOF
set timeout 60
spawn bluetoothctl
send -- "scan on\r"
expect "$device"
send -- "pair $device\r"
expect "Pairing successful"
send -- "connect $device\r"
expect "Connection successful"
send -- "trust $device\r"
expect "trust succeeded"
send -- "exit\r"
expect eof
EOF
)

Offline

#3 2021-09-30 18:13:12

Raynman
Member
Registered: 2011-10-22
Posts: 1,312

Re: [SOLVED] How to script device detection with bluetootctl scan

Unnecessarily ugly/complex, though. Better would be

#!/usr/bin/env bash

device="00:1B:66:88:1D:52"
/usr/bin/expect -f - <<EOF
# ...
EOF

But Tcl has variables too, so you don't need bash at all:

#!/usr/bin/expect -f

set device "00:1B:66:88:1D:52"
# ...

Offline

#4 2021-09-30 18:34:52

7thSon
Member
Registered: 2017-05-07
Posts: 178

Re: [SOLVED] How to script device detection with bluetootctl scan

Raynman wrote:

Unnecessarily ugly/complex, though. Better would be

#!/usr/bin/env bash

device="00:1B:66:88:1D:52"
/usr/bin/expect -f - <<EOF
# ...
EOF

But Tcl has variables too, so you don't need bash at all:

#!/usr/bin/expect -f

set device "00:1B:66:88:1D:52"
# ...

Ah thanks, I was just following along with some examples, so didn't really dive into the capabilities of expect.
I'll be sure to update this to simplify it!

Offline

Board footer

Powered by FluxBB