Skip to content

Instantly share code, notes, and snippets.

@RamonGilabert
Last active October 12, 2023 18:24
Show Gist options
  • Save RamonGilabert/046727b302b4d9fb0055 to your computer and use it in GitHub Desktop.
Save RamonGilabert/046727b302b4d9fb0055 to your computer and use it in GitHub Desktop.
Bluetoothctl automation
#!/usr/bin/expect -f
set prompt "#"
set address [lindex $argv 0]
spawn sudo bluetoothctl -a
expect -re $prompt
send "remove $address\r"
sleep 1
expect -re $prompt
send "scan on\r"
send_user "\nSleeping\r"
sleep 5
send_user "\nDone sleeping\r"
send "scan off\r"
expect "Controller"
send "trust $address\r"
sleep 2
send "pair $address\r"
sleep 2
send "0000\r"
sleep 3
send_user "\nShould be paired now.\r"
send "quit\r"
expect eof
@NeonLightning
Copy link

No PIN in my case, it just asks if I accept pairing, have to type yes. I've come to this:

#!/usr/bin/expect -f

set timeout 5

spawn bluetoothctl

set address [lindex $argv 0]
set pairExecuted 0

# Defines procedure (function) `pair`, `address` is the parameter
proc pair {address} {
  send "scan on\n"
  sleep 3
  send "scan off\n"

  send "pair $address\n"
}

send "agent on\n"
send "power on\n"
expect "Changing power on succeeded" {
  send "devices\n"
  expect "Device ${address}" {
    send "remove ${address}\n"

    expect "Device has been removed" {

      # Calls procedure `pair` passing `address` as argument (defined at the top)
      puts [pair ${address}]

      # Increments `pairExecuted` variable, so the next
      # check (if statement below) will know this has already been executed
      incr pairExecuted
    }
  }

  # Checks if the pair procedure has not yet been executed
  # this avoids executing it twice
  # in other words: if procedure `pair` not yet executed, execute it
  if {$pairExecuted == 0}
    puts [pair ${address}]
  }
}

expect "Accept pairing (yes/no):" { send "yes\n" }
expect "Pairing successful" { send "exit\n" }

expect eof

About the language used here: https://www.tcl-lang.org/

i can't seem to use it. i get
": no such file or directory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment