Esp32 bluetooth low energy tracker hub

ESP32 BLETracker

preview

This firmware help you to track a Bluetooth Low Energy device with an ESP32, using the MQTT protocol and Home Assistant or FHEM and the collectord daemon.
Please note that the targeted device can’t have a changing BLE address (normally called ‘random’ instead of ‘public’ address).

What this firmware can do for you:

  • Tracks all discovered ble devices or only the desired devices placed in a white-list
  • Selectively reads the battery level of tracked devices
  • Generates MQTT topic for an easy integration in you favorite Home Automation Hub
  • Mimics a lepresenced server to be integrated in FHEM
  • You can configure the devices to be tracked directly from the integrated WebServer without need to re-flash the firmware
  • Supports for OTA Update
  • Logs main events in order to identify problems.

Easy to build

Use PlatformIO to build and deploy this firmware, remember to install git in order to allow PlatformIO to download automatically all the required dependencies.
You have to modify the user_config.h file inserting the correct information to connect to the WiFi and to the MQTT broker.
The GATEWAY_NAME is used as Client ID to connect to the broker so be sure it’s unique.
The battery level can be read from the devices providing the Battery Service (0x180F) and the Battery Level characteristic (0x2A19), check the availability using a nRF Sniffer i.e. nRF Connect
This feature was successfully tested with a Nut Mini, using other devices you could have connection problems.
If many devices are discovered the battery level check can be very slow causing frequent Wi-Fi disconnection so that I have introduced a whitelist containing the Mac Address of the devices to check. The whitelist is in the form:
BLE_BATTERY_WHITELIST “XXXXXXXXX”,”YYYYYYYY”
Mac Addresses have to be uppercase without “:” or “-“ i.e “BA683F7EC159”

MQTT integration

The firmware can generate the following topics:
A topic for the BLETracker state:
///LWT payload:

A single topic with the payload in JSON format containing all the items returned by the device (this is the default):
//,”rssi”:,”battery”:>

Читайте также:  Драйвер блютуз acer v3 571

WEB Server

A WEB server is integrated into the BLETracker, it can be accessed using a web browser and the ip or the network name of the tracker.
The WEB server can be used to see some system information and to update the firmware using an OTA Update, simply choosing the .bin file to upload.
Default credential to access the WEB Server are:
user: admin
password: admin

The new WEB server interface allow to customize the list of devices to be tracked, the scan period, and the MQTT broker parameters.
The new interface allows also to monitor some logs. The number of logs is limited and when the maximum capacity is reached the oldest are removed.

indexpage systempage configpage logspageotapage

FHEM Support

If properly configured the BLETracker can be integrate in your FHEM environment. Instead publishing MQTT tokens the BLETracker can be configured to act as a lepresenced daemon. A server will run on the port 5333 listening for incoming connection generated by the collectord. The FHEM support and the MQTT support are mutually exclusive because of memory issues. The FHEM support can be easily enabled using Platform.io simply choosing the esp32dev-ble-fhem-release build variant.
The values of presence_timeout and absence_timeout stored in the collectord.conf cannot be less than or equal to the BLE_SCANNING_PERIOD (default is 10 seconds).

Build with Arduino IDE

