python连接蓝牙设备,python蓝牙-检查连接状态
I am using the bluetooth module for python import bluetooth which I believe isthe PyBluez package. I am able to connect, send, and receive just fine from the bluetooth.BluetoothSocket class but my a..
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.
解决方案
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 "", 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
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)