Bluepy BLE Отключение после получения нескольких пакетов от Bluno Beetle
Мне нужно подключить 6 жуков bluno к моему Raspi 3B+ для одновременного получения некоторых данных. Однако, имея только одно соединение с одним жуком-блуно, я уже постоянно теряю соединение после получения нескольких пакетов. Иногда я могу получить 20 пакетов до отключения, а иногда я могу получить 5 пакетов до отключения. Количество полученных пакетов колеблется.
Это должно быть нормально?
Мой raspi 3B+ установлен с Raspbian GNU/Linux 10 (buster). У меня установлен python3 с установленной bluepy версии 1.3.0.
The Bluno Beetle is an Arduino Uno based board with bluetooth 4.0 The Raspi 3B+ has a Bluetooth HCI Version: 5.0 (0x9)
I have tried to handle disconnection by reconnecting and it works fine. But the time taken to reconnect takes a while (4-5 seconds) which I would have data from Bluno beetle side.
How can I further enhance the robustness of BLE? This is my python code below where I am only listening to data sent from the Bluno Beetle.
from bluepy import btle
from bluepy.btle import BTLEException, Scanner, BTLEDisconnectError
import threading
# Global Vars
connectionObjects = [] # Total of 6 Connections expected
connectedThreads = [] # Total of 6 Connections expected
threads = list()
class MyDelegate(btle. DefaultDelegate):
def __init__(self, connection_index):
btle.DefaultDelegate.__init__(self)
def handleNotification(self, cHandle, data):
print("handling notification...")
data_string = str(data)
print(data_string)
class ConnectionHandlerThread (threading.Thread):
def __init__(self, connection_index, BTAddress):
threading.Thread.__init__(self)
self.connection_index = connection_index
self.BTAddress = BTAddress
self.connection = connectionObjects[self.connection_index]
def connect(self):
self.connection.setDelegate(MyDelegate(self.connection_index))
def run(self):
self.connect()
while True:
try:
if self.connection.waitForNotifications(1.0):
continue
print("Waiting...")
except:
try:
self.connection.disconnect()
except:
pass
finally:
reestablish_connection(self.connection, self.BTAddress, self.connection_index)
def reestablish_connection (connection, BTAddr, index):
while True:
try:
print("trying to reconnect with " + str(BTAddr) )
connection.connect(str(BTAddr))
print("re-connected to "+ str(BTAddr) +", index = " + str(index))
return
except:
continue
BTAddress = ['1c:ba:8c:1d:3a:c1']
for index in range(len(BTAddress)):
while True:
try:
p = btle.Peripheral()
p.connect(BTAddress[index], btle.ADDR_TYPE_PUBLIC)
break
except btle.BTLEException as e:
print("Connection Fail. Retrying now...")
continue
print ("Successful Connection to BLE " + str(BTAddress[index]))
connectionObjects.append(p) # first index is 0, first connected is beetle num 1
thread = ConnectionHandlerThread(len(connectionObjects)-1, BTAddress[index])
thread.setName("BLE-Thread-" + str(len(connectionObjects)-1))
thread.start()
connectedThreads.append(thread)
My hciconfig:
hci0: Type: Primary Bus: UART
BD Address: B8:27:EB:D4:EC:5D ACL MTU: 1021:8 SCO MTU: 64:1
UP RUNNING
RX bytes:204543 acl:2383 sco:0 events:8342 errors:0
TX bytes:49523 acl:152 sco:0 commands:4072 errors:0
Connecting via bluetoothctl seems fine:
root@raspberrypi:~# bluetoothctl
Agent registered
[bluetooth]# connect 1c:ba:8c:1d:3a:c1
Attempting to connect to 1c:ba:8c:1d:3a:c1
[CHG] Device 1C:BA:8C:1D:3A:C1 Connected: yes
Connection successful
I have been searching around the net for a robust solution but could not find a way to prevent disconnection or increase the reconnection time. Would appreciate if you could help me with this!
Could the reason be RPI firmaware makes BLE unstable?? https://github.com/IanHarvey/bluepy/issues/396
1 ответ
Я могу сделать вывод, что прошивка RPI имеет проблемы после тестирования с другой платой.
Может быть причина в том, что фирма RPI делает BLE нестабильным? https://github.com/IanHarvey/bluepy/issues/396
Работает без отключения при тестировании той же настройки с Ultra96 v2, работающей на Ubuntu 18.04 bionic. Я могу читать / писать на устройство bluno каждые 1 мс, и соединение надежное.
Следовательно, похоже, что проблема была в прошивке RPI. Я использовал Rasbian Buster на Raspberry pi 3b+.