Connect to bluetooth device from command lineHow can I change the default audio device from command line?How do I connect to my Bluetooth headset?Autoconnecting Bluetooth Devicesplay audio through bluetooth speakers in 12.04 using CLIError while connecting A2DP device, Bluetooth BlueZ Dbus Exception Ubuntu12.04LTSCan't enable Bluetooth. `sudo rfkill unblock bluetooth` does not helpBluetooth speaker via ALSAReconnect to a previously paired bluetooth mouse from command lineShouldn't Blueman manager tray applet list paired bluetooth devices (with option to connect)?How to troubleshoot Bluetooth connection with headset?Reconnect to a previously paired bluetooth mouse from command lineBluetooth connection - will not auto pair/reconnect to audio deviceHow to unpair bluetooth device from the command lineHow to show battery percentage of a Bluetooth connected gadget (headphone)Stream audio from PC to bluetooth headset via android phoneConnect Bluetooth 4.0 Headset
Can a Tiefling be born from two human parents?
Two super-button calculator
Why were early PC 3D cards unsuitable for 2D graphics?
Is there a coup going on in Bolivia?
Are there any (natural) scientists in Middle-earth?
Why do airline tickets have titles in addition to names?
What is the maximum distance you can cause damage from?
Why does Rome municipality seem to have a hard time maintaining the city?
Intersection of four circles
Does the German President's apology for WWII reflect the views of the people of Germany?
Ideal Firearms for time travel or low tech universe exploration
Why does the media continue to hide the identity of the Trump-Ukraine whistle blower when they have already been outed?
What is QED about "Cavity QED"?
Is there any convention about the form IDs?
Is there a bulletproof way to know a file has been successfully decrypted?
What is the scientific term to describe the operation of a bong?
Did any astronauts on a mission complain about waking up?
Expand a recursive pattern
How do impulse response guitar amp simulators work?
Water Jug Problem in AI
What superheroes have worked for the Daily Bugle in the comics?
What's the difference between "can't move" and "speed becomes 0"?
Responding to social invitations with autism
Why does radiocarbon dating only work in nonliving creatures?
Connect to bluetooth device from command line
How can I change the default audio device from command line?How do I connect to my Bluetooth headset?Autoconnecting Bluetooth Devicesplay audio through bluetooth speakers in 12.04 using CLIError while connecting A2DP device, Bluetooth BlueZ Dbus Exception Ubuntu12.04LTSCan't enable Bluetooth. `sudo rfkill unblock bluetooth` does not helpBluetooth speaker via ALSAReconnect to a previously paired bluetooth mouse from command lineShouldn't Blueman manager tray applet list paired bluetooth devices (with option to connect)?How to troubleshoot Bluetooth connection with headset?Reconnect to a previously paired bluetooth mouse from command lineBluetooth connection - will not auto pair/reconnect to audio deviceHow to unpair bluetooth device from the command lineHow to show battery percentage of a Bluetooth connected gadget (headphone)Stream audio from PC to bluetooth headset via android phoneConnect Bluetooth 4.0 Headset
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
Background: I'm using my bluetooth headset as audio output. I managed to get it working by the long list of instructions on BluetoothHeadset community documentation, and I have automated the process of activating the headset as default audio output into a script, thanks to another question.
However, since I use the bluetooth headset with both my phone and computer (and the headset doesn't support two input connections) in order for the phone not to "steal" the connection when handset is turned on, I force the headset into a discovery mode when connecting to the computer (phone gets to connect to it automatically).
So even though the headset is paired ok and would in "normal" scenario autoconnect, I have to always use the little bluetooth icon in the notification area to actually connect to my device (see screenshot).
What I want to avoid: This GUI for connecting to a known and paired bluetooth device:
What I want instead: I'd want to make the bluetooth do exactly what the clicking the connect item in the GUI does, only by using command line. I want to use command line so I can make a single keypress shortcut for the action, and would't need to navigate the GUI every time I want to establish a connection to the device.
The question: How can I attempt to connect to a specific, known and paired bluetooth device from command line?
Further question: How do I tell if the connection was successful or not?
command-line bluetooth
add a comment
|
Background: I'm using my bluetooth headset as audio output. I managed to get it working by the long list of instructions on BluetoothHeadset community documentation, and I have automated the process of activating the headset as default audio output into a script, thanks to another question.
However, since I use the bluetooth headset with both my phone and computer (and the headset doesn't support two input connections) in order for the phone not to "steal" the connection when handset is turned on, I force the headset into a discovery mode when connecting to the computer (phone gets to connect to it automatically).
So even though the headset is paired ok and would in "normal" scenario autoconnect, I have to always use the little bluetooth icon in the notification area to actually connect to my device (see screenshot).
What I want to avoid: This GUI for connecting to a known and paired bluetooth device:
What I want instead: I'd want to make the bluetooth do exactly what the clicking the connect item in the GUI does, only by using command line. I want to use command line so I can make a single keypress shortcut for the action, and would't need to navigate the GUI every time I want to establish a connection to the device.
The question: How can I attempt to connect to a specific, known and paired bluetooth device from command line?
Further question: How do I tell if the connection was successful or not?
command-line bluetooth
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52
add a comment
|
Background: I'm using my bluetooth headset as audio output. I managed to get it working by the long list of instructions on BluetoothHeadset community documentation, and I have automated the process of activating the headset as default audio output into a script, thanks to another question.
However, since I use the bluetooth headset with both my phone and computer (and the headset doesn't support two input connections) in order for the phone not to "steal" the connection when handset is turned on, I force the headset into a discovery mode when connecting to the computer (phone gets to connect to it automatically).
So even though the headset is paired ok and would in "normal" scenario autoconnect, I have to always use the little bluetooth icon in the notification area to actually connect to my device (see screenshot).
What I want to avoid: This GUI for connecting to a known and paired bluetooth device:
What I want instead: I'd want to make the bluetooth do exactly what the clicking the connect item in the GUI does, only by using command line. I want to use command line so I can make a single keypress shortcut for the action, and would't need to navigate the GUI every time I want to establish a connection to the device.
The question: How can I attempt to connect to a specific, known and paired bluetooth device from command line?
Further question: How do I tell if the connection was successful or not?
command-line bluetooth
Background: I'm using my bluetooth headset as audio output. I managed to get it working by the long list of instructions on BluetoothHeadset community documentation, and I have automated the process of activating the headset as default audio output into a script, thanks to another question.
However, since I use the bluetooth headset with both my phone and computer (and the headset doesn't support two input connections) in order for the phone not to "steal" the connection when handset is turned on, I force the headset into a discovery mode when connecting to the computer (phone gets to connect to it automatically).
So even though the headset is paired ok and would in "normal" scenario autoconnect, I have to always use the little bluetooth icon in the notification area to actually connect to my device (see screenshot).
What I want to avoid: This GUI for connecting to a known and paired bluetooth device:
What I want instead: I'd want to make the bluetooth do exactly what the clicking the connect item in the GUI does, only by using command line. I want to use command line so I can make a single keypress shortcut for the action, and would't need to navigate the GUI every time I want to establish a connection to the device.
The question: How can I attempt to connect to a specific, known and paired bluetooth device from command line?
Further question: How do I tell if the connection was successful or not?
command-line bluetooth
command-line bluetooth
edited Apr 13 '17 at 12:23
Community♦
1
1
asked Jun 10 '11 at 8:23
Ilari KajasteIlari Kajaste
4201 gold badge5 silver badges19 bronze badges
4201 gold badge5 silver badges19 bronze badges
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52
add a comment
|
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52
add a comment
|
4 Answers
4
active
oldest
votes
Bluetooth daemon
In the default installation a daemon (bluetoothd) runs in the background (run from the file /etc/init.d/bluetooth
). This daemon takes care on recognizing and connecting to known bluetooth devices and may be cofigured with configuration files in /etc/bluetooth
. For autoconneting a headset the following line in audio.conf
should be uncommented (remove #
):
AutoConnect=true
To restart the daemon type sudo /etc/init.d/bluetooth restart
.
Remark: Using the command line tool sudo hcitool cc <MAC-Adress>
did not lead to a stable connection to a known device in the test environment here when the daemon was running.
DBus
In order to connect a disconnected but physically present and paired headset we can use D-Bus from a script. Here's an example in python:
#!/usr/bin/python
# Toggles headset connection
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
#Get dbus interface for headset
manager = bus.get_object('org.bluez', '/')
iface_m = dbus.Interface(manager, 'org.bluez.Manager')
adapterPath = iface_m.DefaultAdapter()
adapter = bus.get_object('org.bluez', adapterPath)
iface_a = dbus.Interface(adapter, 'org.bluez.Adapter')
devicePath = iface_a.ListDevices()[0] # assuming first device
device = bus.get_object('org.bluez', devicePath)
iface_h = dbus.Interface(device, 'org.bluez.Headset')
#Check state of connection
connected = iface_h.IsConnected()
print 'Toggling connection. Please wait'
# toggle connection
if not connected:
try:
iface_h.Connect()
print 'Connecting: ', devicePath
except:
print 'Device not found'
else:
iface_h.Disconnect()
print 'Disconnecting: ', devicePath
In case we have more than one Bluetooth device we will have to adapt the devicePath
appropriately, of course. The example above will connect a Headset
. Change the interface to a different protocol for any other service (e.g. AudioSink
).
Pulseaudio
If you know the MAC adress of your Bluetooth device you can connect it as an output sink for pulseaudio by:
pacmd set-default-sink bluez_sink.xx_xx_xx_xx_xx_xx
Where xx_xx_xx_xx_xx_xx is the MAC address (replace ':' by '_' for pulseaudio to recognize it).
See also this answer for more details.
I do know the address, and I replaced the xx with it. I only getSink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.
– Ilari Kajaste
Jun 10 '11 at 8:56
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matchingbt
orblue
is listed inpacmd list-sinks
. (It reports only 1 sink available.)
– Ilari Kajaste
Jun 10 '11 at 9:29
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
|
show 13 more comments
I use this script to connect my Bluetooth Audio Device. If your headset is already paired, you should be able to connect your headset in the same way using org.bluez.Headset.Connect/Disconnect in place of org.bluez.Audiosink.Connect/Disconnect.
#!/bin/bash
MAC_ADD="C8:84:47:10:11:CD"
MAC_ADD="dev_$MAC_ADD//:/_"
BT_ADAPTER=`dbus-send --system --print-reply --dest=org.bluez /
org.bluez.Manager.DefaultAdapter|awk '/object path/ print $3'`
BT_ADAPTER="$BT_ADAPTER//"//$MAC_ADD"
echo "Connecting to $BT_ADAPTER..."
if [ "$1" == "on" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Connect
elif [ "$1" == "off" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Disconnect
fi
HTH!
this worked for me too on16.04
, thank you! others, do not forget to passon
option to the script!
– MInner
Jun 30 '17 at 5:58
add a comment
|
I use i3 as a window manager so I do not have the bluetooth tray icon available. For some reason the check button in unity settings is not sensitive and so I need a way to do this from time to time when my headphones don't connect.
It seems that bluez
has changed their dbus API. The answer utilizing org.bluez.Manager
no longer appears to work. Instead, it is recommended to use ObjectManager
.
Here is an updated python script which will connect the first unconnected bluetooth headset that it finds (presumably the list includes all paired devices?):
#!/usr/bin/env python
# Toggles headset connection
from __future__ import print_function
from __future__ import unicode_literals
import dbus
from dbus.mainloop.glib import DBusGMainLoop
def find_headset(bus):
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.items():
if ("org.bluez.Device1" in ifaces and
"org.freedesktop.DBus.Properties" in ifaces):
iprops = dbus.Interface(
bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = iprops.GetAll("org.bluez.Device1")
# Looking for a headset. Could also match on other properties like
# "Name". See bluez docs for whats available.
if props.get("Class") == 0x240404:
if props.get("Connected"):
print("Found headset () but it is already connected"
.format(props.get("Name"), props.get("Address")))
continue
return path
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
hpath = find_headset(bus)
if hpath:
adapter = dbus.Interface(
bus.get_object("org.bluez", hpath), "org.bluez.Device1")
adapter.Connect()
this example, like the other example on this thread, uses the dbus
python package. On ubuntu 16.04 I installed this through apt-get install python-dbus
.
If you wish to match other criteria, this document appears to show a list of properties that can be queried over dbus.
I have this script saved in ~/.local/bin/bt-connect-headset
which is on my PATH
so I can execute it from the i3 launcher. Make it executable (chmod +x bt-connect-headset
) if you plan to use it as a command.
This script has only been tested on an up-to-date ubuntu 16.04 as of 09/28/2018.
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of2360344
instead of0x240404
.
– dom_watson
Nov 29 '18 at 21:40
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use theDisconnect()
method. I haven't tried it, but it's probably a safe bet ;).
– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you sayfirst unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line toadapter.Disconnect()
.)
– cipricus
Sep 2 at 11:33
|
show 1 more comment
After trying some of the above (scripts didn't work for me) I found the following solution.
First find out the MAC-Adress of the device you want to connect to
bluetoothctl
this will enter a shell and list all available devices with adress. ("quit" to exit the shell & get back to prompt)
Then connect to XX:XX:XX:XX:XX:XX bluetooth device :
echo -e 'connect XX:XX:XX:XX:XX:XX' | bluetoothctl
to disconnect
echo -e 'disconnect XX:XX:XX:XX:XX:XX' | bluetoothctl
been searching for this quite a while - nothing seemed to work, felt so relieved when I found out. Thought others might want to know about it, too. :))
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get~$ bluetoothctl Agent registered [UE BOOM 2]#
. Thendisconnect "UE BOOM 2" Device UE BOOM 2 not available
.
– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output ofbluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.
– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, tryingecho -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get :Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
|
show 1 more comment
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "89"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f48001%2fconnect-to-bluetooth-device-from-command-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Bluetooth daemon
In the default installation a daemon (bluetoothd) runs in the background (run from the file /etc/init.d/bluetooth
). This daemon takes care on recognizing and connecting to known bluetooth devices and may be cofigured with configuration files in /etc/bluetooth
. For autoconneting a headset the following line in audio.conf
should be uncommented (remove #
):
AutoConnect=true
To restart the daemon type sudo /etc/init.d/bluetooth restart
.
Remark: Using the command line tool sudo hcitool cc <MAC-Adress>
did not lead to a stable connection to a known device in the test environment here when the daemon was running.
DBus
In order to connect a disconnected but physically present and paired headset we can use D-Bus from a script. Here's an example in python:
#!/usr/bin/python
# Toggles headset connection
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
#Get dbus interface for headset
manager = bus.get_object('org.bluez', '/')
iface_m = dbus.Interface(manager, 'org.bluez.Manager')
adapterPath = iface_m.DefaultAdapter()
adapter = bus.get_object('org.bluez', adapterPath)
iface_a = dbus.Interface(adapter, 'org.bluez.Adapter')
devicePath = iface_a.ListDevices()[0] # assuming first device
device = bus.get_object('org.bluez', devicePath)
iface_h = dbus.Interface(device, 'org.bluez.Headset')
#Check state of connection
connected = iface_h.IsConnected()
print 'Toggling connection. Please wait'
# toggle connection
if not connected:
try:
iface_h.Connect()
print 'Connecting: ', devicePath
except:
print 'Device not found'
else:
iface_h.Disconnect()
print 'Disconnecting: ', devicePath
In case we have more than one Bluetooth device we will have to adapt the devicePath
appropriately, of course. The example above will connect a Headset
. Change the interface to a different protocol for any other service (e.g. AudioSink
).
Pulseaudio
If you know the MAC adress of your Bluetooth device you can connect it as an output sink for pulseaudio by:
pacmd set-default-sink bluez_sink.xx_xx_xx_xx_xx_xx
Where xx_xx_xx_xx_xx_xx is the MAC address (replace ':' by '_' for pulseaudio to recognize it).
See also this answer for more details.
I do know the address, and I replaced the xx with it. I only getSink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.
– Ilari Kajaste
Jun 10 '11 at 8:56
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matchingbt
orblue
is listed inpacmd list-sinks
. (It reports only 1 sink available.)
– Ilari Kajaste
Jun 10 '11 at 9:29
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
|
show 13 more comments
Bluetooth daemon
In the default installation a daemon (bluetoothd) runs in the background (run from the file /etc/init.d/bluetooth
). This daemon takes care on recognizing and connecting to known bluetooth devices and may be cofigured with configuration files in /etc/bluetooth
. For autoconneting a headset the following line in audio.conf
should be uncommented (remove #
):
AutoConnect=true
To restart the daemon type sudo /etc/init.d/bluetooth restart
.
Remark: Using the command line tool sudo hcitool cc <MAC-Adress>
did not lead to a stable connection to a known device in the test environment here when the daemon was running.
DBus
In order to connect a disconnected but physically present and paired headset we can use D-Bus from a script. Here's an example in python:
#!/usr/bin/python
# Toggles headset connection
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
#Get dbus interface for headset
manager = bus.get_object('org.bluez', '/')
iface_m = dbus.Interface(manager, 'org.bluez.Manager')
adapterPath = iface_m.DefaultAdapter()
adapter = bus.get_object('org.bluez', adapterPath)
iface_a = dbus.Interface(adapter, 'org.bluez.Adapter')
devicePath = iface_a.ListDevices()[0] # assuming first device
device = bus.get_object('org.bluez', devicePath)
iface_h = dbus.Interface(device, 'org.bluez.Headset')
#Check state of connection
connected = iface_h.IsConnected()
print 'Toggling connection. Please wait'
# toggle connection
if not connected:
try:
iface_h.Connect()
print 'Connecting: ', devicePath
except:
print 'Device not found'
else:
iface_h.Disconnect()
print 'Disconnecting: ', devicePath
In case we have more than one Bluetooth device we will have to adapt the devicePath
appropriately, of course. The example above will connect a Headset
. Change the interface to a different protocol for any other service (e.g. AudioSink
).
Pulseaudio
If you know the MAC adress of your Bluetooth device you can connect it as an output sink for pulseaudio by:
pacmd set-default-sink bluez_sink.xx_xx_xx_xx_xx_xx
Where xx_xx_xx_xx_xx_xx is the MAC address (replace ':' by '_' for pulseaudio to recognize it).
See also this answer for more details.
I do know the address, and I replaced the xx with it. I only getSink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.
– Ilari Kajaste
Jun 10 '11 at 8:56
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matchingbt
orblue
is listed inpacmd list-sinks
. (It reports only 1 sink available.)
– Ilari Kajaste
Jun 10 '11 at 9:29
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
|
show 13 more comments
Bluetooth daemon
In the default installation a daemon (bluetoothd) runs in the background (run from the file /etc/init.d/bluetooth
). This daemon takes care on recognizing and connecting to known bluetooth devices and may be cofigured with configuration files in /etc/bluetooth
. For autoconneting a headset the following line in audio.conf
should be uncommented (remove #
):
AutoConnect=true
To restart the daemon type sudo /etc/init.d/bluetooth restart
.
Remark: Using the command line tool sudo hcitool cc <MAC-Adress>
did not lead to a stable connection to a known device in the test environment here when the daemon was running.
DBus
In order to connect a disconnected but physically present and paired headset we can use D-Bus from a script. Here's an example in python:
#!/usr/bin/python
# Toggles headset connection
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
#Get dbus interface for headset
manager = bus.get_object('org.bluez', '/')
iface_m = dbus.Interface(manager, 'org.bluez.Manager')
adapterPath = iface_m.DefaultAdapter()
adapter = bus.get_object('org.bluez', adapterPath)
iface_a = dbus.Interface(adapter, 'org.bluez.Adapter')
devicePath = iface_a.ListDevices()[0] # assuming first device
device = bus.get_object('org.bluez', devicePath)
iface_h = dbus.Interface(device, 'org.bluez.Headset')
#Check state of connection
connected = iface_h.IsConnected()
print 'Toggling connection. Please wait'
# toggle connection
if not connected:
try:
iface_h.Connect()
print 'Connecting: ', devicePath
except:
print 'Device not found'
else:
iface_h.Disconnect()
print 'Disconnecting: ', devicePath
In case we have more than one Bluetooth device we will have to adapt the devicePath
appropriately, of course. The example above will connect a Headset
. Change the interface to a different protocol for any other service (e.g. AudioSink
).
Pulseaudio
If you know the MAC adress of your Bluetooth device you can connect it as an output sink for pulseaudio by:
pacmd set-default-sink bluez_sink.xx_xx_xx_xx_xx_xx
Where xx_xx_xx_xx_xx_xx is the MAC address (replace ':' by '_' for pulseaudio to recognize it).
See also this answer for more details.
Bluetooth daemon
In the default installation a daemon (bluetoothd) runs in the background (run from the file /etc/init.d/bluetooth
). This daemon takes care on recognizing and connecting to known bluetooth devices and may be cofigured with configuration files in /etc/bluetooth
. For autoconneting a headset the following line in audio.conf
should be uncommented (remove #
):
AutoConnect=true
To restart the daemon type sudo /etc/init.d/bluetooth restart
.
Remark: Using the command line tool sudo hcitool cc <MAC-Adress>
did not lead to a stable connection to a known device in the test environment here when the daemon was running.
DBus
In order to connect a disconnected but physically present and paired headset we can use D-Bus from a script. Here's an example in python:
#!/usr/bin/python
# Toggles headset connection
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
#Get dbus interface for headset
manager = bus.get_object('org.bluez', '/')
iface_m = dbus.Interface(manager, 'org.bluez.Manager')
adapterPath = iface_m.DefaultAdapter()
adapter = bus.get_object('org.bluez', adapterPath)
iface_a = dbus.Interface(adapter, 'org.bluez.Adapter')
devicePath = iface_a.ListDevices()[0] # assuming first device
device = bus.get_object('org.bluez', devicePath)
iface_h = dbus.Interface(device, 'org.bluez.Headset')
#Check state of connection
connected = iface_h.IsConnected()
print 'Toggling connection. Please wait'
# toggle connection
if not connected:
try:
iface_h.Connect()
print 'Connecting: ', devicePath
except:
print 'Device not found'
else:
iface_h.Disconnect()
print 'Disconnecting: ', devicePath
In case we have more than one Bluetooth device we will have to adapt the devicePath
appropriately, of course. The example above will connect a Headset
. Change the interface to a different protocol for any other service (e.g. AudioSink
).
Pulseaudio
If you know the MAC adress of your Bluetooth device you can connect it as an output sink for pulseaudio by:
pacmd set-default-sink bluez_sink.xx_xx_xx_xx_xx_xx
Where xx_xx_xx_xx_xx_xx is the MAC address (replace ':' by '_' for pulseaudio to recognize it).
See also this answer for more details.
edited Apr 13 '17 at 12:23
Community♦
1
1
answered Jun 10 '11 at 8:43
TakkatTakkat
114k40 gold badges263 silver badges386 bronze badges
114k40 gold badges263 silver badges386 bronze badges
I do know the address, and I replaced the xx with it. I only getSink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.
– Ilari Kajaste
Jun 10 '11 at 8:56
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matchingbt
orblue
is listed inpacmd list-sinks
. (It reports only 1 sink available.)
– Ilari Kajaste
Jun 10 '11 at 9:29
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
|
show 13 more comments
I do know the address, and I replaced the xx with it. I only getSink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.
– Ilari Kajaste
Jun 10 '11 at 8:56
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matchingbt
orblue
is listed inpacmd list-sinks
. (It reports only 1 sink available.)
– Ilari Kajaste
Jun 10 '11 at 9:29
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
I do know the address, and I replaced the xx with it. I only get
Sink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.– Ilari Kajaste
Jun 10 '11 at 8:56
I do know the address, and I replaced the xx with it. I only get
Sink bluez_sink.xx_xx_xx_xx_xx_xx does not exist.
Tried both uppercase and lowercase.– Ilari Kajaste
Jun 10 '11 at 8:56
1
1
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matching
bt
or blue
is listed in pacmd list-sinks
. (It reports only 1 sink available.)– Ilari Kajaste
Jun 10 '11 at 9:29
Yes, pulseaudio-module-bluetooth is isntalle. No, nothing matching
bt
or blue
is listed in pacmd list-sinks
. (It reports only 1 sink available.)– Ilari Kajaste
Jun 10 '11 at 9:29
2
2
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
So it's not recognized. This is a prerequisite to be able to connect by commandline. Try restarting BT or try restarting pulsaudio. I've not yet found out why it's sometimes not detetcted.
– Takkat
Jun 10 '11 at 9:38
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
Huh? So it can be in a state that it's possible to connect from GUI, but not from CLI?
– Ilari Kajaste
Jun 10 '11 at 9:46
1
1
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
@Takkat Oh, yes, good point. My bad! I'm using the headset in discovery more, so it won't autoconnect. I edited the question to reflect this. Sorry for leading you down to a wrong path.
– Ilari Kajaste
Jun 10 '11 at 10:44
|
show 13 more comments
I use this script to connect my Bluetooth Audio Device. If your headset is already paired, you should be able to connect your headset in the same way using org.bluez.Headset.Connect/Disconnect in place of org.bluez.Audiosink.Connect/Disconnect.
#!/bin/bash
MAC_ADD="C8:84:47:10:11:CD"
MAC_ADD="dev_$MAC_ADD//:/_"
BT_ADAPTER=`dbus-send --system --print-reply --dest=org.bluez /
org.bluez.Manager.DefaultAdapter|awk '/object path/ print $3'`
BT_ADAPTER="$BT_ADAPTER//"//$MAC_ADD"
echo "Connecting to $BT_ADAPTER..."
if [ "$1" == "on" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Connect
elif [ "$1" == "off" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Disconnect
fi
HTH!
this worked for me too on16.04
, thank you! others, do not forget to passon
option to the script!
– MInner
Jun 30 '17 at 5:58
add a comment
|
I use this script to connect my Bluetooth Audio Device. If your headset is already paired, you should be able to connect your headset in the same way using org.bluez.Headset.Connect/Disconnect in place of org.bluez.Audiosink.Connect/Disconnect.
#!/bin/bash
MAC_ADD="C8:84:47:10:11:CD"
MAC_ADD="dev_$MAC_ADD//:/_"
BT_ADAPTER=`dbus-send --system --print-reply --dest=org.bluez /
org.bluez.Manager.DefaultAdapter|awk '/object path/ print $3'`
BT_ADAPTER="$BT_ADAPTER//"//$MAC_ADD"
echo "Connecting to $BT_ADAPTER..."
if [ "$1" == "on" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Connect
elif [ "$1" == "off" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Disconnect
fi
HTH!
this worked for me too on16.04
, thank you! others, do not forget to passon
option to the script!
– MInner
Jun 30 '17 at 5:58
add a comment
|
I use this script to connect my Bluetooth Audio Device. If your headset is already paired, you should be able to connect your headset in the same way using org.bluez.Headset.Connect/Disconnect in place of org.bluez.Audiosink.Connect/Disconnect.
#!/bin/bash
MAC_ADD="C8:84:47:10:11:CD"
MAC_ADD="dev_$MAC_ADD//:/_"
BT_ADAPTER=`dbus-send --system --print-reply --dest=org.bluez /
org.bluez.Manager.DefaultAdapter|awk '/object path/ print $3'`
BT_ADAPTER="$BT_ADAPTER//"//$MAC_ADD"
echo "Connecting to $BT_ADAPTER..."
if [ "$1" == "on" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Connect
elif [ "$1" == "off" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Disconnect
fi
HTH!
I use this script to connect my Bluetooth Audio Device. If your headset is already paired, you should be able to connect your headset in the same way using org.bluez.Headset.Connect/Disconnect in place of org.bluez.Audiosink.Connect/Disconnect.
#!/bin/bash
MAC_ADD="C8:84:47:10:11:CD"
MAC_ADD="dev_$MAC_ADD//:/_"
BT_ADAPTER=`dbus-send --system --print-reply --dest=org.bluez /
org.bluez.Manager.DefaultAdapter|awk '/object path/ print $3'`
BT_ADAPTER="$BT_ADAPTER//"//$MAC_ADD"
echo "Connecting to $BT_ADAPTER..."
if [ "$1" == "on" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Connect
elif [ "$1" == "off" ]; then
dbus-send --print-reply --system --dest=org.bluez $BT_ADAPTER org.bluez.AudioSink.Disconnect
fi
HTH!
answered Feb 23 '13 at 16:50
doublerebeldoublerebel
4965 silver badges4 bronze badges
4965 silver badges4 bronze badges
this worked for me too on16.04
, thank you! others, do not forget to passon
option to the script!
– MInner
Jun 30 '17 at 5:58
add a comment
|
this worked for me too on16.04
, thank you! others, do not forget to passon
option to the script!
– MInner
Jun 30 '17 at 5:58
this worked for me too on
16.04
, thank you! others, do not forget to pass on
option to the script!– MInner
Jun 30 '17 at 5:58
this worked for me too on
16.04
, thank you! others, do not forget to pass on
option to the script!– MInner
Jun 30 '17 at 5:58
add a comment
|
I use i3 as a window manager so I do not have the bluetooth tray icon available. For some reason the check button in unity settings is not sensitive and so I need a way to do this from time to time when my headphones don't connect.
It seems that bluez
has changed their dbus API. The answer utilizing org.bluez.Manager
no longer appears to work. Instead, it is recommended to use ObjectManager
.
Here is an updated python script which will connect the first unconnected bluetooth headset that it finds (presumably the list includes all paired devices?):
#!/usr/bin/env python
# Toggles headset connection
from __future__ import print_function
from __future__ import unicode_literals
import dbus
from dbus.mainloop.glib import DBusGMainLoop
def find_headset(bus):
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.items():
if ("org.bluez.Device1" in ifaces and
"org.freedesktop.DBus.Properties" in ifaces):
iprops = dbus.Interface(
bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = iprops.GetAll("org.bluez.Device1")
# Looking for a headset. Could also match on other properties like
# "Name". See bluez docs for whats available.
if props.get("Class") == 0x240404:
if props.get("Connected"):
print("Found headset () but it is already connected"
.format(props.get("Name"), props.get("Address")))
continue
return path
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
hpath = find_headset(bus)
if hpath:
adapter = dbus.Interface(
bus.get_object("org.bluez", hpath), "org.bluez.Device1")
adapter.Connect()
this example, like the other example on this thread, uses the dbus
python package. On ubuntu 16.04 I installed this through apt-get install python-dbus
.
If you wish to match other criteria, this document appears to show a list of properties that can be queried over dbus.
I have this script saved in ~/.local/bin/bt-connect-headset
which is on my PATH
so I can execute it from the i3 launcher. Make it executable (chmod +x bt-connect-headset
) if you plan to use it as a command.
This script has only been tested on an up-to-date ubuntu 16.04 as of 09/28/2018.
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of2360344
instead of0x240404
.
– dom_watson
Nov 29 '18 at 21:40
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use theDisconnect()
method. I haven't tried it, but it's probably a safe bet ;).
– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you sayfirst unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line toadapter.Disconnect()
.)
– cipricus
Sep 2 at 11:33
|
show 1 more comment
I use i3 as a window manager so I do not have the bluetooth tray icon available. For some reason the check button in unity settings is not sensitive and so I need a way to do this from time to time when my headphones don't connect.
It seems that bluez
has changed their dbus API. The answer utilizing org.bluez.Manager
no longer appears to work. Instead, it is recommended to use ObjectManager
.
Here is an updated python script which will connect the first unconnected bluetooth headset that it finds (presumably the list includes all paired devices?):
#!/usr/bin/env python
# Toggles headset connection
from __future__ import print_function
from __future__ import unicode_literals
import dbus
from dbus.mainloop.glib import DBusGMainLoop
def find_headset(bus):
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.items():
if ("org.bluez.Device1" in ifaces and
"org.freedesktop.DBus.Properties" in ifaces):
iprops = dbus.Interface(
bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = iprops.GetAll("org.bluez.Device1")
# Looking for a headset. Could also match on other properties like
# "Name". See bluez docs for whats available.
if props.get("Class") == 0x240404:
if props.get("Connected"):
print("Found headset () but it is already connected"
.format(props.get("Name"), props.get("Address")))
continue
return path
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
hpath = find_headset(bus)
if hpath:
adapter = dbus.Interface(
bus.get_object("org.bluez", hpath), "org.bluez.Device1")
adapter.Connect()
this example, like the other example on this thread, uses the dbus
python package. On ubuntu 16.04 I installed this through apt-get install python-dbus
.
If you wish to match other criteria, this document appears to show a list of properties that can be queried over dbus.
I have this script saved in ~/.local/bin/bt-connect-headset
which is on my PATH
so I can execute it from the i3 launcher. Make it executable (chmod +x bt-connect-headset
) if you plan to use it as a command.
This script has only been tested on an up-to-date ubuntu 16.04 as of 09/28/2018.
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of2360344
instead of0x240404
.
– dom_watson
Nov 29 '18 at 21:40
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use theDisconnect()
method. I haven't tried it, but it's probably a safe bet ;).
– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you sayfirst unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line toadapter.Disconnect()
.)
– cipricus
Sep 2 at 11:33
|
show 1 more comment
I use i3 as a window manager so I do not have the bluetooth tray icon available. For some reason the check button in unity settings is not sensitive and so I need a way to do this from time to time when my headphones don't connect.
It seems that bluez
has changed their dbus API. The answer utilizing org.bluez.Manager
no longer appears to work. Instead, it is recommended to use ObjectManager
.
Here is an updated python script which will connect the first unconnected bluetooth headset that it finds (presumably the list includes all paired devices?):
#!/usr/bin/env python
# Toggles headset connection
from __future__ import print_function
from __future__ import unicode_literals
import dbus
from dbus.mainloop.glib import DBusGMainLoop
def find_headset(bus):
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.items():
if ("org.bluez.Device1" in ifaces and
"org.freedesktop.DBus.Properties" in ifaces):
iprops = dbus.Interface(
bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = iprops.GetAll("org.bluez.Device1")
# Looking for a headset. Could also match on other properties like
# "Name". See bluez docs for whats available.
if props.get("Class") == 0x240404:
if props.get("Connected"):
print("Found headset () but it is already connected"
.format(props.get("Name"), props.get("Address")))
continue
return path
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
hpath = find_headset(bus)
if hpath:
adapter = dbus.Interface(
bus.get_object("org.bluez", hpath), "org.bluez.Device1")
adapter.Connect()
this example, like the other example on this thread, uses the dbus
python package. On ubuntu 16.04 I installed this through apt-get install python-dbus
.
If you wish to match other criteria, this document appears to show a list of properties that can be queried over dbus.
I have this script saved in ~/.local/bin/bt-connect-headset
which is on my PATH
so I can execute it from the i3 launcher. Make it executable (chmod +x bt-connect-headset
) if you plan to use it as a command.
This script has only been tested on an up-to-date ubuntu 16.04 as of 09/28/2018.
I use i3 as a window manager so I do not have the bluetooth tray icon available. For some reason the check button in unity settings is not sensitive and so I need a way to do this from time to time when my headphones don't connect.
It seems that bluez
has changed their dbus API. The answer utilizing org.bluez.Manager
no longer appears to work. Instead, it is recommended to use ObjectManager
.
Here is an updated python script which will connect the first unconnected bluetooth headset that it finds (presumably the list includes all paired devices?):
#!/usr/bin/env python
# Toggles headset connection
from __future__ import print_function
from __future__ import unicode_literals
import dbus
from dbus.mainloop.glib import DBusGMainLoop
def find_headset(bus):
manager = dbus.Interface(bus.get_object("org.bluez", "/"),
"org.freedesktop.DBus.ObjectManager")
objects = manager.GetManagedObjects()
for path, ifaces in objects.items():
if ("org.bluez.Device1" in ifaces and
"org.freedesktop.DBus.Properties" in ifaces):
iprops = dbus.Interface(
bus.get_object("org.bluez", path),
"org.freedesktop.DBus.Properties")
props = iprops.GetAll("org.bluez.Device1")
# Looking for a headset. Could also match on other properties like
# "Name". See bluez docs for whats available.
if props.get("Class") == 0x240404:
if props.get("Connected"):
print("Found headset () but it is already connected"
.format(props.get("Name"), props.get("Address")))
continue
return path
dbus_loop = DBusGMainLoop()
bus = dbus.SystemBus(mainloop=dbus_loop)
hpath = find_headset(bus)
if hpath:
adapter = dbus.Interface(
bus.get_object("org.bluez", hpath), "org.bluez.Device1")
adapter.Connect()
this example, like the other example on this thread, uses the dbus
python package. On ubuntu 16.04 I installed this through apt-get install python-dbus
.
If you wish to match other criteria, this document appears to show a list of properties that can be queried over dbus.
I have this script saved in ~/.local/bin/bt-connect-headset
which is on my PATH
so I can execute it from the i3 launcher. Make it executable (chmod +x bt-connect-headset
) if you plan to use it as a command.
This script has only been tested on an up-to-date ubuntu 16.04 as of 09/28/2018.
answered Sep 28 '18 at 21:46
cheshirekowcheshirekow
4551 gold badge5 silver badges19 bronze badges
4551 gold badge5 silver badges19 bronze badges
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of2360344
instead of0x240404
.
– dom_watson
Nov 29 '18 at 21:40
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use theDisconnect()
method. I haven't tried it, but it's probably a safe bet ;).
– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you sayfirst unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line toadapter.Disconnect()
.)
– cipricus
Sep 2 at 11:33
|
show 1 more comment
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of2360344
instead of0x240404
.
– dom_watson
Nov 29 '18 at 21:40
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use theDisconnect()
method. I haven't tried it, but it's probably a safe bet ;).
– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you sayfirst unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line toadapter.Disconnect()
.)
– cipricus
Sep 2 at 11:33
1
1
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
Used your script on Ubuntu 18.10. Thanks!
– Brombomb
Nov 15 '18 at 20:03
1
1
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of
2360344
instead of 0x240404
.– dom_watson
Nov 29 '18 at 21:40
Super, this worked for me in Linux Mint 19 Cinnamon. However, I used a device class of
2360344
instead of 0x240404
.– dom_watson
Nov 29 '18 at 21:40
1
1
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
works as such in Mint Xfce 19.2. I'm sure it works in Xubuntu. - What about a script to disconnect the bluetooth ?
– cipricus
Aug 30 at 1:06
1
1
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use the
Disconnect()
method. I haven't tried it, but it's probably a safe bet ;).– cheshirekow
Aug 31 at 4:47
@cipricus That is correct, and is already mentioned in the answer. There's a link in the answer on how to match other criteria if you need something more advanced (like matching a device of a particular name). That link also includes a list of methods available on this interface. To disconnect, my guess is use the
Disconnect()
method. I haven't tried it, but it's probably a safe bet ;).– cheshirekow
Aug 31 at 4:47
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you say
first unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line to adapter.Disconnect()
.)– cipricus
Sep 2 at 11:33
I was wrong. I thought it never goes beyond the first in the list of paired devices, but it does. I might have also missed the fact that you say
first unconnected bluetooth headset
: will it always use the headset (if powered) before other device like bluetooth speakers (no matter the position in the list)? That's what happens in my case. -- Also, in order to disconnect I cannot do it by just changing the last line to adapter.Disconnect()
.)– cipricus
Sep 2 at 11:33
|
show 1 more comment
After trying some of the above (scripts didn't work for me) I found the following solution.
First find out the MAC-Adress of the device you want to connect to
bluetoothctl
this will enter a shell and list all available devices with adress. ("quit" to exit the shell & get back to prompt)
Then connect to XX:XX:XX:XX:XX:XX bluetooth device :
echo -e 'connect XX:XX:XX:XX:XX:XX' | bluetoothctl
to disconnect
echo -e 'disconnect XX:XX:XX:XX:XX:XX' | bluetoothctl
been searching for this quite a while - nothing seemed to work, felt so relieved when I found out. Thought others might want to know about it, too. :))
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get~$ bluetoothctl Agent registered [UE BOOM 2]#
. Thendisconnect "UE BOOM 2" Device UE BOOM 2 not available
.
– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output ofbluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.
– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, tryingecho -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get :Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
|
show 1 more comment
After trying some of the above (scripts didn't work for me) I found the following solution.
First find out the MAC-Adress of the device you want to connect to
bluetoothctl
this will enter a shell and list all available devices with adress. ("quit" to exit the shell & get back to prompt)
Then connect to XX:XX:XX:XX:XX:XX bluetooth device :
echo -e 'connect XX:XX:XX:XX:XX:XX' | bluetoothctl
to disconnect
echo -e 'disconnect XX:XX:XX:XX:XX:XX' | bluetoothctl
been searching for this quite a while - nothing seemed to work, felt so relieved when I found out. Thought others might want to know about it, too. :))
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get~$ bluetoothctl Agent registered [UE BOOM 2]#
. Thendisconnect "UE BOOM 2" Device UE BOOM 2 not available
.
– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output ofbluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.
– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, tryingecho -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get :Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
|
show 1 more comment
After trying some of the above (scripts didn't work for me) I found the following solution.
First find out the MAC-Adress of the device you want to connect to
bluetoothctl
this will enter a shell and list all available devices with adress. ("quit" to exit the shell & get back to prompt)
Then connect to XX:XX:XX:XX:XX:XX bluetooth device :
echo -e 'connect XX:XX:XX:XX:XX:XX' | bluetoothctl
to disconnect
echo -e 'disconnect XX:XX:XX:XX:XX:XX' | bluetoothctl
been searching for this quite a while - nothing seemed to work, felt so relieved when I found out. Thought others might want to know about it, too. :))
After trying some of the above (scripts didn't work for me) I found the following solution.
First find out the MAC-Adress of the device you want to connect to
bluetoothctl
this will enter a shell and list all available devices with adress. ("quit" to exit the shell & get back to prompt)
Then connect to XX:XX:XX:XX:XX:XX bluetooth device :
echo -e 'connect XX:XX:XX:XX:XX:XX' | bluetoothctl
to disconnect
echo -e 'disconnect XX:XX:XX:XX:XX:XX' | bluetoothctl
been searching for this quite a while - nothing seemed to work, felt so relieved when I found out. Thought others might want to know about it, too. :))
edited Aug 11 at 20:39
answered Aug 9 at 20:24
JosephJoseph
586 bronze badges
586 bronze badges
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get~$ bluetoothctl Agent registered [UE BOOM 2]#
. Thendisconnect "UE BOOM 2" Device UE BOOM 2 not available
.
– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output ofbluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.
– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, tryingecho -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get :Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
|
show 1 more comment
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get~$ bluetoothctl Agent registered [UE BOOM 2]#
. Thendisconnect "UE BOOM 2" Device UE BOOM 2 not available
.
– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output ofbluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.
– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, tryingecho -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get :Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
Could you edit your answer to add how to get the device's address, so the answer is more complete?
– user3140225
Aug 9 at 20:32
1
1
@user3140225 just did.
– Joseph
Aug 11 at 20:44
@user3140225 just did.
– Joseph
Aug 11 at 20:44
I get
~$ bluetoothctl Agent registered [UE BOOM 2]#
. Then disconnect "UE BOOM 2" Device UE BOOM 2 not available
.– cipricus
Sep 2 at 12:13
I get
~$ bluetoothctl Agent registered [UE BOOM 2]#
. Then disconnect "UE BOOM 2" Device UE BOOM 2 not available
.– cipricus
Sep 2 at 12:13
@cipricus @user3140225 Could you post the output of
bluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.– Joseph
Sep 4 at 6:18
@cipricus @user3140225 Could you post the output of
bluetoothctl
? You need to feed the commands with the MAC-adress of the device - which is the combination of HEX Values in the format XX:XX:XX:XX:XX:XX, where X is either a letter or a number.– Joseph
Sep 4 at 6:18
I can see the MAC as said here. Then, trying
echo -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get : Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
I can see the MAC as said here. Then, trying
echo -e 'connect CC:AF:78:AF:59:03' | bluetoothctl
I get : Agent registered [bluetooth]# connect CC:AF:78:AF:59:03 Device CC:AF:78:AF:59:03 not available
– cipricus
Sep 4 at 12:17
|
show 1 more comment
Thanks for contributing an answer to Ask Ubuntu!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f48001%2fconnect-to-bluetooth-device-from-command-line%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What tray tool is that? is it Blueman Manager tray icon? Should Blueman manager tray applet list paired bluetooth devices?
– cipricus
Jun 26 at 7:52