-
Notifications
You must be signed in to change notification settings - Fork 205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Работа термометров в Home Assistant c Bluetooth LE Long Range. #297
Comments
НА в докере, не получилось заставить работать с LR по предложенной инструкции. Может быть нужно ещё что то предпринять? |
На ходу, когда уже загружен HA, переключение адаптера не работает.
В Linux, в Bluez, адаптер BT5.0 по старту системы инициализируется неправильно. От этого все проблемы в Linux. Интеграция "bluetooth" работает через прокладку "Bleak". "Bleak" в свою очередь работает через DBUS, Далее следующая "прокладка" - "Bluez", далее kernel. Это упрощенно, т.к. там десятки так называемых API прокладок. WEB Bluetooth API нормально не работает в Linux. В Android оно может соединяться с любыми PHY, но меню сканирования у Chrome ещё не умеет работать с BT5.0. В Windows ситуация с WEB Bluetooth API почти аналогична с Linux, но там другие проблемы. Linux тормозят Bluez и Товальдс, подписывая кривые решения. API Android работает без проблем с Coded PHY и всеми остальными форматами PHY. Примером является nRFConnect и многие другие приложения на Android. Apple вообще никогда не придерживалось стандартов Bluetooth SIG. И там свои предрассудки. По идее, в докере, всё должно быть аналогично, если произвести переключение в той части, которая управляет адаптером. Адаптеры BT5.0 умеют сканировать во всех вариантах PHY с 2016 года. |
Интеграция "ble_monitor" в HA включает сканирование только на 1M PHY. Автор ещё не умеет переключать адаптер на работу в BT5.0. |
Спасибо за описание. Удалось таки перевести датчики lywsd03mmc на использование BLE LR в HA в докере. Пришлось перейти с ble_monitor на xiaomi_ble и заново их определить. |
Long Range - ok. |
@pvvx |
На Windows "Advertising.html" практически не работает. Это проблема в Windows c
В HA две интеграции для работы с термометрами - "Bluetooth" и "Bluetooth Low Energy Monitor - Passive BLE monitor".
Рисунки и названия адаптеров от продавцов ни о чем не говорят. По USB VID/PID можно узнать какой чип. По номерам HCI/LMP - какой версии bluetooth: |
@pvvx |
Настройки применяются сразу, но BLE реклама не работает во время соединения. |
цель зависти все это не на виндовс, а на RPI 4 c Home Assistant и с этим свистком |
Google: USB\VID_0BDA&PID_8771 а это и есть 8761B
А это уже ваши проблемы с версиями ОС на RPI 4 и Home Assistant. |
Может отсоединяется по причине посаженной батарейки. Для соединения желательно чтобы было более 40% (+20С). |
батарея 99%. а подключение к chrome на телефоне может мешать подключению к RPI4? |
Во время подключения BLE реклама, ту которую принимает HA, не передается. |
спасибо за уделенное время. пока безуспешно. на тлф в браузере все ок |
Отключите соединение с термометром в Android и в других. Закройте эксплорер. |
@pvvx еще маленький вопрос, значок Bluetooth на самом устройстве что обозначает и должен ли он отображаться в момент рекламы (или соединения)? |
Значок Bluetooth активен только во время соединения и мигает если нажата впаянная кнопка или геркон с выбором в меню функции геркона/кнопки "соединение" (обычно для Long Range). |
@pvvx вместо Xiaomi BLE, установил аддон Passive BLE Monitor |
ASUS BT500
***@***.***:~$ bluetoothctl devices
Device F2:FE:77:F8:2B:5C F2-FE-77-F8-2B-5C
Device 54:EF:44:48:5D:E2 54-EF-44-48-5D-E2
Device A4:C1:38:94:08:E2 LYWSD03MMC
Device A4:C1:38:93:D5:64 LYWSD03MMC
Device A4:C1:38:D1:0C:8C LYWSD03MMC
Device C5:83:F5:63:9F:A6 SumUp 100
Device C4:30:18:EA:B9:C7 JBL PartyBox 100
Device A5:73:B3:0F:94:CE Wuzhi Audio
Haldyz ***@***.***> ezt írta (időpont: 2024. jan. 4., Cs,
9:56):
… I would buy a new one, but i would like to have some recommendation. This
one i have bough this one from the same Ali link you have shared
previously. It seems to be the same like on your picture marked as V5.1 (*Barrot
BR865101*).
image.png (view on web)
<https://github.com/pvvx/ATC_MiThermometer/assets/77940005/e2f36f6b-ce56-4891-a792-151a6ae7bfd4>
I have also one more dongle, which is marked as V5.0, where is *Barrot
8041A02* chip:
image.png (view on web)
<https://github.com/pvvx/ATC_MiThermometer/assets/77940005/9d7a6f21-f22e-4ca1-abdc-9912d29f8d74>
This one is recognized on my RPi like bellow, but its not connecting to Mi
Thermometers at all:
#lsusb
Bus 001 Device 003: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
#hciconfig -a
hci2: Type: Primary Bus: USB
BD Address: 00:1A:7D:DA:71:11 ACL MTU: 679:9 SCO MTU: 48:16
UP RUNNING
RX bytes:684 acl:0 sco:0 events:48 errors:0
TX bytes:3362 acl:0 sco:0 commands:48 errors:0
Features: 0xff 0xff 0x87 0xfa 0xdb 0xbf 0x7b 0x83
Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
Link policy: RSWITCH HOLD SNIFF PARK
Link mode: SLAVE ACCEPT
Name: 'raspberrypi #3'
Class: 0x4c0000
Service Classes: Rendering, Capturing, Telephony
Device Class: Miscellaneous,
HCI Version: 5.0 (0x9) Revision: 0x810
LMP Version: 5.0 (0x9) Subversion: 0x2512
Manufacturer: Cambridge Silicon Radio (10)
You have previously recommended to buy a Realtek RTL8761 BT adapter, but
its not easy to find it on Ali according to the chipset name. Can you
recommend some dongle which is tested and working well please?
—
Reply to this email directly, view it on GitHub
<#297 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AE3B7YKDLQSP4PQWAIOUJJ3YMZVEFAVCNFSM6AAAAAAU7QUZZ6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQNZWG4ZDSMBYGI>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>
--
Barják László +36209347499
|
For "LE Long Range" only RTL8761. Otherwise, there are either a lot of errors in the firmware, or very poor sensitivity of the receiver. LE Long Range -> RTL8761BU (BT5.3) The best reception with the built-in antenna: sensitivity is better than -108..110 dBm. Realtek updates firmware. The firmware is available for download. Loaded into the adapter's RAM at startup. It is possible to create an alternative firmware if you obtain information from Realtek. USB\VID_0BDA&PID_8771&REV_0200 - https://aliexpress.com/item/4001097686145.html RTL8761B https://www.home-assistant.io/integrations/bluetooth/#realtek-rtl8761bu-adapters |
Thank you, I have ordered ASUS USB-BT500 from my local store, so I hope it will work well. |
https://www.asus.com/networking-iot-servers/adapters/all-series/usb-bt500/helpdesk_download?model2Name=USB-BT500
sudo apt install build-essential
sudo make install INTERFACE=usb
Haldyz ***@***.***> ezt írta (időpont: 2024. jan. 9., K,
10:58):
… Hello. I have finally received my new dongle - ASUS USB-BT500, which
should be based on RTL8761BU.
But it seems it doesn't work on my RPi. I can see it in hciconfig, but the
HCI even LMP Version is (0xa), which I don't think its right.
# hciconfig:
hci0: Type: Primary Bus: USB
BD Address: C8:7F:54:98:B9:2B ACL MTU: 1021:6 SCO MTU: 255:12
UP RUNNING
RX bytes:16805 acl:0 sco:0 events:1389 errors:0
TX bytes:19200 acl:0 sco:0 commands:1353 errors:0
Features: 0xff 0xff 0xff 0xfe 0xdb 0xfd 0x7b 0x87
Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
Link policy: RSWITCH HOLD SNIFF PARK
Link mode: SLAVE ACCEPT
Name: 'raspberrypi #1'
Class: 0x4c0000
Service Classes: Rendering, Capturing, Telephony
Device Class: Miscellaneous,
HCI Version: (0xa) Revision: 0xb
LMP Version: (0xa) Subversion: 0x8761
Manufacturer: Realtek Semiconductor Corporation (93)
# lsusb:
Bus 001 Device 003: ID 0b05:190e ASUSTek Computer, Inc.
I have tested for now with one thermometer (LYWSD03MMC) and your latest
firmware (v4.6) with following settings, but it's not connected via BTHome
addon in HA.
image.png (view on web)
<https://github.com/pvvx/ATC_MiThermometer/assets/77940005/37c37e93-98ed-41de-8fbd-99fb3718d684>
image.png (view on web)
<https://github.com/pvvx/ATC_MiThermometer/assets/77940005/d6ae125e-ab3f-46a7-8a0d-81cd9bd9a7ad>
image.png (view on web)
<https://github.com/pvvx/ATC_MiThermometer/assets/77940005/35419319-572f-4648-ae55-e95f7e9ea2ca>
Any idea what can be wrong please? Maybe a driver issue?
The only thing I have done was following settings followed by reboot of my
RPi:
hcitool -i hci0 cmd 08 31 03 05 05
—
Reply to this email directly, view it on GitHub
<#297 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AE3B7YIMGPEEXJTKXUSR55TYNUICRAVCNFSM6AAAAAAU7QUZZ6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQOBSG42TIMZTGM>
.
You are receiving this because you commented.Message ID:
***@***.***>
--
Barják László +36209347499
|
My RPi 4B is running on 32bit OS with Linux Kernel 5.10.103-v7l+ armv7l.
I can try to copy and overwrite the files rtl8761bu_config & rtl8761bu_fw from dwonloaded driver to /lib/firmware/, but I'm not sure, if its a good idea (because of Kernel version). I'm sorry, I'm not a Linux guru. |
raspberrypi/linux#5110
Haldyz ***@***.***> ezt írta (időpont: 2024. jan. 9., K,
12:20):
… My RPi 4B is running on 32bit OS with Linux Kernel 5.10.103-v7l+ armv7l.
On Asus pages is a 32bit driver which support kernel 2.6.32 - 4.15 - so my
Kernel seems to be not supported.
When I checked /lib/firmware/ there are already rtl8761bu_config &
rtl8761bu_fw files dated from 4.4.2023
sudo apt install build-essential
says build-essential is already the newest version (12.6).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
sudo make install INTERFACE=usb
make: *** No rule to make target 'install'. Stop.
I can try to copy and overwrite the files rtl8761bu_config & rtl8761bu_fw
from dwonloaded driver to /lib/firmware/, but I'm not sure, if its a good
idea (because of Kernel version).
I'm sorry, I'm not a Linux guru.
—
Reply to this email directly, view it on GitHub
<#297 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AE3B7YI5JCLCSOLF2H3DDHTYNURXLAVCNFSM6AAAAAAU7QUZZ6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQOBSHA4DONJSGM>
.
You are receiving this because you commented.Message ID:
***@***.***>
--
Barják László +36209347499
|
Thank you @lbarjak . I have downloaded fw and config files from the link above and I have copied them to my RPi:
Then it was needed to switch the adapter to work with CodedPHY: The main issue was probably the setting for CodedPHY. not the driver.
and seems that only 04 is working fine for me. One more thing I want to ensure - is the following settings the best option for BLE? And the last question is about 'BTHome integration' vs 'Passive BLE Monitor' in HA. PS: "Packet Id" & "Signal Strength" is not available in BTHome. Update: Thank you |
Realtek has long released a firmware (rtl8761bu_fw.bin, rtl8761bu_config.bin) version with BT5.3 for RTL8761BU.
Bit0 - PHY 1Mbit (BLE Legacy) |
I'm sorry Victor for a dumb question, but I really do not understand the relation between i.e. 04 04 and the Bit0 - Bit3 you have described above. Please can you share more details? I'm interesting in which case to use 04/05/07 or maybe some other? My intention is to have as long range as possible. And if you stated that Realtek has long released a firmware with BT5.3 for RTL8761BU, do you mean that adapter based on RTL8761BU which was sold as BT5.0 will support BT5.3 with latest firmware? Thank you |
https://en.m.wikipedia.org/wiki/Binary_number#Binary_counting |
Thank you @fanoush So my understanding is following:
Then becomes a question - which PHY is supported by my adapter (RTL8761BU)?
I can try it just by testing of each combination, so if I understand it right, the best should be 08 31 03 07 07, where all bellow options should be available: Am I right? PS:
|
For BLE advertising, the standard will be 0x05 to receive the advertising header on the main channels. That is, only 1M PHY and Coded S8 PHY are allowed in the Bluetooth SIG standard. 2M PHY is used only after negotiation during connection. Or with extended advertising, after receiving a header on 1M PHY or Сoded S8 PHY, which indicates that the second part will be on 2M PHY on an additional channel. Therefore, 2 values are used - for the main channel and for the additional one. But this is not in the Linux API, which makes it impossible to support BT5.0. - Linux is dead.
This chip supports all PHYs. But that doesn't indicate what Bluez supports. Bluez is limited to pre-2014 knowledge. |
@pvvx : but if bluez is frozen in 2014, and windows is in the same bad situation, and ESP32 simply don't support BLE LR.. What are you using on the remote side of your sensors? I get you have a realtek USB adapter, the one I bought too on aliexpress.. But what OS? What BLE to MQTT solution (if any)? |
One option could be dedicated usb dongle based on nrf52840. I do have long range/coded phy working in Espruino which is javascript interpreter acessible over usb serial (or BLE of course). There is also See e.g. this https://forum.espruino.com/conversations/393987/ or https://forum.espruino.com/conversations/361380/ I don't use home assistant or MQTT but I believe it should work. One possible hardware is E104-BT5040U which is ~US$10 thing on Aliexpress https://www.aliexpress.com/item/1005004625411410.html It is compatible with original Nordic 52840 dongle (PCA10059) so all the tools work with it just fine, you can upload new firmware over USB with nRF Connect for Desktop which is available both for Windows and Linux. Here is quick sample of scanning for all devices advertising over coded PHY showing one of my thermometers switched to long range mode.
EDIT: or for cheaper 52840 boards check https://github.com/joric/nrfmicro/wiki/Alternatives |
@fanoush - NRF has not released USB-BT adapters or software for these options. |
I don't use MQTT. I receive BLE in Home Assistant using two simple USB-BT adapters. One works for the near zone, the second for the far zone in the “LE Long Range” mode. |
I am not talking about (normal HCI) USB-BT adapters. With espruino these dongles can run your stored javascript code, talk to anything over BLE and then write to USB serial any output you need. So the logic is in javascrit code inside the dongle, if the MQTT broker (like EspruinoHub) or the Home Assistant directly can read from serial port it should work. |
No versatility. For each task on NRF you will have to create a new program. Today there are cheaper chips with full support for BT 5.4 from WCH. Less than 1 dollar. The CH32V208W is a little more expensive. It has BT5.4, USB, Ethernet,... The SDK contains examples of working with BLE+MQTT+Ethernet... |
Oh! Well, I think you don't quite get it with the versatility, but never mind. if you have solution that works for you than that's great. Here is one example of 'no versatility' https://www.espruino.com/Pixl.js+BLE+Ethernet+Bridge - it is NRF device with BLE and ethernet shield connected over SPI. In just few lines of javascript you convert any BLE advertisement seen around into MQTT message and send it to server over ethernet. You don't need to write that stuff in C like with SDK for CH32V208W . If there would be e.g. micropython for that CH32V208W with working BLE api that can do long range then it would be similar. |
Who cares - I can do it faster in C. But no one has been able to write a normal BLE gateway on nRF. For years already. And who in the modern world needs chips with libraries in blobs? NRF - proprietary software. - Correction of errors in nRF binary libs has to wait for years. |
I would like to copy a specific long range solution, put one up, whether c
or js.
Victor ***@***.***> ezt írta (időpont: 2024. febr. 15., Cs
19:41):
… Who cares - I can do it faster in C.
—
Reply to this email directly, view it on GitHub
<#297 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AE3B7YMVI7DHMJYNEPPFSO3YTZJFBAVCNFSM6AAAAAAU7QUZZ6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSNBWHEYTQNBVGY>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
Not sure what you mean by "normal BLE gateway". If you mean HCI then we already discussed that, it is part of ZephyrOS and works. However due to poor Linux support as you said many times it is not very useful to get long range/coded phy working in Linux.
This was already discussed too. There are several open source production ready certified BLE stacks for nRF5x chips. Hardly any other chip has such wide open source support. There is ZephyrOS which is also current supported official SDK from Nordic (called nRF Connect SDK), there is also Apache NimBLE and there is at least one commercial one with full sources on GitHub which I think needs license for commercial use (forgot its name, maybe it was this one https://github.com/packetcraft-inc/stacks ?). SoftDevices are legacy and you are definitely not forced (or even recommended) to use them if you don't appreciate the advantages (stability, simplicity, clear separation from your code). |
Again, one nRF advertisement, but in reality there are no devices for users or DIY on nRF.
I want to enable 'PAWR' on all thermometers, but users have no adapters capable of working with PAwR. |
Well I was just disproving your untruths. Would be nice if you could stop so there is no need to correct you over and over again (it is also off topic here). Sadly you just did it again. There are of course tons of nrf5x based devices directly targeted for DYI both made by companies and also individuals and there is also a lot of hackable cheap nrf52 based stuff on aliexpress (smartwatches, fitness trackers, NFC+BLE keychains). For companies just check sparkfun or adafruit for their own nrf5x boards, adafruit even maintains Arduino and also Circuitpython for nrf52 just check list here https://github.com/adafruit/circuitpython/tree/main/ports/nrf/boards , also Microbit is NRF, the version 2 is 52833 and widely available (version 1 was bad IMO but 2 is nice). The Espruino stuff is mostly nrf52, previously I linked nrf52 boards for doing custom BLE/USB HID keyboards https://github.com/joric/nrfmicro/wiki/Alternatives For some reason they like 52840 based boards for this, not sure why, but they are probably quite popular as they got cloned and sold on aliexpress in quantities (google "ZMK firmware"). The Pinetime watch is nrf52832 - they are using Apache NimBLE there in their firmware. In fact it is one of many cheap hackable OTA updatable DaFit nrf5x based smartwatches which come in many shapes and sizes. One example is the 12 EUR "C17" nrf52840 one a.k.a. Magic 3 you can find on aliexpress now but there are many others. So you must be living in some parallel universe to say that thing I quoted. Or you just like to troll.
Oh, that is actually interesting stuff I did not know yet. Some time ago I tried to sync precise time via advertising but got bitten by that random delay and also wanted to send different scan response based on who is asking (so having bidirectional communication via advertising+scan response), it is nice someone was thinking in same direction and fixing both issues :-) GATT and connections are too heavy for a lot of stuff. |
Where is the firmware for this thermometer to work in BTHome? You are describing some toys that are not needed in IoT. Low cost BLE Advertisements Repeater into Ethernet TCP/IP @fanoush - How long will you advertise nRF or will you do something? :) :)
Or do you need to block access to the repository "from this universe"? :) |
I wanted to move from my esp32 to bluetooth on my RPi and found this thread from the docs. Or is this only for people who use their wifi, because yes, then bluetooth does not work properly anymore. But with wifi disabled, should the internal one not be sufficient? |
предлагаемые что nrf, что wch и esp - новые сущности, для которых нужны будут и драйвера и софт. получается эдакий черный ящик по типу zigbee - мало кто знает как оно вообще работает внутри, просто даем нужные (AT) команды и получаем результат. При этом пока что эта штука будет diy - потребуется некоторые умения, чтобы просто собрать ее и прошить. |
Сокращать или оптимизировать код - это не в духе современных программистов. Драйвер в Linux kernel не умеет работать с чипами в BT5.0+. И решений не предвидится. Ситуация в Linux с WiFi, Zigbee, SSD/NVME, CPU, ... аналогична. Никакой поддержки стандартов вышедших десятилетие назад. Только частичная - выборочная и кривая. |
Предварительное описание решения.
Для примера можно взять:
Low-cost Realtek RTL8761 BT adapter
USB ID 0bda:8771 Realtek Semiconductor Corp. Bluetooth Radio
Сurrent version of Linux fw on RTL8761 supports BT5.1:
Для работы HA c LE Long Range в интеграции “Bluetooth” желательно установить последнюю версию bluez и добавить в файле /lib/systemd/system/bluetooth.service
ExecStart=/usr/local/libexec/bluetooth/bluetoothd --experimental
Из-за неверной инициализации адаптеров BT5.+ в Bluez, перед запуском Home Assistant необходимо переключить BT адаптер на работу в режим Bluetoch 5.0:
hcitool -i hci1 cmd 08 31 03 05 05
или во всех режимах PHY 1M/2M/Coded:
hcitool -i hci1 cmd 08 31 03 07 07
Номер hciN - свой.
Проверить переключение возможно в btmon (log btmon):
В итоге, в интеграции "BTHome" получаем успешный прием термометров со стандартной рекламой и работающих в LE Long Range:
Если адаптер будет работать неустойчиво, тогда HA может его переинициализировать и настройка на работу в Coded PHY (Long Range) собьется. Ожидать официальной поддержки в интеграции “Bluetooth” нет никакой возможности. Выбранный автором API “Bleak” не позволяет управлять PHY адаптера и не предвидится никакой поддержки BLUETOOTH SPECIFICATION Version 5.0 от 2016 года.
Проверить адаптер на совместимость возможно с помощью команд:
Установка вариантов PHY в btmgmt работает не совсем корректно (в некоторых вариантах имеются ошибки). Но и с помощью этой программы возможно установить необходимые PHY.
Для этого необходимо:
Для установки PHY через API в bluez смотреть /doc/mgmt-api.txt.
Или через hci_send_cmd(). Пример для Python (неполный и не совсем корректный):
The text was updated successfully, but these errors were encountered: