簡體   English   中英

Python-連接BLE設備

[英]Python - Connect a BLE device

如標題所示,我有一個希望通過python腳本連接的BLE設備。 我正在使用Raspberry 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()

當我執行代碼時,得到以下輸出:

Traceback (most recent call last):
  File "./test.py", line 10, in <module>
    adapter.start()
  File "/usr/local/lib/python2.7/dist-packages/pygatt/backends/gatttool/gatttool.py", line 90, in start
   self._con.expect(r'\[LE\]>', timeout=1)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1418, in expect
    timeout, searchwindowsize)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1433, in expect_list
    timeout, searchwindowsize)
  File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1535, in expect_loop
    raise TIMEOUT(str(err) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0x76737730>
version: 3.2
command: /usr/bin/gatttool
args: ['/usr/bin/gatttool', '-i', 'hci0', '-I']
searcher: <pexpect.searcher_re object at 0x76737770>
buffer (last 100 chars): ''
before (last 100 chars): ''
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 5062
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

我還嘗試了以下代碼:

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

執行此代碼后,我得到了完全相同的錯誤。 我嘗試過更改超時,但似乎沒有什么不同,所有發生的事情是它等待分配的時間,並且將顯示相同的輸出。

我想念什么? 有一個更好的方法嗎?

謝謝,提前提供任何幫助。

可能現在為時已晚,但是如果有人有同樣的疑問,則可以使用pexpect庫。 我將留下一些適用的示例代碼(我可以讀取從PSOC 4200 ble設備發送的一些數據)。

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

然后閱讀一些內容,只需執行以下操作:

# Presence Sensor
  child.sendline("char-read-hnd 0x16") # put the handle you want to read
  child.expect("Characteristic value/descriptor: ", timeout=5)
  child.expect("\r\n", timeout=5)
  print("Presence Sensor:  "),
  print(child.before),
  print(chr(int(child.before[0:2],16)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM