Python连接设备

2024-10-01 07:48:11 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所示,我有一个BLE设备,我希望通过python脚本连接到它。我正在使用一个覆盆子Pi,并安装了最新版本的Bluez。在

我已经用Bluepy连接到了一个不同的BLE设备,不幸的是,我无法使用当前BLE检索任何数据,这就是为什么我要用不同的方式连接到它。在

我已经使用GATTTool连接到新设备并成功地获得了数据,我知道有一些库可以在python脚本中方便地与GATTTool连接。我尝试过pexpect和pygatt,但似乎都不起作用,因为在建立连接之前会超时。在

这是我在网上找到的一段代码

import pygatt.backends
from binascii import hexlify

def printIndication(handle, value):
    print('Indication received {} : {}'.format(hex(handle), hexlify(str(value))))

adapter = pygatt.backends.GATTToolBackend()
adapter.start()
while True:  
 try:
    device = adapter.connect('00:38:40:0A:00:04', 5)
    break
 except pygatt.exceptions.NotConnectedError:
    print('Waiting...')

device.subscribe('0002021-0000-1000-8000-00805f9b34fb', callback = printIndication, indication = True)
device.subscribe('00002022-0000-1000-8000-00805f9b34fb', callback = printIndication, indication = True)
device.subscribe('00002a19-0000-1000-8000-00805f9b34fb', callback = printIndication, indication = True)


device.disconnect()
adapter.stop()

当我执行代码时,我得到以下输出:

^{pr2}$

我还尝试了以下代码:

import pygatt.backends

# The BGAPI backend will attemt to auto-discover the serial device name of the
# attached BGAPI-compatible USB adapter.
adapter = pygatt.backends.GATTToolBackend()
adapter.start()
device = adapter.connect('01:23:45:67:89:ab')
value = device.char_read("a1e8f5b1-696b-4e4c-87c6-69dfe0b0093b")

在执行这段代码之后,我得到了完全相同的错误。我尝试过更改超时,但似乎没有什么区别,所发生的只是它等待分配的时间,并显示相同的输出。在

我错过了什么?有更好的方法吗?在

感谢您的帮助。在


Tags: 数据代码import脚本trueadaptervaluedevice
1条回答
网友
1楼 · 发布于 2024-10-01 07:48:11

现在可能太晚了,但是如果有人有同样的疑问,您可以使用pexpect库。我将留下一些可以使用的示例代码(我可以读取从psoc4200ble设备发送的一些数据)。在

import pexpect
DEVICE = "00:A0:50:CF:62:CD"   # address of your device
if len(sys.argv) == 2:
  DEVICE = str(sys.argv[1])
# Run gatttool interactively.
child = pexpect.spawn("gatttool -I")

# Connect to the device.
print("Connecting to:"),
print(DEVICE)
NOF_REMAINING_RETRY = 3
while True:
  try:
    child.sendline("connect {0}".format(DEVICE))
    child.expect("Connection successful", timeout=5)
  except pexpect.TIMEOUT:
    NOF_REMAINING_RETRY = NOF_REMAINING_RETRY-1
    if (NOF_REMAINING_RETRY>0):
      print "timeout, retry..."
      continue
    else:
      print "timeout, giving up."
      break
  else:
    print("Connected!")
    break

然后读点东西就这样做:

^{pr2}$

相关问题 更多 >