You can build this sketch using Arduino IDE (currently it’s using arduino-esp32 v1.0.4), but be sure to install the required dependencies:

  • You have to install the esp32 Board in Arduino IDE. You can find a tutorial following this link
  • You have to install the library PubSubClient v2.8 (not needed if you want enable FHEM support)
  • To enable the FHEM support you have to:
    • install the Regexp library (https://www.arduino.cc/reference/en/libraries/regexp/)
    • set USE_MQTT to false and USE_FHEM_LEPRESENCE_SERVER to true in the config.h

    Build using the Minimal SPIFFS partition schema.

    Licence

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the “Software”), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

    If you like the content of this repo, please add a star! Thank you!

    Support my work

    If you like my work, please consider buying me a coffee. Thank you for your support!

    This page was generated by GitHub Pages.

    Источник

    Блютуз прокси на ESP32 в ESPHome. Bluetooth proxy.

    Не так давно появилась в ESPHome очень интересная функция, которая обошла меня стороной.

    Дело в том, что у меня установлен Home Assistant На Raspberry pi 4 и блютуза встроенного в Raspberry pi 4 мне хватало. ПО этому я не обращал внимание на Bluetooth proxy от ESPHome.

    Но беда пришла откуда не ждали. Я начал разбираться с датчиком движения LD2410B. И установить с ним Bluetooth соединение не получалось. Raspberry pi 4 с Home Assistant На борту его не находила. Хотя телефон вполне к нему подключался через приложение.

    И вот поломав голову изменяя настройки датчика, решил попробовать Bluetooth proxy от ESPHome. Загрузив буквально несколько строчек кода, у меня тут-же датчик движения LD2410B нашелся и пробросился в Home Assistant.

    По этому я и решил сделать эту статью, чтоб помочь людям, у которых такая же проблема возникнет. Или просто если на компьютере с Home Assistant нет Bluetooth модуля, то это очень удобный способ будет для добавления устройств Bluetooth в Home Assitant.

    Bluetooth proxy ESPHome.

    Bluetooth-прокси ESPHome предоставляет Home Assistant максимум 3 одновременных активных соединения. Устройства, которые поддерживают постоянное активное соединение, будут потреблять одно из них постоянно, в то время как устройства, которые периодически отключаются и снова подключаются , позволяют использовать более 3 из них (на статистической основе). Пассивно передаваемые данные датчиков (которые рекламируются определенными устройствами без активных подключений) принимаются отдельно от них и не ограничиваются определенным количеством.

    Компонент веб-сервера следует отключить, так как в устройстве может не хватить памяти, и при одновременном включении обоих компонентов устройство может работать со сбоями.

    Поддерживаются не все устройства, а ESPHome не декодирует и не ведет список. Чтобы узнать, поддерживается ли ваше устройство, найдите его в списке интеграций Home Assistant .

    С предупреждением разобрались, идем далее.

    По сути Bluetoot proxy включается двумя строчками кода:

    bluetooth_proxy: active: true
    • active ( Необязательный , логическое значение): Включает проксирование активных подключений. По умолчанию false . Требуется Home Assistant 2022.10 или новее.

    Добавив этот параметр, у Вас включится Buetooth прокси, но есть еще некий параметр, который улучшит связт Bluetooth.

    Улучшение качества приема

    Используйте плату с Ethernet-подключением к сети, чтобы разгрузить радиомодуль ESP32 от трафика WiFi, это повышает производительность на стороне Bluetooth.

    Но у меня и по Wi-fi отлично все работает. Правда я на модуль ничего больше не вешал кроме Bluetooth proxy функции.

    Чтобы максимизировать шансы поймать рекламу датчиков, вы можете установить interval равным window в настройках параметров сканирования ESP32 Bluetooth Low Energy Tracker Hub :

    esp32_ble_tracker: scan_parameters: interval: 1100ms window: 1100ms 

    Для прокси-серверов на основе WiFi изменение значений по умолчанию interval или window значений по умолчанию может привести к нестабильному соединению WiFi. Использование значений по умолчанию для interval и window обычно устраняет любую нестабильность.

    Ну и собственно конечный результат у меня выглядит так:

    esp32_ble_tracker: scan_parameters: interval: 1100ms window: 1100ms active: true bluetooth_proxy: active: true 

    Добавив эти несколько строчек кода и добавив получившееся устройство в Home Assistant, у Вас моментально начнут появляться новые устройства для добавления в Home Assistant по Bluetooth.

    Вот как у меня это выглядело. Как работало на штатном bluetooth raspbery pi 4. Видно, что нашлось какое-то одно устройство Bluetooth:

    Ну а как только я добавил Bluetooth proxy, картина тут-же изменилась:

    И мой многострадальный датчик LD2410B сразу нашелся.

    P.S. Bluetooth proxy поддерживается и ESP32-C3.

    Источник

Оцените статью
Adblock
detector