Skip to content

Instantly share code, notes, and snippets.

Created March 31, 2017 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8f6058df9a879292bc8dbd3aaf26077c to your computer and use it in GitHub Desktop.
Save anonymous/8f6058df9a879292bc8dbd3aaf26077c to your computer and use it in GitHub Desktop.
Ubuntu BT speakers/headphones connection script.
#!/usr/bin/env ruby
require 'open3'
require 'io/wait'
# :readline will block if there is no input available, while :readX will raise an error; in order
# to solve this problem easily, the 'io/wait' library makes `IO#ready?` available.
#
def read_available_io(io)
buffer = ''
buffer << io.readchar while io.ready?
buffer
end
def connect_bt(bt_id, btctl_in, btctl_out)
loop do
btctl_in.puts("connect #{ bt_id }")
while true
output = read_available_io(btctl_out)
puts output if output != ''
case output
when /Connection successful/
puts
return
when /Failed to connect/
break
else
sleep 0.5
end
end
end
end
def disconnect_bt(bt_id, btctl_in, btctl_out)
loop do
btctl_in.puts("disconnect #{ bt_id }")
while true
output = read_available_io(btctl_out)
puts output if output != ''
# Disconnection will always be successful, when the device is available.
#
case output
when /Successful disconnected/
puts
return
when /Device [0-9A-F:] not available/
raise "Dafuq!!"
else
sleep 0.5
end
end
end
end
def set_pa_card_profile(card, profile)
puts "Setting PA card profile: #{ profile }"
Open3.popen3("pactl set-card-profile #{ card } #{ profile }") do |_, _, stderr, wait_thread|
if ! wait_thread.value.success?
puts stderr.readlines.join
exit
end
end
puts
end
def mad_connect_headphones(bt_id, pa_card_name)
Open3.popen3('bluetoothctl') do |stdin, stdout, _, _|
puts read_available_io(stdout)
connect_bt(bt_id, stdin, stdout)
set_pa_card_profile(pa_card_name, 'off')
disconnect_bt(bt_id, stdin, stdout)
connect_bt(bt_id, stdin, stdout)
set_pa_card_profile(pa_card_name, 'a2dp_sink')
end
end
# Use `pactl list cards` for informations about the cards.
#
BLUETOOTH_ID = 'set me!'
PULSEAUDIO_CARD_NAME = 'set me!'
if __FILE__ == $0
mad_connect_headphones(BLUETOOTH_ID, PULSEAUDIO_CARD_NAME)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment