python bluetooth - check connection status

别等时光非礼了梦想. 提交于 2019-11-29 14:53:56

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!

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!