python蓝牙-检查连接状态 [英] python bluetooth - check connection status

查看:583
本文介绍了python蓝牙-检查连接状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为python import bluetooth使用蓝牙模块,我相信它是PyBluez软件包.我可以从bluetooth.BluetoothSocket类进行连接,发送和接收,但是当涉及到连接状态时,我的应用程序完全是盲目的.

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.

我希望我的应用程序在断开设备连接时禁用某些功能,但是似乎没有任何类型的BluetoothSocket.is_connected()方法.我希望它能够尽快检测到蓝牙状态的变化.

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.

通常有多个关于这样简单的内容的主题,如果这是重复的内容,则表示歉意.我已经多次搜索该站点的答案,但没有发现特定于python的内容.

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.

推荐答案

如果您使用的是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

这篇关于python蓝牙-检查连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