简体   繁体   English

python 蓝牙 - 检查连接状态

[英]python bluetooth - check connection status

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.我正在使用 python import bluetooth的蓝牙模块,我相信它是 PyBluez package。我能够从蓝牙连接、发送和接收。BluetoothSocket class 但我的应用程序在涉及状态时完全失明联系。

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.我希望我的应用程序在设备断开连接时禁用某些功能,但似乎没有任何类型的 BluetoothSocket.is_connected() 方法。 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.我已多次搜索此站点以寻找答案,但没有发现任何特定于 python 的内容。

If your SO is linux, you could use the hcitool , which will tell you the status of your bluetooth devices. 如果您的SO是linux,则可以使用hcitool ,它将告诉您蓝牙设备的状态。

Please find below a small Python snippet that can accomplish your need. 请在下面找到一个可以满足您需求的Python小片段。 You will need to know your bluetooth device's MAC: 您将需要知道蓝牙设备的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. 如果您使用的是Linux,还可以使用BluetoothSocket的getpeername()方法检查设备是否仍然可用。 This method (which is inherited from python's socket class) returns the remote address to which the socket is connected. 此方法(继承自python的套接字类)返回套接字连接到的远程地址。

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

Much easier way to get mac address:获取 mac 地址的更简单方法:

import getmac
from getmac import get_mac_address as gma

mac_addr = gma()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM