使用pexpect检测和处理来自蓝牙LE的通知

2024-05-19 03:38:11 发布

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

我一直在编写一个python代码来读取Bluetooth LE接收到的Raspberry pi3模型B上的值。 我可以通过以下方式读取正确的值:

child.sendline("char-read-hnd handle")
child.expect("Characteristic value/descripto: ",timeout=5)

我现在要做的是在任何时候检查通知,所以我有一个线程来搜索预期的模式“Notification handle=”,如下所示:

^{pr2}$

现在在我的主代码中,我总是做一些子级.sendline检查新值以及孩子。期待. 问题是我的线程调用希望。期待上面挡住了我的其他人希望。期待在我的代码里。 我已经尝试过做第二个类似于第一个的孩子在线程内工作,但是结果是一样的。 有人知道我该怎么做吗?在

任何帮助都将不胜感激。 提前谢谢


Tags: 代码模型lechildread方式孩子线程
1条回答
网友
1楼 · 发布于 2024-05-19 03:38:11

我正在考虑将pexpect.spawn子类化并提供一个expect_before(p,c)方法,该方法将保存模式列表p和回调函数{},然后重写expect(p2),在调用实数spawn.expect函数之前,将列表p添加到该调用的列表p2上。在

如果实函数返回一个匹配索引i,它在列表p的大小内,我们可以调用函数c[i],然后再次循环。当索引超出该列表时,我们将其调整为list p2中的索引,并从调用中返回。这是一个近似值:

#!/usr/bin/python
# https://stackoverflow.com/q/51622025/5008284
from __future__ import print_function
import sys, pexpect

class Myspawn(pexpect.spawn):
  def __init__(self, *args, **kwargs):
    pexpect.spawn.__init__(self, *args, **kwargs)

  def expect_before(self, patterns, callbacks):
    self.eb_pat = patterns
    self.eb_cb = callbacks

  def expect(self, patlist, *args, **kwargs):
    numbefore = len(self.eb_pat)
    while True:
      rc = pexpect.spawn.expect(self, self.eb_pat+patlist, *args, **kwargs)
      if rc>=numbefore:
        break
      self.eb_cb[rc]() # call callback
    return rc-numbefore

def test():
    child = Myspawn("sudo bluetoothctl", logfile=sys.stdout)
    patterns = ['Device FC:A8:9A:..:..:..', 'Device C8:FD:41:..:..:..']
    callbacks = [lambda :handler1(), lambda :handler2()]
    child.expect_before(patterns, callbacks)
    child.sendline('scan on')
    while True:
      child.expect(['[bluetooth].*?#'], timeout=5)

相关问题 更多 >

    热门问题