diff --git a/environments.ini b/environments.ini index cf462a9..95c14fa 100644 --- a/environments.ini +++ b/environments.ini @@ -126,10 +126,10 @@ build_flags = custom_description = BLE gateway with external antenna and Ethernet/WiFi connectivity, [user guide](https://tbridge02.theengs.io/) custom_hardware = Theengs Bridge gateway ethernet -; DISCLAIMER: This is the default environment for Theengs Plug. +; DISCLAIMER: This is the default environment for Theengs Plug. ; Any modifications to this configuration are not covered by warranty. ; Proceed with caution when making changes. -; +; ; SAFETY WARNING: Do not modify values related to current limits MAX_CURRENT_ACTUATOR or other ; safety-critical parameters. Doing so may lead to fire hazards or damage to the device. [env:theengs-plug] @@ -143,7 +143,7 @@ lib_deps = ${libraries.decoder} ${libraries.adafruit_neopixel} ${libraries.rn8209} -build_flags = +build_flags = ${env.build_flags} ${com-esp32.build_flags} '-DZgatewayBT="BT"' @@ -1811,7 +1811,7 @@ build_flags = '-DCONFIG_ESP_CONSOLE_UART=ESP_CONSOLE_USB_SERIAL_JTAG' [env:esp32c3-m5stamp] -; https://docs.m5stack.com/en/core/stamp_c3 +; https://docs.m5stack.com/en/core/stamp_c3 platform = ${com.esp32_platform} board = esp32-c3-devkitm-1 board_build.partitions = min_spiffs.csv @@ -1834,7 +1834,7 @@ custom_description = BLE gateway on ESP32C3 custom_hardware = M5Stamp C3 [env:esp32c3u-m5stamp] -; https://docs.m5stack.com/en/core/stamp_c3u +; https://docs.m5stack.com/en/core/stamp_c3u platform = ${com.esp32_platform} board = esp32-c3-devkitm-1 board_build.partitions = min_spiffs.csv @@ -1898,8 +1898,9 @@ extra_scripts = ${com-esp32.extra_scripts} board_build.partitions = partitions/min_spiffs.csv lib_deps = ${com-esp32.lib_deps} - ${libraries.ble} ${libraries.decoder} + h2zero/esp-nimble-cpp@2.0.1 + h2zero/NimBLEOta@0.1.0 build_flags = ${com-esp32.build_flags} '-DZgatewayBT="BT"' @@ -1908,5 +1909,5 @@ build_flags = '-DGateway_Name="OMG_ESP32_BLE"' '-DUSE_BLUFI=1' '-DenableMultiGTWSync=false' - '-DARDUINO_LOOP_STACK_SIZE=17500' + '-DCONFIG_NIMBLE_CPP_FREERTOS_TASK_BLOCK_BIT=31' custom_description = Regular BLE gateway based on esp-idf with adaptive scanning activated, automatically adapts the scan parameters depending on your devices diff --git a/main/Zblufi.ino b/main/Zblufi.ino index cfba591..dfdee34 100644 --- a/main/Zblufi.ino +++ b/main/Zblufi.ino @@ -27,6 +27,7 @@ */ #if defined(ESP32) && defined(USE_BLUFI) # include "NimBLEDevice.h" +# include "NimBLEOta.h" # include "esp_blufi_api.h" # include "esp_timer.h" @@ -35,6 +36,9 @@ extern "C" { } static esp_timer_handle_t connection_timer = nullptr; +static NimBLEOta* pNimBLEOta; +static NimBLECharacteristic* pCommandCharacteristic; +static NimBLECharacteristic* pRecvFwCharacteristic; struct pkt_info { uint8_t* pkt; @@ -183,6 +187,8 @@ void stop_connection_timer() {} static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_param_t* param) { /* actually, should post to blufi_task handle the procedure, * now, as a example, we do it more simply */ + ble_gap_conn_desc desc; + switch (event) { case ESP_BLUFI_EVENT_INIT_FINISH: Log.trace(F("BLUFI init finish" CR)); @@ -201,6 +207,10 @@ static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_para gatewayState = GatewayState::ONBOARDING; omg_blufi_ble_connected = true; restart_connection_timer(); + ble_gap_conn_find(param->connect.conn_id, &desc); + // Blufi dosn't provide a callback for subscribe so we emulate it here. + pCommandCharacteristic->getCallbacks()->onSubscribe(pCommandCharacteristic, *(NimBLEConnInfo*)&desc, 2); + pRecvFwCharacteristic->getCallbacks()->onSubscribe(pRecvFwCharacteristic, *(NimBLEConnInfo*)&desc, 2); esp_blufi_adv_stop(); blufi_security_init(); break; @@ -217,6 +227,9 @@ static void example_event_callback(esp_blufi_cb_event_t event, esp_blufi_cb_para } else { gatewayState = GatewayState::OFFLINE; } + ble_gap_conn_find(param->connect.conn_id, &desc); + pCommandCharacteristic->getCallbacks()->onSubscribe(pCommandCharacteristic, *(NimBLEConnInfo*)&desc, 0); + pRecvFwCharacteristic->getCallbacks()->onSubscribe(pRecvFwCharacteristic, *(NimBLEConnInfo*)&desc, 0); blufi_security_deinit(); esp_blufi_adv_start(); break; @@ -386,7 +399,7 @@ bool startBlufi() { return false; } - if (NimBLEDevice::getInitialized()) { + if (NimBLEDevice::isInitialized()) { NimBLEDevice::deinit(true); delay(50); } @@ -401,7 +414,14 @@ bool startBlufi() { } snprintf(advName, sizeof(advName), Gateway_Short_Name "_%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); NimBLEDevice::init(advName); + NimBLEDevice::setMTU(517); + NimBLEDevice::createServer(); // this initializes the GATT server so we need to reset it for blufi to init + ble_gatts_reset(); esp_blufi_gatt_svr_init(); + pNimBLEOta = new NimBLEOta(); + NimBLEService* pNimBLEOtaSvc = pNimBLEOta->start(); + pCommandCharacteristic = pNimBLEOtaSvc->getCharacteristic(NimBLEUUID((uint16_t)0x8022)); + pRecvFwCharacteristic = pNimBLEOtaSvc->getCharacteristic(NimBLEUUID((uint16_t)0x8020)); ble_gatts_start(); Log.notice(F("BLUFI started" CR)); return esp_blufi_profile_init() == ESP_OK; diff --git a/main/ZgatewayBLEConnect.h b/main/ZgatewayBLEConnect.h index cedbd77..1d8ca0e 100644 --- a/main/ZgatewayBLEConnect.h +++ b/main/ZgatewayBLEConnect.h @@ -12,7 +12,7 @@ public: TaskHandle_t m_taskHandle = nullptr; zBLEConnect(NimBLEAddress& addr) { m_pClient = NimBLEDevice::createClient(addr); - m_pClient->setConnectTimeout(5); + m_pClient->setConnectTimeout(5000); } virtual ~zBLEConnect() { NimBLEDevice::deleteClient(m_pClient); } virtual bool writeData(BLEAction* action); diff --git a/main/ZgatewayBLEConnect.ino b/main/ZgatewayBLEConnect.ino index 2f18f20..855d05e 100644 --- a/main/ZgatewayBLEConnect.ino +++ b/main/ZgatewayBLEConnect.ino @@ -44,11 +44,12 @@ bool zBLEConnect::writeData(BLEAction* action) { } std::vector buf; + buf.reserve(len / 2); for (auto i = 0; i < len; i += 2) { - std::string temp = action->value.substr(i, 2); - buf.push_back((uint8_t)strtoul(temp.c_str(), nullptr, 16)); + char sVal[3] = {action->value[i], action->value[i + 1], 0}; + buf.push_back((uint8_t)strtoul(sVal, nullptr, 16)); } - return pChar->writeValue((const uint8_t*)&buf[0], buf.size(), !pChar->canWriteNoResponse()); + return pChar->writeValue(&buf[0], buf.size(), !pChar->canWriteNoResponse()); } case BLE_VAL_INT: return pChar->writeValue(strtol(action->value.c_str(), nullptr, 0), !pChar->canWriteNoResponse()); @@ -80,13 +81,13 @@ bool zBLEConnect::processActions(std::vector& actions) { if (NimBLEAddress(it.addr) == m_pClient->getPeerAddress()) { DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; + BLEdata["id"] = m_pClient->getPeerAddress().toString().c_str(); BLEdata["service"] = it.service.toString(); BLEdata["characteristic"] = it.characteristic.toString(); if (it.write) { Log.trace(F("processing BLE write" CR)); - BLEdata["write"] = it.value; + BLEdata["write"] = std::string(it.value); result = writeData(&it); } else { Log.trace(F("processing BLE read" CR)); @@ -94,9 +95,7 @@ bool zBLEConnect::processActions(std::vector& actions) { if (result) { switch (it.value_type) { case BLE_VAL_HEX: { - char* pHex = NimBLEUtils::buildHexData(nullptr, (uint8_t*)it.value.c_str(), it.value.length()); - BLEdata["read"] = pHex; - free(pHex); + BLEdata["read"] = NimBLEUtils::dataToHexString(it.value.data(), it.value.size()); break; } case BLE_VAL_INT: { @@ -141,19 +140,18 @@ void LYWSD03MMC_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pD Log.trace(F("Device identified creating BLE buffer" CR)); DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); + auto mac_addr = m_pClient->getPeerAddress().toString().c_str(); for (std::vector::iterator it = devices.begin(); it != devices.end(); ++it) { BLEdevice* p = *it; - if ((strcmp(p->macAdr, (char*)mac_address.c_str()) == 0)) { + if ((strcmp(p->macAdr, mac_addr) == 0)) { if (p->sensorModel_id == BLEconectable::id::LYWSD03MMC) BLEdata["model"] = "LYWSD03MMC"; else if (p->sensorModel_id == BLEconectable::id::MHO_C401) BLEdata["model"] = "MHO-C401"; } } - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); + BLEdata["id"] = mac_addr; + Log.trace(F("Device identified in CB: %s" CR), mac_addr); BLEdata["tempc"] = (float)((pData[0] | (pData[1] << 8)) * 0.01); BLEdata["tempf"] = (float)(convertTemp_CtoF((pData[0] | (pData[1] << 8)) * 0.01)); BLEdata["hum"] = (float)(pData[2]); @@ -212,11 +210,10 @@ void DT24_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, s Log.trace(F("Device identified creating BLE buffer" CR)); DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); + auto mac_address = m_pClient->getPeerAddress().toString().c_str(); BLEdata["model"] = "DT24"; - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); + BLEdata["id"] = mac_address; + Log.trace(F("Device identified in CB: %s" CR), mac_address); BLEdata["volt"] = (float)(((m_data[4] * 256 * 256) + (m_data[5] * 256) + m_data[6]) / 10.0); BLEdata["current"] = (float)(((m_data[7] * 256 * 256) + (m_data[8] * 256) + m_data[9]) / 1000.0); BLEdata["power"] = (float)(((m_data[10] * 256 * 256) + (m_data[11] * 256) + m_data[12]) / 10.0); @@ -269,10 +266,8 @@ void BM2_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* pData, si Log.trace(F("Device identified creating BLE buffer" CR)); DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); BLEdata["model"] = "BM2 Battery Monitor"; - BLEdata["id"] = (char*)mac_address.c_str(); + BLEdata["id"] = m_pClient->getPeerAddress().toString().c_str(); mbedtls_aes_context aes; mbedtls_aes_init(&aes); unsigned char output[16]; @@ -356,10 +351,8 @@ void HHCCJCY01HHCC_connect::publishData() { batteryValue = val2[0]; DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); BLEdata["model"] = "HHCCJCY01HHCC"; - BLEdata["id"] = (char*)mac_address.c_str(); + BLEdata["id"] = m_pClient->getPeerAddress().toString().c_str(); BLEdata["batt"] = (int)batteryValue; buildTopicFromId(BLEdata, subjectBTtoMQTT); enqueueJsonObject(BLEdata, QueueSemaphoreTimeOutTask); @@ -383,11 +376,10 @@ void XMWSDJ04MMC_connect::notifyCB(NimBLERemoteCharacteristic* pChar, uint8_t* p Log.trace(F("Device identified creating BLE buffer" CR)); DynamicJsonDocument BLEdataBuffer(JSON_MSG_BUFFER); JsonObject BLEdata = BLEdataBuffer.to(); - String mac_address = m_pClient->getPeerAddress().toString().c_str(); - mac_address.toUpperCase(); + auto mac_address = m_pClient->getPeerAddress().toString().c_str(); BLEdata["model"] = "XMWSDJ04MMC"; - BLEdata["id"] = (char*)mac_address.c_str(); - Log.trace(F("Device identified in CB: %s" CR), (char*)mac_address.c_str()); + BLEdata["id"] = mac_address; + Log.trace(F("Device identified in CB: %s" CR), mac_address); BLEdata["tempc"] = (float)((pData[0] | (pData[1] << 8)) * 0.1); BLEdata["tempf"] = (float)(convertTemp_CtoF((pData[0] | (pData[1] << 8)) * 0.1)); BLEdata["hum"] = (float)((pData[2] | (pData[3] << 8)) * 0.1); @@ -460,7 +452,7 @@ bool SBS1_connect::processActions(std::vector& actions) { bool result = false; if (actions.size() > 0) { for (auto& it : actions) { - if (NimBLEAddress(it.addr) == m_pClient->getPeerAddress()) { + if (it.addr == m_pClient->getPeerAddress()) { NimBLERemoteCharacteristic* pChar = getCharacteristic(serviceUUID, charUUID); NimBLERemoteCharacteristic* pNotifyChar = getCharacteristic(serviceUUID, notifyCharUUID); @@ -497,8 +489,8 @@ bool SBS1_connect::processActions(std::vector& actions) { if (result || it.ttl <= 1) { StaticJsonDocument BLEdataBuffer; JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; - BLEdata["state"] = it.value; + BLEdata["id"] = m_pClient->getPeerAddress().toString().c_str(); + BLEdata["state"] = std::string(it.value); buildTopicFromId(BLEdata, subjectBTtoMQTT); enqueueJsonObject(BLEdata, QueueSemaphoreTimeOutTask); } @@ -592,7 +584,7 @@ bool SBBT_connect::processActions(std::vector& actions) { if (result || it.ttl <= 1) { StaticJsonDocument BLEdataBuffer; JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; + BLEdata["id"] = it.addr.toString().c_str(); if (value != -99 || value != -1) BLEdata["tilt"] = value; if (value == 50) { @@ -694,7 +686,7 @@ bool SBCU_connect::processActions(std::vector& actions) { if (result || it.ttl <= 1) { StaticJsonDocument BLEdataBuffer; JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = it.addr; + BLEdata["id"] = it.addr.toString().c_str(); if (value != -99 || value != -1) BLEdata["position"] = value; buildTopicFromId(BLEdata, subjectBTtoMQTT); diff --git a/main/ZgatewayBT.ino b/main/ZgatewayBT.ino index cb6e600..2ee882b 100644 --- a/main/ZgatewayBT.ino +++ b/main/ZgatewayBT.ino @@ -1,7 +1,7 @@ /* OpenMQTTGateway - ESP8266 or Arduino program for home automation - Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT This gateway enables to: @@ -579,15 +579,15 @@ void XMWSDJ04MMCDiscovery(const char* mac, const char* sensorModel_id) {} //core on which the BLE detection task will run static int taskCore = 0; -class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks { - void onResult(BLEAdvertisedDevice* advertisedDevice) { - BLEAdvertisedDevice* ad = new BLEAdvertisedDevice(*advertisedDevice); +class ScanCallbacks : public NimBLEScanCallbacks { + void onResult(const NimBLEAdvertisedDevice* advertisedDevice) { + NimBLEAdvertisedDevice* ad = new NimBLEAdvertisedDevice(*advertisedDevice); if (xQueueSend(BLEQueue, &ad, 0) != pdTRUE) { Log.error(F("BLEQueue full" CR)); delete (ad); } } -}; +} scanCallbacks; std::string convertServiceData(std::string deviceServiceData) { int serviceDataLength = (int)deviceServiceData.length(); @@ -624,13 +624,7 @@ void procBLETask(void* pvParameters) { Log.trace(F("Creating BLE buffer" CR)); StaticJsonDocument BLEdataBuffer; JsonObject BLEdata = BLEdataBuffer.to(); - std::string mac_address = advertisedDevice->getAddress().toString(); - - for (char& c : mac_address) { - c = std::toupper(c); - } - - BLEdata["id"] = mac_address; + BLEdata["id"] = advertisedDevice->getAddress().toString(); BLEdata["mac_type"] = advertisedDevice->getAddress().getType(); BLEdata["adv_type"] = advertisedDevice->getAdvType(); Log.notice(F("BT Device detected: %s" CR), BLEdata["id"].as()); @@ -646,16 +640,14 @@ void procBLETask(void* pvParameters) { if (advertisedDevice->haveName()) BLEdata["name"] = (char*)advertisedDevice->getName().c_str(); if (advertisedDevice->haveManufacturerData()) { - char* manufacturerdata = BLEUtils::buildHexData(NULL, (uint8_t*)advertisedDevice->getManufacturerData().data(), advertisedDevice->getManufacturerData().length()); - BLEdata["manufacturerdata"] = manufacturerdata; - free(manufacturerdata); + BLEdata["manufacturerdata"] = NimBLEUtils::dataToHexString((uint8_t*)advertisedDevice->getManufacturerData().data(), + advertisedDevice->getManufacturerData().length()); } - if (advertisedDevice->haveRSSI()) - BLEdata["rssi"] = (int)advertisedDevice->getRSSI(); + BLEdata["rssi"] = (int)advertisedDevice->getRSSI(); if (advertisedDevice->haveTXPower()) BLEdata["txpower"] = (int8_t)advertisedDevice->getTXPower(); - if (advertisedDevice->haveRSSI() && BTConfig.presenceEnable) { - hass_presence(BLEdata); // this device has an rssi and with either only sensors or not we can use it for home assistant room presence component + if (BTConfig.presenceEnable) { + hass_presence(BLEdata); // with either only sensors or not we can use it for home assistant room presence component } if (advertisedDevice->haveServiceData()) { int serviceDataCount = advertisedDevice->getServiceDataCount(); @@ -695,8 +687,7 @@ void BLEscan() { } Log.notice(F("Scan begin" CR)); BLEScan* pBLEScan = BLEDevice::getScan(); - MyAdvertisedDeviceCallbacks myCallbacks; - pBLEScan->setAdvertisedDeviceCallbacks(&myCallbacks); + pBLEScan->setScanCallbacks(&scanCallbacks); if ((millis() > (timeBetweenActive + BTConfig.intervalActiveScan) || BTConfig.intervalActiveScan == BTConfig.BLEinterval) && !BTConfig.forcePassiveScan) { pBLEScan->setActiveScan(true); timeBetweenActive = millis(); @@ -705,7 +696,7 @@ void BLEscan() { } pBLEScan->setInterval(BLEScanInterval); pBLEScan->setWindow(BLEScanWindow); - BLEScanResults foundDevices = pBLEScan->start(BTConfig.scanDuration / 1000, false); + NimBLEScanResults foundDevices = pBLEScan->getResults(BTConfig.scanDuration, false); if (foundDevices.getCount()) scanCount++; Log.notice(F("Found %d devices, scan number %d end" CR), foundDevices.getCount(), scanCount); @@ -768,7 +759,7 @@ void BLEconnect() { for (auto& it : BLEactions) { if (!it.complete && --it.ttl) { swap.push_back(it); - } else if (memcmp(it.addr, p->macAdr, sizeof(it.addr)) == 0) { + } else if (it.addr == NimBLEAddress(p->macAdr, p->macType)) { if (p->sensorModel_id != BLEconectable::id::DT24_BLE && p->sensorModel_id != TheengsDecoder::BLE_ID_NUM::HHCCJCY01HHCC && p->sensorModel_id != BLEconectable::id::LYWSD03MMC && @@ -851,7 +842,9 @@ void coreTask(void* pvParameters) { } void setupBTTasksAndBLE() { +# ifdef CONFIG_BTDM_BLE_SCAN_DUPL BLEDevice::setScanDuplicateCacheSize(BLEScanDuplicateCacheSize); +# endif BLEDevice::init(""); xTaskCreatePinnedToCore( procBLETask, /* Function to implement the task */ @@ -1363,7 +1356,7 @@ void immediateBTAction(void* pvParameters) { if (xSemaphoreTake(semaphoreCreateOrUpdateDevice, pdMS_TO_TICKS(QueueSemaphoreTimeOutTask)) == pdTRUE) { // swap the vectors so only this device is processed std::vector dev_swap; - dev_swap.push_back(getDeviceByMac(BLEactions.back().addr)); + dev_swap.push_back(getDeviceByMac(BLEactions.back().addr.toString().c_str())); std::swap(devices, dev_swap); std::vector act_swap; @@ -1393,7 +1386,7 @@ void immediateBTAction(void* pvParameters) { gatewayState = GatewayState::ERROR; StaticJsonDocument BLEdataBuffer; JsonObject BLEdata = BLEdataBuffer.to(); - BLEdata["id"] = BLEactions.back().addr; + BLEdata["id"] = BLEactions.back().addr.toString().c_str(); BLEdata["success"] = false; buildTopicFromId(BLEdata, subjectBTtoMQTT); enqueueJsonObject(BLEdata, QueueSemaphoreTimeOutTask); @@ -1423,9 +1416,8 @@ void KnownBTActions(JsonObject& BTdata) { gatewayState = GatewayState::ERROR; return; } - BLEAction action; - memset(&action, 0, sizeof(BLEAction)); - strcpy(action.addr, (const char*)BTdata["id"]); + + BLEAction action{}; action.write = true; action.ttl = 3; bool res = false; @@ -1435,7 +1427,7 @@ void KnownBTActions(JsonObject& BTdata) { action.value_type = BLE_VAL_STRING; std::string val = BTdata["cmd"].as(); // Fix #1694 action.value = val; - createOrUpdateDevice(action.addr, device_flags_connect, + createOrUpdateDevice(BTdata["id"].as(), device_flags_connect, TheengsDecoder::BLE_ID_NUM::SBS1, 1); res = true; } @@ -1450,7 +1442,7 @@ void KnownBTActions(JsonObject& BTdata) { if (res) { std::string val = BTdata["tilt"].as(); // Fix #1694 action.value = val; - createOrUpdateDevice(action.addr, device_flags_connect, + createOrUpdateDevice(BTdata["id"].as(), device_flags_connect, TheengsDecoder::BLE_ID_NUM::SBBT, 1); } } else if (BTdata["model_id"] == "W070160X") { @@ -1464,11 +1456,12 @@ void KnownBTActions(JsonObject& BTdata) { if (res) { std::string val = BTdata["position"].as(); // Fix #1694 action.value = val; - createOrUpdateDevice(action.addr, device_flags_connect, + createOrUpdateDevice(BTdata["id"].as(), device_flags_connect, TheengsDecoder::BLE_ID_NUM::SBCU, 1); } } if (res) { + action.addr = NimBLEAddress(BTdata["id"].as(), 1); BLEactions.push_back(action); startBTActionTask(); } else { @@ -1482,10 +1475,8 @@ void KnownBTActions(JsonObject& BTdata) {} # endif void XtoBTAction(JsonObject& BTdata) { - BLEAction action; - memset(&action, 0, sizeof(BLEAction)); + BLEAction action{}; action.ttl = BTdata.containsKey("ttl") ? (uint8_t)BTdata["ttl"] : 1; - action.addr_type = BTdata.containsKey("mac_type") ? BTdata["mac_type"].as() : 0; action.value_type = BLE_VAL_STRING; if (BTdata.containsKey("value_type")) { String vt = BTdata["value_type"]; @@ -1508,7 +1499,7 @@ void XtoBTAction(JsonObject& BTdata) { BTdata.containsKey("ble_write_service") && BTdata.containsKey("ble_write_char") && BTdata.containsKey("ble_write_value")) { - strcpy(action.addr, (const char*)BTdata["ble_write_address"]); + action.addr = NimBLEAddress(BTdata["ble_write_address"].as(), BTdata.containsKey("mac_type") ? BTdata["mac_type"].as() : 0); action.service = NimBLEUUID((const char*)BTdata["ble_write_service"]); action.characteristic = NimBLEUUID((const char*)BTdata["ble_write_char"]); std::string val = BTdata["ble_write_value"].as(); // Fix #1694 @@ -1518,7 +1509,7 @@ void XtoBTAction(JsonObject& BTdata) { } else if (BTdata.containsKey("ble_read_address") && BTdata.containsKey("ble_read_service") && BTdata.containsKey("ble_read_char")) { - strcpy(action.addr, (const char*)BTdata["ble_read_address"]); + action.addr = NimBLEAddress(BTdata["ble_read_address"].as(), BTdata.containsKey("mac_type") ? BTdata["mac_type"].as() : 0); action.service = NimBLEUUID((const char*)BTdata["ble_read_service"]); action.characteristic = NimBLEUUID((const char*)BTdata["ble_read_char"]); action.write = false; @@ -1527,9 +1518,7 @@ void XtoBTAction(JsonObject& BTdata) { return; } - createOrUpdateDevice(action.addr, device_flags_connect, - UNKWNON_MODEL, - action.addr_type); + createOrUpdateDevice(action.addr.toString().c_str(), device_flags_connect, UNKWNON_MODEL, action.addr.getType()); BLEactions.push_back(action); if (BTdata.containsKey("immediate") && BTdata["immediate"].as()) { diff --git a/main/config_BT.h b/main/config_BT.h index 9d90ecd..b3126ac 100644 --- a/main/config_BT.h +++ b/main/config_BT.h @@ -1,15 +1,15 @@ -/* +/* Theengs OpenMQTTGateway - We Unite Sensors in One Open-Source Interface - Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker + Act as a gateway between your 433mhz, infrared IR, BLE, LoRa signal and one interface like an MQTT broker Send and receiving command by MQTT - + This files enables to set your parameter for the bluetooth low energy gateway (beacons detection) - + Copyright: (c)Florian ROBERT - + This file is part of OpenMQTTGateway. - + OpenMQTTGateway is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or @@ -34,6 +34,7 @@ extern String stateBTMeasures(bool); #ifdef ESP32 # include "NimBLEDevice.h" + #endif /*-----------BT TOPICS & COMPILATION PARAMETERS-----------*/ @@ -208,9 +209,8 @@ enum ble_val_type { }; struct BLEAction { - std::string value; - char addr[18]; - int addr_type; + NimBLEAttValue value; + NimBLEAddress addr; NimBLEUUID service; NimBLEUUID characteristic; bool write; diff --git a/platformio.ini b/platformio.ini index 0b8beaf..ea82bff 100644 --- a/platformio.ini +++ b/platformio.ini @@ -119,7 +119,7 @@ arduinolog = https://github.com/1technophile/Arduino-Log.git#f634509 picomqtt = PicoMQTT@1.1.1 rc-switch = https://github.com/1technophile/rc-switch.git#98537e9 newremoteswitch = https://github.com/1technophile/NewRemoteSwitch.git#8eb980e -ble = https://github.com/h2zero/NimBLE-Arduino.git#1.4.1 +ble = https://github.com/h2zero/NimBLE-Arduino.git#2.2.1 irremoteesp = IRremoteESP8266@2.8.5 lora = https://github.com/sandeepmistry/arduino-LoRa.git#f4a1d27 esppilight = ESPiLight@0.17.0 @@ -202,6 +202,7 @@ build_flags = '-DZmqttDiscovery="HADiscovery"' '-DCONFIG_BT_NIMBLE_ROLE_PERIPHERAL_DISABLED' '-DCONFIG_BT_NIMBLE_ROLE_BROADCASTER_DISABLED' + '-DCONFIG_NIMBLE_CPP_ADDR_FMT_UPPERCASE' '-DMQTTsetMQTT' '-DMQTT_HTTPS_FW_UPDATE' ;'-DCORE_DEBUG_LEVEL=4' diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 93a38af..f52be83 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -135,7 +135,7 @@ CONFIG_AUTOSTART_ARDUINO=y CONFIG_ARDUINO_RUN_CORE1=y # CONFIG_ARDUINO_RUN_NO_AFFINITY is not set CONFIG_ARDUINO_RUNNING_CORE=1 -CONFIG_ARDUINO_LOOP_STACK_SIZE=8192 +CONFIG_ARDUINO_LOOP_STACK_SIZE=17500 # CONFIG_ARDUINO_EVENT_RUN_CORE0 is not set CONFIG_ARDUINO_EVENT_RUN_CORE1=y # CONFIG_ARDUINO_EVENT_RUN_NO_AFFINITY is not set @@ -209,11 +209,3 @@ CONFIG_ARDUINO_SELECTIVE_Wire=y # CONFIG_ESP32_WIFI_IRAM_OPT is not set # CONFIG_ESP32_WIFI_RX_IRAM_OPT is not set -# -# SPI configuration -# -# CONFIG_SPI_MASTER_IN_IRAM is not set -# CONFIG_SPI_MASTER_ISR_IN_IRAM is not set -# CONFIG_SPI_SLAVE_IN_IRAM is not set -# CONFIG_SPI_SLAVE_ISR_IN_IRAM is not set -# end of SPI configuration \ No newline at end of file