Skip to content

Instantly share code, notes, and snippets.

@DamirSvrtan
Last active February 2, 2023 21:58
Show Gist options
  • Save DamirSvrtan/8250695 to your computer and use it in GitHub Desktop.
Save DamirSvrtan/8250695 to your computer and use it in GitHub Desktop.
Bluetooth speaker connection script. Out of convenience written in Ruby.
#!/usr/bin/env ruby
require 'open3'
class NojzError < StandardError
def initialize(msg)
@msg = msg
super(msg)
end
def custom_message
if @msg.include? "org.bluez.Error.NoSuchAdapter: No such adapter"
"PLEASE TURN BLUETOOTH ON"
elsif @msg.include? "org.bluez.Error.Failed: Connect Failed"
"UNABLE TO CONNECT TO CREATIVE D80 SPEAKERS"
else
@msg
end
end
end
class Nojz
BLUETOOTH_MAC_ADDRESS = "00:02:02:33:B1:87"
SINK_NAME = "bluez_sink.00_02_02_33_B1_87"
SOURCE_NAME = "bluez_sink.00_02_02_33_B1_87.monitor"
class << self
def connect_to_speakers
begin
Open3.popen3("bt-audio -c #{BLUETOOTH_MAC_ADDRESS}") do |stdin, stdout, stderr, wait_thr|
errors = stderr.read
raise NojzError.new(errors) unless errors.empty?
adjust_sound_settings
end
rescue NojzError => e
alert e.custom_message
end
end
private
def adjust_sound_settings
set_bluetooth_sink_to_default_sink
set_default_source
set_sink_volume
transfer_sink_inputs_to_bluetooth_sink
end
def set_bluetooth_sink_to_default_sink
`pacmd set-default-sink #{SINK_NAME}`
end
def set_default_source
`pacmd set-default-source #{SOURCE_NAME}`
end
def set_sink_volume
`pacmd set-sink-volume #{SINK_NAME} 0x6000`
end
def transfer_sink_inputs_to_bluetooth_sink
sink_input_indices.each {|sink_input_index| `pacmd move-sink-input #{sink_input_index} #{SINK_NAME}` }
end
def alert(msg)
puts "\033[31m#{msg}\033[0m"
end
def sink_input_indices
sink_inputs = `pacmd list-sink-inputs`
sink_inputs.split("\n").map {|line| line.split(' ').last if line.include? "index"}.compact
end
def turn_bluetooth_on
`rfkill unblock bluetooth`
end
end
end
if ARGV.length == 0 || ARGV[0] == "on"
Nojz.connect_to_speakers
end
@DamirSvrtan
Copy link
Author

Make the script executable:

chmod +x nojz

Add to ~/.bashrc:

export PATH=/home/damir/Desktop/rails_projects/nojz/:$PATH

To be sure sink inputs will be redirected to the new sink, add to the /etc/pulse/default.pa file:

load-module module-stream-restore restore_device=false

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