且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python蓝牙-检查连接状态

更新时间:2023-11-26 11:03:16

如果您使用的是Linux,还可以使用BluetoothSocket的getpeername()方法检查设备是否仍然可用.此方法(继承自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.

如果设备仍然可用:

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

如果未连接设备:

>>>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