python bluetooth - check connection status
Asked Answered
C

3

5

I am using the bluetooth module for python import bluetooth which I believe is the PyBluez package. I am able to connect, send, and receive just fine from the bluetooth.BluetoothSocket class but my application is completely blind when it comes to the status of the connection.

I want my application to disable certain functionality when the device is disconnected but there does not seem to be any BluetoothSocket.is_connected() methods of any kind. I would like it to detect changes in the bluetooth status as soon as they occur.

Usually there are multiple topics about something as simple as this, so apologies if this is a duplicate. I have searched this site multiple times for an answer but found nothing specific to python.

Catercornered answered 30/10, 2016 at 1:21 Comment(1)
RoccoLacatus has a good answer which solved the issue for me. If it solved the issue for you as well, you should mark this question as answered.Dispersant
F
5

If your SO is linux, you could use the hcitool, which will tell you the status of your bluetooth devices.

Please find below a small Python snippet that can accomplish your need. You will need to know your bluetooth device's MAC:

import subprocess as sp

stdoutdata = sp.getoutput("hcitool con")

if "XX:XX:XX:XX:XX:XX" in stdoutdata.split():
    print("Bluetooth device is connected")

Hope this helps!

Faunia answered 25/3, 2017 at 19:12 Comment(1)
For 2.7 use sp.check_output(["hcitool", "con")Brucie
K
3

If you are using Linux, it's also possible to check whether the device is still available using BluetoothSocket's getpeername() method. This method (which is inherited from python's socket class) returns the remote address to which the socket is connected.

If the device is still available:

>>>sock.getpeername()
('98:C3:32:81:64:DE', 1)

If the device is not connected:

>>>sock.getpeername()
Traceback (most recent call last):
    File "<string>", line 3, in getpeername
_bluetooth.error: (107, 'Transport endpoint is not connected')

Therefore, to test if a socket is still connected to an actual device, you could use:

try:
    sock.getpeername()
    still_connected = True
except:
    still_connected = False
Ketene answered 10/5, 2017 at 10:42 Comment(0)
D
0

Much easier way to get mac address:

import getmac
from getmac import get_mac_address as gma

mac_addr = gma()
Downer answered 22/3, 2022 at 22:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.