From 3fa2c2eaaf8292145a7d3feaf1213263ec0fca78 Mon Sep 17 00:00:00 2001 From: Victor Aprea Date: Mon, 1 Jun 2020 12:45:36 -0400 Subject: [PATCH] here's the changes from esp32-snippets --- libraries/BLE/src/BLEAddress.cpp | 15 +- libraries/BLE/src/BLEAdvertisedDevice.cpp | 100 +++----- libraries/BLE/src/BLEAdvertisedDevice.h | 13 +- libraries/BLE/src/BLEAdvertising.cpp | 94 +++---- libraries/BLE/src/BLEAdvertising.h | 4 +- libraries/BLE/src/BLEBeacon.cpp | 8 +- libraries/BLE/src/BLECharacteristic.cpp | 238 ++++++++---------- libraries/BLE/src/BLECharacteristic.h | 17 +- libraries/BLE/src/BLECharacteristicMap.cpp | 15 +- libraries/BLE/src/BLEClient.cpp | 183 ++++++++------ libraries/BLE/src/BLEClient.h | 13 +- libraries/BLE/src/BLEDescriptor.cpp | 43 ++-- libraries/BLE/src/BLEDescriptorMap.cpp | 15 +- libraries/BLE/src/BLEDevice.cpp | 166 ++++++------ libraries/BLE/src/BLEDevice.h | 5 +- libraries/BLE/src/BLEEddystoneTLM.cpp | 100 +++++--- libraries/BLE/src/BLEEddystoneTLM.h | 0 libraries/BLE/src/BLEEddystoneURL.cpp | 6 +- libraries/BLE/src/BLEEddystoneURL.h | 0 libraries/BLE/src/BLEExceptions.cpp | 2 +- libraries/BLE/src/BLEHIDDevice.cpp | 1 + libraries/BLE/src/BLERemoteCharacteristic.cpp | 130 +++++----- libraries/BLE/src/BLERemoteCharacteristic.h | 15 +- libraries/BLE/src/BLERemoteDescriptor.cpp | 50 ++-- libraries/BLE/src/BLERemoteDescriptor.h | 2 - libraries/BLE/src/BLERemoteService.cpp | 119 +++------ libraries/BLE/src/BLEScan.cpp | 38 +-- libraries/BLE/src/BLESecurity.cpp | 11 + libraries/BLE/src/BLESecurity.h | 1 + libraries/BLE/src/BLEServer.cpp | 70 +++--- libraries/BLE/src/BLEServer.h | 2 +- libraries/BLE/src/BLEService.cpp | 65 ++--- libraries/BLE/src/BLEServiceMap.cpp | 13 +- libraries/BLE/src/BLEUUID.cpp | 79 +++--- libraries/BLE/src/BLEUtils.cpp | 219 +++++++--------- libraries/BLE/src/BLEValue.cpp | 17 +- libraries/BLE/src/FreeRTOS.cpp | 70 ++---- libraries/BLE/src/FreeRTOS.h | 2 - libraries/BLE/src/GeneralUtils.cpp | 57 +++-- 39 files changed, 934 insertions(+), 1064 deletions(-) mode change 100644 => 100755 libraries/BLE/src/BLEEddystoneTLM.cpp mode change 100644 => 100755 libraries/BLE/src/BLEEddystoneTLM.h mode change 100644 => 100755 libraries/BLE/src/BLEEddystoneURL.cpp mode change 100644 => 100755 libraries/BLE/src/BLEEddystoneURL.h mode change 100644 => 100755 libraries/BLE/src/BLEServer.cpp mode change 100644 => 100755 libraries/BLE/src/BLEServer.h mode change 100644 => 100755 libraries/BLE/src/BLEServiceMap.cpp diff --git a/libraries/BLE/src/BLEAddress.cpp b/libraries/BLE/src/BLEAddress.cpp index 6d83b17e68e..d6883340283 100644 --- a/libraries/BLE/src/BLEAddress.cpp +++ b/libraries/BLE/src/BLEAddress.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #ifdef ARDUINO_ARCH_ESP32 #include "esp32-hal-log.h" #endif @@ -84,11 +83,13 @@ esp_bd_addr_t *BLEAddress::getNative() { * @return The string representation of the address. */ std::string BLEAddress::toString() { - auto size = 18; - char *res = (char*)malloc(size); - snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[0], m_address[1], m_address[2], m_address[3], m_address[4], m_address[5]); - std::string ret(res); - free(res); - return ret; + std::stringstream stream; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[0] << ':'; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[1] << ':'; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[2] << ':'; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[3] << ':'; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[4] << ':'; + stream << std::setfill('0') << std::setw(2) << std::hex << (int) ((uint8_t*) (m_address))[5]; + return stream.str(); } // toString #endif diff --git a/libraries/BLE/src/BLEAdvertisedDevice.cpp b/libraries/BLE/src/BLEAdvertisedDevice.cpp index f27ba6f6c7c..d3e60bddeae 100644 --- a/libraries/BLE/src/BLEAdvertisedDevice.cpp +++ b/libraries/BLE/src/BLEAdvertisedDevice.cpp @@ -16,7 +16,13 @@ #include #include "BLEAdvertisedDevice.h" #include "BLEUtils.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG="BLEAdvertisedDevice"; +#endif BLEAdvertisedDevice::BLEAdvertisedDevice() { m_adFlag = 0; @@ -25,8 +31,7 @@ BLEAdvertisedDevice::BLEAdvertisedDevice() { m_manufacturerData = ""; m_name = ""; m_rssi = -9999; - m_serviceData = {}; - m_serviceDataUUIDs = {}; + m_serviceData = ""; m_txPower = 0; m_pScan = nullptr; @@ -102,66 +107,33 @@ BLEScan* BLEAdvertisedDevice::getScan() { return m_pScan; } // getScan -/** - * @brief Get the number of service data. - * @return Number of service data discovered. - */ -int BLEAdvertisedDevice::getServiceDataCount() { - if (m_haveServiceData) - return m_serviceData.size(); - else - return 0; - -} //getServiceDataCount /** * @brief Get the service data. * @return The ServiceData of the advertised device. */ std::string BLEAdvertisedDevice::getServiceData() { - return m_serviceData[0]; + return m_serviceData; } //getServiceData -/** - * @brief Get the service data. - * @return The ServiceData of the advertised device. - */ -std::string BLEAdvertisedDevice::getServiceData(int i) { - return m_serviceData[i]; -} //getServiceData /** * @brief Get the service data UUID. * @return The service data UUID. */ BLEUUID BLEAdvertisedDevice::getServiceDataUUID() { - return m_serviceDataUUIDs[0]; + return m_serviceDataUUID; } // getServiceDataUUID -/** - * @brief Get the service data UUID. - * @return The service data UUID. - */ -BLEUUID BLEAdvertisedDevice::getServiceDataUUID(int i) { - return m_serviceDataUUIDs[i]; -} // getServiceDataUUID /** * @brief Get the Service UUID. * @return The Service UUID of the advertised device. */ -BLEUUID BLEAdvertisedDevice::getServiceUUID() { +BLEUUID BLEAdvertisedDevice::getServiceUUID() { //TODO Remove it eventually, is no longer useful return m_serviceUUIDs[0]; } // getServiceUUID -/** - * @brief Get the Service UUID. - * @return The Service UUID of the advertised device. - */ -BLEUUID BLEAdvertisedDevice::getServiceUUID(int i) { - return m_serviceUUIDs[i]; -} // getServiceUUID - /** * @brief Check advertised serviced for existence required UUID * @return Return true if service is advertised @@ -277,7 +249,7 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) length--; char* pHex = BLEUtils::buildHexData(nullptr, payload, length); - log_d("Type: 0x%.2x (%s), length: %d, data: %s", + ESP_LOGD(LOG_TAG, "Type: 0x%.2x (%s), length: %d, data: %s", ad_type, BLEUtils::advTypeToString(ad_type), length, pHex); free(pHex); @@ -336,7 +308,7 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) case ESP_BLE_AD_TYPE_SERVICE_DATA: { // Adv Data Type: 0x16 (Service Data) - 2 byte UUID if (length < 2) { - log_e("Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA"); + ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA"); break; } uint16_t uuid = *(uint16_t*)payload; @@ -349,7 +321,7 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) case ESP_BLE_AD_TYPE_32SERVICE_DATA: { // Adv Data Type: 0x20 (Service Data) - 4 byte UUID if (length < 4) { - log_e("Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA"); + ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA"); break; } uint32_t uuid = *(uint32_t*) payload; @@ -362,7 +334,7 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) case ESP_BLE_AD_TYPE_128SERVICE_DATA: { // Adv Data Type: 0x21 (Service Data) - 16 byte UUID if (length < 16) { - log_e("Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA"); + ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA"); break; } @@ -374,7 +346,7 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) } //ESP_BLE_AD_TYPE_32SERVICE_DATA default: { - log_d("Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type); + ESP_LOGD(LOG_TAG, "Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type); break; } } // switch @@ -414,7 +386,7 @@ void BLEAdvertisedDevice::setAdFlag(uint8_t adFlag) { void BLEAdvertisedDevice::setAppearance(uint16_t appearance) { m_appearance = appearance; m_haveAppearance = true; - log_d("- appearance: %d", m_appearance); + ESP_LOGD(LOG_TAG, "- appearance: %d", m_appearance); } // setAppearance @@ -426,7 +398,7 @@ void BLEAdvertisedDevice::setManufacturerData(std::string manufacturerData) { m_manufacturerData = manufacturerData; m_haveManufacturerData = true; char* pHex = BLEUtils::buildHexData(nullptr, (uint8_t*) m_manufacturerData.data(), (uint8_t) m_manufacturerData.length()); - log_d("- manufacturer data: %s", pHex); + ESP_LOGD(LOG_TAG, "- manufacturer data: %s", pHex); free(pHex); } // setManufacturerData @@ -438,7 +410,7 @@ void BLEAdvertisedDevice::setManufacturerData(std::string manufacturerData) { void BLEAdvertisedDevice::setName(std::string name) { m_name = name; m_haveName = true; - log_d("- setName(): name: %s", m_name.c_str()); + ESP_LOGD(LOG_TAG, "- setName(): name: %s", m_name.c_str()); } // setName @@ -449,7 +421,7 @@ void BLEAdvertisedDevice::setName(std::string name) { void BLEAdvertisedDevice::setRSSI(int rssi) { m_rssi = rssi; m_haveRSSI = true; - log_d("- setRSSI(): rssi: %d", m_rssi); + ESP_LOGD(LOG_TAG, "- setRSSI(): rssi: %d", m_rssi); } // setRSSI @@ -478,7 +450,7 @@ void BLEAdvertisedDevice::setServiceUUID(const char* serviceUUID) { void BLEAdvertisedDevice::setServiceUUID(BLEUUID serviceUUID) { m_serviceUUIDs.push_back(serviceUUID); m_haveServiceUUID = true; - log_d("- addServiceUUID(): serviceUUID: %s", serviceUUID.toString().c_str()); + ESP_LOGD(LOG_TAG, "- addServiceUUID(): serviceUUID: %s", serviceUUID.toString().c_str()); } // setServiceUUID @@ -488,7 +460,7 @@ void BLEAdvertisedDevice::setServiceUUID(BLEUUID serviceUUID) { */ void BLEAdvertisedDevice::setServiceData(std::string serviceData) { m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceData.push_back(serviceData); // Save the service data that we received. + m_serviceData = serviceData; // Save the service data that we received. } //setServiceData @@ -498,8 +470,7 @@ void BLEAdvertisedDevice::setServiceData(std::string serviceData) { */ void BLEAdvertisedDevice::setServiceDataUUID(BLEUUID uuid) { m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceDataUUIDs.push_back(uuid); - log_d("- addServiceDataUUID(): serviceDataUUID: %s", uuid.toString().c_str()); + m_serviceDataUUID = uuid; } // setServiceDataUUID @@ -510,7 +481,7 @@ void BLEAdvertisedDevice::setServiceDataUUID(BLEUUID uuid) { void BLEAdvertisedDevice::setTXPower(int8_t txPower) { m_txPower = txPower; m_haveTXPower = true; - log_d("- txPower: %d", m_txPower); + ESP_LOGD(LOG_TAG, "- txPower: %d", m_txPower); } // setTXPower @@ -519,31 +490,23 @@ void BLEAdvertisedDevice::setTXPower(int8_t txPower) { * @return A string representation of this device. */ std::string BLEAdvertisedDevice::toString() { - std::string res = "Name: " + getName() + ", Address: " + getAddress().toString(); + std::stringstream ss; + ss << "Name: " << getName() << ", Address: " << getAddress().toString(); if (haveAppearance()) { - char val[6]; - snprintf(val, sizeof(val), "%d", getAppearance()); - res += ", appearance: "; - res += val; + ss << ", appearance: " << getAppearance(); } if (haveManufacturerData()) { char *pHex = BLEUtils::buildHexData(nullptr, (uint8_t*)getManufacturerData().data(), getManufacturerData().length()); - res += ", manufacturer data: "; - res += pHex; + ss << ", manufacturer data: " << pHex; free(pHex); } if (haveServiceUUID()) { - for (int i=0; i < m_serviceUUIDs.size(); i++) { - res += ", serviceUUID: " + getServiceUUID(i).toString(); - } + ss << ", serviceUUID: " << getServiceUUID().toString(); } if (haveTXPower()) { - char val[4]; - snprintf(val, sizeof(val), "%d", getTXPower()); - res += ", txPower: "; - res += val; + ss << ", txPower: " << (int)getTXPower(); } - return res; + return ss.str(); } // toString uint8_t* BLEAdvertisedDevice::getPayload() { @@ -562,5 +525,8 @@ size_t BLEAdvertisedDevice::getPayloadLength() { return m_payloadLength; } +void BLEAdvertisedDeviceCallbacks::onResult(BLEAdvertisedDevice dev) {} +void BLEAdvertisedDeviceCallbacks::onResult(BLEAdvertisedDevice* dev) {} + #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEAdvertisedDevice.h b/libraries/BLE/src/BLEAdvertisedDevice.h index a3181c10b08..cd206d4aa8a 100644 --- a/libraries/BLE/src/BLEAdvertisedDevice.h +++ b/libraries/BLE/src/BLEAdvertisedDevice.h @@ -36,12 +36,8 @@ class BLEAdvertisedDevice { int getRSSI(); BLEScan* getScan(); std::string getServiceData(); - std::string getServiceData(int i); BLEUUID getServiceDataUUID(); - BLEUUID getServiceDataUUID(int i); BLEUUID getServiceUUID(); - BLEUUID getServiceUUID(int i); - int getServiceDataCount(); int8_t getTXPower(); uint8_t* getPayload(); size_t getPayloadLength(); @@ -97,9 +93,9 @@ class BLEAdvertisedDevice { int m_rssi; std::vector m_serviceUUIDs; int8_t m_txPower; - std::vector m_serviceData; - std::vector m_serviceDataUUIDs; - uint8_t* m_payload; + std::string m_serviceData; + BLEUUID m_serviceDataUUID; + uint8_t* m_payload = nullptr; size_t m_payloadLength = 0; esp_ble_addr_type_t m_addressType; }; @@ -120,7 +116,8 @@ class BLEAdvertisedDeviceCallbacks { * As we are scanning, we will find new devices. When found, this call back is invoked with a reference to the * device that was found. During any individual scan, a device will only be detected one time. */ - virtual void onResult(BLEAdvertisedDevice advertisedDevice) = 0; + virtual void onResult(BLEAdvertisedDevice advertisedDevice); + virtual void onResult(BLEAdvertisedDevice* advertisedDevice); }; #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEAdvertising.cpp b/libraries/BLE/src/BLEAdvertising.cpp index 3d86a5072a6..230d77cb7cd 100644 --- a/libraries/BLE/src/BLEAdvertising.cpp +++ b/libraries/BLE/src/BLEAdvertising.cpp @@ -22,7 +22,16 @@ #include #include "BLEUtils.h" #include "GeneralUtils.h" + +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEAdvertising"; +#endif + + /** * @brief Construct a default advertising object. @@ -85,10 +94,6 @@ void BLEAdvertising::setAppearance(uint16_t appearance) { m_advData.appearance = appearance; } // setAppearance -void BLEAdvertising::setAdvertisementType(esp_ble_adv_type_t adv_type){ - m_advParams.adv_type = adv_type; -} // setAdvertisementType - void BLEAdvertising::setMinInterval(uint16_t mininterval) { m_advParams.adv_int_min = mininterval; } // setMinInterval @@ -115,25 +120,25 @@ void BLEAdvertising::setScanResponse(bool set) { * @param [in] connectWhitelistOnly If true, only allow connections from those on the white list. */ void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) { - log_v(">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly); + ESP_LOGD(LOG_TAG, ">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly); if (!scanRequestWhitelistOnly && !connectWhitelistOnly) { m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - log_v("<< setScanFilter"); + ESP_LOGD(LOG_TAG, "<< setScanFilter"); return; } if (scanRequestWhitelistOnly && !connectWhitelistOnly) { m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY; - log_v("<< setScanFilter"); + ESP_LOGD(LOG_TAG, "<< setScanFilter"); return; } if (!scanRequestWhitelistOnly && connectWhitelistOnly) { m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST; - log_v("<< setScanFilter"); + ESP_LOGD(LOG_TAG, "<< setScanFilter"); return; } if (scanRequestWhitelistOnly && connectWhitelistOnly) { m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST; - log_v("<< setScanFilter"); + ESP_LOGD(LOG_TAG, "<< setScanFilter"); return; } } // setScanFilter @@ -144,15 +149,15 @@ void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWh * @param [in] advertisementData The data to be advertised. */ void BLEAdvertising::setAdvertisementData(BLEAdvertisementData& advertisementData) { - log_v(">> setAdvertisementData"); + ESP_LOGD(LOG_TAG, ">> setAdvertisementData"); esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw( (uint8_t*)advertisementData.getPayload().data(), advertisementData.getPayload().length()); if (errRc != ESP_OK) { - log_e("esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); } m_customAdvData = true; // Set the flag that indicates we are using custom advertising data. - log_v("<< setAdvertisementData"); + ESP_LOGD(LOG_TAG, "<< setAdvertisementData"); } // setAdvertisementData @@ -161,15 +166,15 @@ void BLEAdvertising::setAdvertisementData(BLEAdvertisementData& advertisementDat * @param [in] advertisementData The data to be advertised. */ void BLEAdvertising::setScanResponseData(BLEAdvertisementData& advertisementData) { - log_v(">> setScanResponseData"); + ESP_LOGD(LOG_TAG, ">> setScanResponseData"); esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw( (uint8_t*)advertisementData.getPayload().data(), advertisementData.getPayload().length()); if (errRc != ESP_OK) { - log_e("esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); } m_customScanResponseData = true; // Set the flag that indicates we are using custom scan response data. - log_v("<< setScanResponseData"); + ESP_LOGD(LOG_TAG, "<< setScanResponseData"); } // setScanResponseData /** @@ -178,7 +183,7 @@ void BLEAdvertising::setScanResponseData(BLEAdvertisementData& advertisementData * @return N/A. */ void BLEAdvertising::start() { - log_v(">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData); + ESP_LOGD(LOG_TAG, ">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData); // We have a vector of service UUIDs that we wish to advertise. In order to use the // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte) @@ -190,14 +195,14 @@ void BLEAdvertising::start() { m_advData.p_service_uuid = new uint8_t[m_advData.service_uuid_len]; uint8_t* p = m_advData.p_service_uuid; for (int i = 0; i < numServices; i++) { - log_d("- advertising service: %s", m_serviceUUIDs[i].toString().c_str()); + ESP_LOGD(LOG_TAG, "- advertising service: %s", m_serviceUUIDs[i].toString().c_str()); BLEUUID serviceUUID128 = m_serviceUUIDs[i].to128(); memcpy(p, serviceUUID128.getNative()->uuid.uuid128, 16); p += 16; } } else { m_advData.service_uuid_len = 0; - log_d("- no services advertised"); + ESP_LOGD(LOG_TAG, "- no services advertised"); } esp_err_t errRc; @@ -209,7 +214,7 @@ void BLEAdvertising::start() { m_advData.include_txpower = !m_scanResp; errRc = ::esp_ble_gap_config_adv_data(&m_advData); if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } } @@ -220,7 +225,7 @@ void BLEAdvertising::start() { m_advData.include_txpower = m_scanResp; errRc = ::esp_ble_gap_config_adv_data(&m_advData); if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } } @@ -235,10 +240,10 @@ void BLEAdvertising::start() { // Start advertising. errRc = ::esp_ble_gap_start_advertising(&m_advParams); if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } - log_v("<< start"); + ESP_LOGD(LOG_TAG, "<< start"); } // start @@ -248,36 +253,15 @@ void BLEAdvertising::start() { * @return N/A. */ void BLEAdvertising::stop() { - log_v(">> stop"); + ESP_LOGD(LOG_TAG, ">> stop"); esp_err_t errRc = ::esp_ble_gap_stop_advertising(); if (errRc != ESP_OK) { - log_e("esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } - log_v("<< stop"); + ESP_LOGD(LOG_TAG, "<< stop"); } // stop -/** - * @brief Set BLE address. - * @param [in] Bluetooth address. - * @param [in] Bluetooth address type. - * Set BLE address. - */ - -void BLEAdvertising::setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type) -{ - log_v(">> setPrivateAddress"); - - m_advParams.own_addr_type = type; - esp_err_t errRc = esp_ble_gap_set_rand_addr((uint8_t*)addr); - if (errRc != ESP_OK) - { - log_e("esp_ble_gap_set_rand_addr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - log_v("<< setPrivateAddress"); -} // setPrivateAddress - /** * @brief Add data to the payload to be advertised. * @param [in] data The data to be added to the payload. @@ -368,12 +352,12 @@ void BLEAdvertisementData::setFlags(uint8_t flag) { * @param [in] data Manufacturer data. */ void BLEAdvertisementData::setManufacturerData(std::string data) { - log_d("BLEAdvertisementData", ">> setManufacturerData"); + ESP_LOGD("BLEAdvertisementData", ">> setManufacturerData"); char cdata[2]; cdata[0] = data.length() + 1; cdata[1] = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE; // 0xff addData(std::string(cdata, 2) + data); - log_d("BLEAdvertisementData", "<< setManufacturerData"); + ESP_LOGD("BLEAdvertisementData", "<< setManufacturerData"); } // setManufacturerData @@ -382,12 +366,12 @@ void BLEAdvertisementData::setManufacturerData(std::string data) { * @param [in] The complete name of the device. */ void BLEAdvertisementData::setName(std::string name) { - log_d("BLEAdvertisementData", ">> setName: %s", name.c_str()); + ESP_LOGD("BLEAdvertisementData", ">> setName: %s", name.c_str()); char cdata[2]; cdata[0] = name.length() + 1; cdata[1] = ESP_BLE_AD_TYPE_NAME_CMPL; // 0x09 addData(std::string(cdata, 2) + name); - log_d("BLEAdvertisementData", "<< setName"); + ESP_LOGD("BLEAdvertisementData", "<< setName"); } // setName @@ -471,12 +455,12 @@ void BLEAdvertisementData::setServiceData(BLEUUID uuid, std::string data) { * @param [in] The short name of the device. */ void BLEAdvertisementData::setShortName(std::string name) { - log_d("BLEAdvertisementData", ">> setShortName: %s", name.c_str()); + ESP_LOGD("BLEAdvertisementData", ">> setShortName: %s", name.c_str()); char cdata[2]; cdata[0] = name.length() + 1; cdata[1] = ESP_BLE_AD_TYPE_NAME_SHORT; // 0x08 addData(std::string(cdata, 2) + name); - log_d("BLEAdvertisementData", "<< setShortName"); + ESP_LOGD("BLEAdvertisementData", "<< setShortName"); } // setShortName @@ -492,7 +476,7 @@ void BLEAdvertising::handleGAPEvent( esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param) { - log_d("handleGAPEvent [event no: %d]", (int)event); + ESP_LOGD(LOG_TAG, "handleGAPEvent [event no: %d]", (int)event); switch(event) { case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { @@ -508,8 +492,8 @@ void BLEAdvertising::handleGAPEvent( break; } case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { - log_i("STOP advertising"); - //start(); + ESP_LOGI(LOG_TAG, "STOP advertising"); + start(); break; } default: diff --git a/libraries/BLE/src/BLEAdvertising.h b/libraries/BLE/src/BLEAdvertising.h index 94bed945094..3128b50f1e3 100644 --- a/libraries/BLE/src/BLEAdvertising.h +++ b/libraries/BLE/src/BLEAdvertising.h @@ -52,14 +52,12 @@ class BLEAdvertising { void start(); void stop(); void setAppearance(uint16_t appearance); - void setAdvertisementType(esp_ble_adv_type_t adv_type); void setMaxInterval(uint16_t maxinterval); void setMinInterval(uint16_t mininterval); void setAdvertisementData(BLEAdvertisementData& advertisementData); void setScanFilter(bool scanRequertWhitelistOnly, bool connectWhitelistOnly); void setScanResponseData(BLEAdvertisementData& advertisementData); void setPrivateAddress(esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); - void setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param); void setMinPreferred(uint16_t); @@ -77,4 +75,4 @@ class BLEAdvertising { }; #endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */ +#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */ \ No newline at end of file diff --git a/libraries/BLE/src/BLEBeacon.cpp b/libraries/BLE/src/BLEBeacon.cpp index 1056cd54b04..68f8d8ed98a 100644 --- a/libraries/BLE/src/BLEBeacon.cpp +++ b/libraries/BLE/src/BLEBeacon.cpp @@ -8,7 +8,13 @@ #if defined(CONFIG_BT_ENABLED) #include #include "BLEBeacon.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEBeacon"; +#endif #define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) @@ -52,7 +58,7 @@ int8_t BLEBeacon::getSignalPower() { */ void BLEBeacon::setData(std::string data) { if (data.length() != sizeof(m_beaconData)) { - log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData)); + ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData)); return; } memcpy(&m_beaconData, data.data(), sizeof(m_beaconData)); diff --git a/libraries/BLE/src/BLECharacteristic.cpp b/libraries/BLE/src/BLECharacteristic.cpp index 25146136184..2868ee26b4a 100644 --- a/libraries/BLE/src/BLECharacteristic.cpp +++ b/libraries/BLE/src/BLECharacteristic.cpp @@ -18,11 +18,16 @@ #include "BLEUtils.h" #include "BLE2902.h" #include "GeneralUtils.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLECharacteristic"; +#endif #define NULL_HANDLE (0xffff) -static BLECharacteristicCallbacks defaultCallback; //null-object-pattern /** * @brief Construct a characteristic @@ -41,7 +46,7 @@ BLECharacteristic::BLECharacteristic(BLEUUID uuid, uint32_t properties) { m_bleUUID = uuid; m_handle = NULL_HANDLE; m_properties = (esp_gatt_char_prop_t)0; - m_pCallbacks = &defaultCallback; + m_pCallbacks = nullptr; setBroadcastProperty((properties & PROPERTY_BROADCAST) != 0); setReadProperty((properties & PROPERTY_READ) != 0); @@ -65,9 +70,9 @@ BLECharacteristic::~BLECharacteristic() { * @return N/A. */ void BLECharacteristic::addDescriptor(BLEDescriptor* pDescriptor) { - log_v(">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str()); + ESP_LOGD(LOG_TAG, ">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str()); m_descriptorMap.setByUUID(pDescriptor->getUUID(), pDescriptor); - log_v("<< addDescriptor()"); + ESP_LOGD(LOG_TAG, "<< addDescriptor()"); } // addDescriptor @@ -76,16 +81,16 @@ void BLECharacteristic::addDescriptor(BLEDescriptor* pDescriptor) { * @param [in] pService The service with which to associate this characteristic. */ void BLECharacteristic::executeCreate(BLEService* pService) { - log_v(">> executeCreate()"); + ESP_LOGD(LOG_TAG, ">> executeCreate()"); if (m_handle != NULL_HANDLE) { - log_e("Characteristic already has a handle."); + ESP_LOGE(LOG_TAG, "Characteristic already has a handle."); return; } m_pService = pService; // Save the service to which this characteristic belongs. - log_d("Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", + ESP_LOGD(LOG_TAG, "Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", getUUID().toString().c_str(), m_pService->toString().c_str()); @@ -102,7 +107,7 @@ void BLECharacteristic::executeCreate(BLEService* pService) { &control); // Whether to auto respond or not. if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreCreateEvt.wait("executeCreate"); @@ -113,7 +118,7 @@ void BLECharacteristic::executeCreate(BLEService* pService) { pDescriptor = m_descriptorMap.getNext(); } // End while - log_v("<< executeCreate"); + ESP_LOGD(LOG_TAG, "<< executeCreate"); } // executeCreate @@ -195,7 +200,7 @@ void BLECharacteristic::handleGATTServerEvent( esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { - log_v(">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); + ESP_LOGD(LOG_TAG, ">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); switch(event) { // Events handled: @@ -219,19 +224,24 @@ void BLECharacteristic::handleGATTServerEvent( // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL // case ESP_GATTS_EXEC_WRITE_EVT: { - if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) { - m_value.commit(); - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } else { - m_value.cancel(); - } -// ??? - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, ESP_GATT_OK, nullptr); - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + if(m_writeEvt){ + m_writeEvt = false; + if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) { + m_value.commit(); + if (m_pCallbacks != nullptr) { + m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. + } + } else { + m_value.cancel(); + } + // ??? + esp_err_t errRc = ::esp_ble_gatts_send_response( + gatts_if, + param->write.conn_id, + param->write.trans_id, ESP_GATT_OK, nullptr); + if (errRc != ESP_OK) { + ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + } } break; } // ESP_GATTS_EXEC_WRITE_EVT @@ -277,15 +287,19 @@ void BLECharacteristic::handleGATTServerEvent( if (param->write.handle == m_handle) { if (param->write.is_prep) { m_value.addPart(param->write.value, param->write.len); + m_writeEvt = true; } else { setValue(param->write.value, param->write.len); + if (m_pCallbacks != nullptr && param->write.is_prep != true) { + m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. + } } - log_d(" - Response to write event: New value: handle: %.2x, uuid: %s", + ESP_LOGD(LOG_TAG, " - Response to write event: New value: handle: %.2x, uuid: %s", getHandle(), getUUID().toString().c_str()); char* pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len); - log_d(" - Data: length: %d, data: %s", param->write.len, pHexData); + ESP_LOGD(LOG_TAG, " - Data: length: %d, data: %s", param->write.len, pHexData); free(pHexData); if (param->write.need_rsp) { @@ -302,13 +316,10 @@ void BLECharacteristic::handleGATTServerEvent( param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &rsp); if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } } // Response needed - if (param->write.is_prep != true) { - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } } // Match on handles. break; } // ESP_GATTS_WRITE_EVT @@ -354,9 +365,9 @@ void BLECharacteristic::handleGATTServerEvent( // get mtu for peer device that we are sending read request to uint16_t maxOffset = getService()->getServer()->getPeerMTU(param->read.conn_id) - 1; - log_d("mtu value: %d", maxOffset); + ESP_LOGD(LOG_TAG, "mtu value: %d", maxOffset); if (param->read.need_rsp) { - log_d("Sending a response (esp_ble_gatts_send_response)"); + ESP_LOGD(LOG_TAG, "Sending a response (esp_ble_gatts_send_response)"); esp_gatt_rsp_t rsp; if (param->read.is_long) { @@ -377,10 +388,9 @@ void BLECharacteristic::handleGATTServerEvent( } } else { // read.is_long == false - // If is.long is false then this is the first (or only) request to read data, so invoke the callback - // Invoke the read callback. - m_pCallbacks->onRead(this); - + if (m_pCallbacks != nullptr) { // If is.long is false then this is the first (or only) request to read data, so invoke the callback + m_pCallbacks->onRead(this); // Invoke the read callback. + } std::string value = m_value.getValue(); if (value.length() + 1 > maxOffset) { @@ -395,12 +405,16 @@ void BLECharacteristic::handleGATTServerEvent( rsp.attr_value.offset = 0; memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); } + + // if (m_pCallbacks != nullptr) { // If is.long is false then this is the first (or only) request to read data, so invoke the callback + // m_pCallbacks->onRead(this); // Invoke the read callback. + // } } rsp.attr_value.handle = param->read.handle; rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len); - log_d(" - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset); + ESP_LOGD(LOG_TAG, " - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset); free(pHexData); esp_err_t errRc = ::esp_ble_gatts_send_response( @@ -409,7 +423,7 @@ void BLECharacteristic::handleGATTServerEvent( ESP_GATT_OK, &rsp); if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } } // Response needed } // Handle matches this characteristic. @@ -424,7 +438,7 @@ void BLECharacteristic::handleGATTServerEvent( // - uint16_t conn_id – The connection used. // case ESP_GATTS_CONF_EVT: { - // log_d("m_handle = %d, conf->handle = %d", m_handle, param->conf.handle); + // ESP_LOGD(LOG_TAG, "m_handle = %d, conf->handle = %d", m_handle, param->conf.handle); if(param->conf.conn_id == getService()->getServer()->getConnId()) // && param->conf.handle == m_handle) // bug in esp-idf and not implemented in arduino yet m_semaphoreConfEvt.give(param->conf.status); break; @@ -449,7 +463,7 @@ void BLECharacteristic::handleGATTServerEvent( // event. m_descriptorMap.handleGATTServerEvent(event, gatts_if, param); - log_v("<< handleGATTServerEvent"); + ESP_LOGD(LOG_TAG, "<< handleGATTServerEvent"); } // handleGATTServerEvent @@ -461,9 +475,9 @@ void BLECharacteristic::handleGATTServerEvent( */ void BLECharacteristic::indicate() { - log_v(">> indicate: length: %d", m_value.getValue().length()); + ESP_LOGD(LOG_TAG, ">> indicate: length: %d", m_value.getValue().length()); notify(false); - log_v("<< indicate"); + ESP_LOGD(LOG_TAG, "<< indicate"); } // indicate @@ -474,74 +488,60 @@ void BLECharacteristic::indicate() { * @return N/A. */ void BLECharacteristic::notify(bool is_notification) { - log_v(">> notify: length: %d", m_value.getValue().length()); + ESP_LOGD(LOG_TAG, ">> notify: length: %d", m_value.getValue().length()); assert(getService() != nullptr); assert(getService()->getServer() != nullptr); - m_pCallbacks->onNotify(this); // Invoke the notify callback. - GeneralUtils::hexDump((uint8_t*)m_value.getValue().data(), m_value.getValue().length()); if (getService()->getServer()->getConnectedCount() == 0) { - log_v("<< notify: No connected clients."); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0); + ESP_LOGD(LOG_TAG, "<< notify: No connected clients."); return; } // Test to see if we have a 0x2902 descriptor. If we do, then check to see if notification is enabled // and, if not, prevent the notification. - BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); + BLE2902* p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); + if(p2902 == nullptr){ + ESP_LOGE(LOG_TAG, "Characteristic without 0x2902 descriptor"); + return; + } if(is_notification) { if (p2902 != nullptr && !p2902->getNotifications()) { - log_v("<< notifications disabled; ignoring"); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0); // Invoke the notify callback. + ESP_LOGD(LOG_TAG, "<< notifications disabled; ignoring"); return; } } else{ if (p2902 != nullptr && !p2902->getIndications()) { - log_v("<< indications disabled; ignoring"); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0); // Invoke the notify callback. + ESP_LOGD(LOG_TAG, "<< indications disabled; ignoring"); return; } } for (auto &myPair : getService()->getServer()->getPeerDevices(false)) { uint16_t _mtu = (myPair.second.mtu); if (m_value.getValue().length() > _mtu - 3) { - log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3); + ESP_LOGW(LOG_TAG, "- Truncating to %d bytes (maximum notify size)", _mtu - 3); } size_t length = m_value.getValue().length(); - if(!is_notification) // is indication + if(!is_notification) m_semaphoreConfEvt.take("indicate"); esp_err_t errRc = ::esp_ble_gatts_send_indicate( getService()->getServer()->getGattsIf(), myPair.first, getHandle(), length, (uint8_t*)m_value.getValue().data(), !is_notification); // The need_confirm = false makes this a notify. if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_send_ %s: rc=%d %s",is_notification?"notify":"indicate", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_send_ %s: rc=%d %s",is_notification?"notify":"indicate", errRc, GeneralUtils::errorToString(errRc)); m_semaphoreConfEvt.give(); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, errRc); // Invoke the notify callback. return; } - if(!is_notification){ // is indication - if(!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)){ - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0); // Invoke the notify callback. - } else { - auto code = (esp_gatt_status_t) m_semaphoreConfEvt.value(); - if(code == ESP_GATT_OK) { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code); // Invoke the notify callback. - } else { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code); - } - } - } else { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0); // Invoke the notify callback. - } + if(!is_notification) + m_semaphoreConfEvt.wait("indicate"); } - log_v("<< notify"); + ESP_LOGD(LOG_TAG, "<< notify"); } // Notify @@ -553,7 +553,7 @@ void BLECharacteristic::notify(bool is_notification) { * @return N/A */ void BLECharacteristic::setBroadcastProperty(bool value) { - //log_d("setBroadcastProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setBroadcastProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST); } else { @@ -567,13 +567,9 @@ void BLECharacteristic::setBroadcastProperty(bool value) { * @param [in] pCallbacks An instance of a callbacks structure used to define any callbacks for the characteristic. */ void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks* pCallbacks) { - log_v(">> setCallbacks: 0x%x", (uint32_t)pCallbacks); - if (pCallbacks != nullptr){ - m_pCallbacks = pCallbacks; - } else { - m_pCallbacks = &defaultCallback; - } - log_v("<< setCallbacks"); + ESP_LOGD(LOG_TAG, ">> setCallbacks: 0x%x", (uint32_t)pCallbacks); + m_pCallbacks = pCallbacks; + ESP_LOGD(LOG_TAG, "<< setCallbacks"); } // setCallbacks @@ -588,9 +584,9 @@ void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks* pCallbacks) { * @param [in] handle The handle associated with this characteristic. */ void BLECharacteristic::setHandle(uint16_t handle) { - log_v(">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str()); m_handle = handle; - log_v("<< setHandle"); + ESP_LOGD(LOG_TAG, "<< setHandle"); } // setHandle @@ -599,7 +595,7 @@ void BLECharacteristic::setHandle(uint16_t handle) { * @param [in] value Set to true if we are to allow indicate messages. */ void BLECharacteristic::setIndicateProperty(bool value) { - //log_d("setIndicateProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setIndicateProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_INDICATE); } else { @@ -613,7 +609,7 @@ void BLECharacteristic::setIndicateProperty(bool value) { * @param [in] value Set to true if we are to allow notification messages. */ void BLECharacteristic::setNotifyProperty(bool value) { - //log_d("setNotifyProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setNotifyProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_NOTIFY); } else { @@ -627,7 +623,7 @@ void BLECharacteristic::setNotifyProperty(bool value) { * @param [in] value Set to true if we are to allow reads. */ void BLECharacteristic::setReadProperty(bool value) { - //log_d("setReadProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setReadProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_READ); } else { @@ -643,16 +639,14 @@ void BLECharacteristic::setReadProperty(bool value) { */ void BLECharacteristic::setValue(uint8_t* data, size_t length) { char* pHex = BLEUtils::buildHexData(nullptr, data, length); - log_v(">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str()); free(pHex); if (length > ESP_GATT_MAX_ATTR_LEN) { - log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); + ESP_LOGE(LOG_TAG, "Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); return; } - m_semaphoreSetValue.take(); m_value.setValue(data, length); - m_semaphoreSetValue.give(); - log_v("<< setValue"); + ESP_LOGD(LOG_TAG, "<< setValue"); } // setValue @@ -693,13 +687,15 @@ void BLECharacteristic::setValue(int& data32) { } // setValue void BLECharacteristic::setValue(float& data32) { - float temp = data32; - setValue((uint8_t*)&temp, 4); + uint8_t temp[4]; + *((float*)temp) = data32; + setValue(temp, 4); } // setValue void BLECharacteristic::setValue(double& data64) { - double temp = data64; - setValue((uint8_t*)&temp, 8); + uint8_t temp[8]; + *((double*)temp) = data64; + setValue(temp, 8); } // setValue @@ -708,7 +704,7 @@ void BLECharacteristic::setValue(double& data64) { * @param [in] value Set to true if we are to allow writes with no response. */ void BLECharacteristic::setWriteNoResponseProperty(bool value) { - //log_d("setWriteNoResponseProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setWriteNoResponseProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE_NR); } else { @@ -722,7 +718,7 @@ void BLECharacteristic::setWriteNoResponseProperty(bool value) { * @param [in] value Set to true if we are to allow writes. */ void BLECharacteristic::setWriteProperty(bool value) { - //log_d("setWriteProperty(%d)", value); + //ESP_LOGD(LOG_TAG, "setWriteProperty(%d)", value); if (value) { m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE); } else { @@ -736,18 +732,17 @@ void BLECharacteristic::setWriteProperty(bool value) { * @return A string representation of the characteristic. */ std::string BLECharacteristic::toString() { - std::string res = "UUID: " + m_bleUUID.toString() + ", handle : 0x"; - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", m_handle); - res += hex; - res += " "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_READ) res += "Read "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE) res += "Write "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) res += "WriteNoResponse "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_BROADCAST) res += "Broadcast "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY) res += "Notify "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_INDICATE) res += "Indicate "; - return res; + std::stringstream stringstream; + stringstream << std::hex << std::setfill('0'); + stringstream << "UUID: " << m_bleUUID.toString() + ", handle: 0x" << std::setw(2) << m_handle; + stringstream << " " << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_READ) ? "Read " : "") << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE) ? "Write " : "") << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) ? "WriteNoResponse " : "") << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_BROADCAST) ? "Broadcast " : "") << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY) ? "Notify " : "") << + ((m_properties & ESP_GATT_CHAR_PROP_BIT_INDICATE) ? "Indicate " : ""); + return stringstream.str(); } // toString @@ -759,8 +754,8 @@ BLECharacteristicCallbacks::~BLECharacteristicCallbacks() {} * @param [in] pCharacteristic The characteristic that is the source of the event. */ void BLECharacteristicCallbacks::onRead(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onRead: default"); - log_d("BLECharacteristicCallbacks", "<< onRead"); + ESP_LOGD("BLECharacteristicCallbacks", ">> onRead: default"); + ESP_LOGD("BLECharacteristicCallbacks", "<< onRead"); } // onRead @@ -769,31 +764,8 @@ void BLECharacteristicCallbacks::onRead(BLECharacteristic* pCharacteristic) { * @param [in] pCharacteristic The characteristic that is the source of the event. */ void BLECharacteristicCallbacks::onWrite(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onWrite: default"); - log_d("BLECharacteristicCallbacks", "<< onWrite"); + ESP_LOGD("BLECharacteristicCallbacks", ">> onWrite: default"); + ESP_LOGD("BLECharacteristicCallbacks", "<< onWrite"); } // onWrite - -/** - * @brief Callback function to support a Notify request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onNotify(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onNotify: default"); - log_d("BLECharacteristicCallbacks", "<< onNotify"); -} // onNotify - - -/** - * @brief Callback function to support a Notify/Indicate Status report. - * @param [in] pCharacteristic The characteristic that is the source of the event. - * @param [in] s Status of the notification/indication - * @param [in] code Additional code of underlying errors - */ -void BLECharacteristicCallbacks::onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code) { - log_d("BLECharacteristicCallbacks", ">> onStatus: default"); - log_d("BLECharacteristicCallbacks", "<< onStatus"); -} // onStatus - - #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLECharacteristic.h b/libraries/BLE/src/BLECharacteristic.h index adec9587ee0..82a8d7d0626 100644 --- a/libraries/BLE/src/BLECharacteristic.h +++ b/libraries/BLE/src/BLECharacteristic.h @@ -90,8 +90,6 @@ class BLECharacteristic { static const uint32_t PROPERTY_INDICATE = 1<<4; static const uint32_t PROPERTY_WRITE_NR = 1<<5; - static const uint32_t indicationTimeout = 1000; - private: friend class BLEServer; @@ -107,6 +105,7 @@ class BLECharacteristic { BLEService* m_pService; BLEValue m_value; esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; + bool m_writeEvt = false; void handleGATTServerEvent( esp_gatts_cb_event_t event, @@ -119,7 +118,6 @@ class BLECharacteristic { void setHandle(uint16_t handle); FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt"); - FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue"); }; // BLECharacteristic @@ -132,22 +130,9 @@ class BLECharacteristic { */ class BLECharacteristicCallbacks { public: - typedef enum { - SUCCESS_INDICATE, - SUCCESS_NOTIFY, - ERROR_INDICATE_DISABLED, - ERROR_NOTIFY_DISABLED, - ERROR_GATT, - ERROR_NO_CLIENT, - ERROR_INDICATE_TIMEOUT, - ERROR_INDICATE_FAILURE - }Status; - virtual ~BLECharacteristicCallbacks(); virtual void onRead(BLECharacteristic* pCharacteristic); virtual void onWrite(BLECharacteristic* pCharacteristic); - virtual void onNotify(BLECharacteristic* pCharacteristic); - virtual void onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code); }; #endif /* CONFIG_BT_ENABLED */ #endif /* COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ */ diff --git a/libraries/BLE/src/BLECharacteristicMap.cpp b/libraries/BLE/src/BLECharacteristicMap.cpp index 6e648fc7cdc..d73aae99866 100644 --- a/libraries/BLE/src/BLECharacteristicMap.cpp +++ b/libraries/BLE/src/BLECharacteristicMap.cpp @@ -116,18 +116,17 @@ void BLECharacteristicMap::setByUUID(BLECharacteristic* pCharacteristic, BLEUUID * @return A string representation of the characteristic map. */ std::string BLECharacteristicMap::toString() { - std::string res; + std::stringstream stringStream; + stringStream << std::hex << std::setfill('0'); int count = 0; - char hex[5]; for (auto &myPair: m_uuidMap) { - if (count > 0) {res += "\n";} - snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); + if (count > 0) { + stringStream << "\n"; + } count++; - res += "handle: 0x"; - res += hex; - res += ", uuid: " + myPair.first->getUUID().toString(); + stringStream << "handle: 0x" << std::setw(2) << myPair.first->getHandle() << ", uuid: " + myPair.first->getUUID().toString(); } - return res; + return stringStream.str(); } // toString diff --git a/libraries/BLE/src/BLEClient.cpp b/libraries/BLE/src/BLEClient.cpp index 436813f859d..d6e759889cf 100644 --- a/libraries/BLE/src/BLEClient.cpp +++ b/libraries/BLE/src/BLEClient.cpp @@ -18,7 +18,14 @@ #include #include #include "BLEDevice.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEClient"; +#endif + /* * Design @@ -47,6 +54,21 @@ BLEClient::BLEClient() { m_gattc_if = ESP_GATT_IF_NONE; m_haveServices = false; m_isConnected = false; // Initially, we are flagged as not connected. + + + m_appId = BLEDevice::m_appId++; + m_appId = m_appId%100; + BLEDevice::addPeerDevice(this, true, m_appId); + m_semaphoreRegEvt.take("connect"); + + esp_err_t errRc = ::esp_ble_gattc_app_register(m_appId); + if (errRc != ESP_OK) { + ESP_LOGE(LOG_TAG, "esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return; + } + + m_semaphoreRegEvt.wait("connect"); + } // BLEClient @@ -56,10 +78,12 @@ BLEClient::BLEClient() { BLEClient::~BLEClient() { // We may have allocated service references associated with this client. Before we are finished // with the client, we must release resources. - for (auto &myPair : m_servicesMap) { - delete myPair.second; - } - m_servicesMap.clear(); + clearServices(); + esp_ble_gattc_app_unregister(m_gattc_if); + BLEDevice::removePeerDevice(m_appId, true); + if(m_deleteCallbacks) + delete m_pClientCallbacks; + } // ~BLEClient @@ -68,14 +92,15 @@ BLEClient::~BLEClient() { * */ void BLEClient::clearServices() { - log_v(">> clearServices"); + ESP_LOGD(LOG_TAG, ">> clearServices"); // Delete all the services. for (auto &myPair : m_servicesMap) { delete myPair.second; } m_servicesMap.clear(); + m_servicesMapByInstID.clear(); m_haveServices = false; - log_v("<< clearServices"); + ESP_LOGD(LOG_TAG, "<< clearServices"); } // clearServices /** @@ -93,40 +118,26 @@ bool BLEClient::connect(BLEAdvertisedDevice* device) { * @return True on success. */ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { - log_v(">> connect(%s)", address.toString().c_str()); - -// We need the connection handle that we get from registering the application. We register the app -// and then block on its completion. When the event has arrived, we will have the handle. - m_appId = BLEDevice::m_appId++; - BLEDevice::addPeerDevice(this, true, m_appId); - m_semaphoreRegEvt.take("connect"); - - // clearServices(); // we dont need to delete services since every client is unique? - esp_err_t errRc = ::esp_ble_gattc_app_register(m_appId); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return false; - } - - m_semaphoreRegEvt.wait("connect"); + ESP_LOGD(LOG_TAG, ">> connect(%s)", address.toString().c_str()); + clearServices(); m_peerAddress = address; // Perform the open connection request against the target BLE Server. m_semaphoreOpenEvt.take("connect"); - errRc = ::esp_ble_gattc_open( + esp_err_t errRc = ::esp_ble_gattc_open( m_gattc_if, *getPeerAddress().getNative(), // address type, // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature. 1 // direct connection <-- maybe needs to be changed in case of direct indirect connection??? ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return false; } uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. - log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); + ESP_LOGD(LOG_TAG, "<< connect(), rc=%d", rc==ESP_GATT_OK); return rc == ESP_GATT_OK; } // connect @@ -136,13 +147,14 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { * @return N/A. */ void BLEClient::disconnect() { - log_v(">> disconnect()"); + ESP_LOGD(LOG_TAG, ">> disconnect()"); + // ESP_LOGW(__func__, "gattIf: %d, connId: %d", getGattcIf(), getConnId()); esp_err_t errRc = ::esp_ble_gattc_close(getGattcIf(), getConnId()); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } - log_v("<< disconnect()"); + ESP_LOGD(LOG_TAG, "<< disconnect()"); } // disconnect @@ -154,21 +166,21 @@ void BLEClient::gattClientEventHandler( esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) { - log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", + ESP_LOGD(LOG_TAG, "gattClientEventHandler [esp_gatt_if: %d] ... %s", gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); // Execute handler code based on the type of event received. switch(event) { case ESP_GATTC_SRVC_CHG_EVT: - log_i("SERVICE CHANGED"); + if(m_gattc_if != gattc_if) + break; + + ESP_LOGI(LOG_TAG, "SERVICE CHANGED"); break; - case ESP_GATTC_CLOSE_EVT: { - // esp_ble_gattc_app_unregister(m_appId); - // BLEDevice::removePeerDevice(m_gattc_if, true); + case ESP_GATTC_CLOSE_EVT: break; - } // // ESP_GATTC_DISCONNECT_EVT @@ -178,18 +190,20 @@ void BLEClient::gattClientEventHandler( // - uint16_t conn_id // - esp_bd_addr_t remote_bda case ESP_GATTC_DISCONNECT_EVT: { - // If we receive a disconnect event, set the class flag that indicates that we are - // no longer connected. - m_isConnected = false; - if (m_pClientCallbacks != nullptr) { - m_pClientCallbacks->onDisconnect(this); - } - esp_ble_gattc_app_unregister(m_gattc_if); - m_semaphoreOpenEvt.give(ESP_GATT_IF_NONE); - m_semaphoreRssiCmplEvt.give(); - m_semaphoreSearchCmplEvt.give(1); - BLEDevice::removePeerDevice(m_appId, true); + ESP_LOGE(__func__, "disconnect event, reason: %d, connId: %d, my connId: %d, my IF: %d, gattc_if: %d", (int)evtParam->disconnect.reason, evtParam->disconnect.conn_id, getConnId(), getGattcIf(), gattc_if); + if(m_gattc_if != gattc_if) + break; + m_semaphoreOpenEvt.give(evtParam->disconnect.reason); + if(!m_isConnected) break; + // If we receive a disconnect event, set the class flag that indicates that we are + // no longer connected. + esp_ble_gattc_close(m_gattc_if, m_conn_id); + m_isConnected = false; + if (m_pClientCallbacks != nullptr) { + m_pClientCallbacks->onDisconnect(this); + } + break; } // ESP_GATTC_DISCONNECT_EVT // @@ -201,12 +215,15 @@ void BLEClient::gattClientEventHandler( // - esp_bd_addr_t remote_bda // case ESP_GATTC_OPEN_EVT: { + if(m_gattc_if != gattc_if) + break; m_conn_id = evtParam->open.conn_id; if (m_pClientCallbacks != nullptr) { m_pClientCallbacks->onConnect(this); } if (evtParam->open.status == ESP_GATT_OK) { m_isConnected = true; // Flag us as connected. + m_mtu = evtParam->open.mtu; } m_semaphoreOpenEvt.give(evtParam->open.status); break; @@ -221,23 +238,30 @@ void BLEClient::gattClientEventHandler( // uint16_t app_id // case ESP_GATTC_REG_EVT: { - m_gattc_if = gattc_if; - m_semaphoreRegEvt.give(); + if(m_appId == evtParam->reg.app_id){ + ESP_LOGI(__func__, "register app id: %d, %d, gattc_if: %d", m_appId, evtParam->reg.app_id, gattc_if); + m_gattc_if = gattc_if; + m_semaphoreRegEvt.give(); + } break; } // ESP_GATTC_REG_EVT case ESP_GATTC_CFG_MTU_EVT: if(evtParam->cfg_mtu.status != ESP_GATT_OK) { - log_e("Config mtu failed"); + ESP_LOGE(LOG_TAG,"Config mtu failed"); } - m_mtu = evtParam->cfg_mtu.mtu; + else + m_mtu = evtParam->cfg_mtu.mtu; break; case ESP_GATTC_CONNECT_EVT: { + if(m_gattc_if != gattc_if) + break; + m_conn_id = evtParam->connect.conn_id; BLEDevice::updatePeerDevice(this, true, m_gattc_if); esp_err_t errRc = esp_ble_gattc_send_mtu_req(gattc_if, evtParam->connect.conn_id); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_send_mtu_req: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_send_mtu_req: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig if(BLEDevice::m_securityLevel){ @@ -255,22 +279,22 @@ void BLEClient::gattClientEventHandler( // - uint16_t conn_id // case ESP_GATTC_SEARCH_CMPL_EVT: { - esp_ble_gattc_cb_param_t* p_data = (esp_ble_gattc_cb_param_t*)evtParam; - if (p_data->search_cmpl.status != ESP_GATT_OK){ - log_e("search service failed, error status = %x", p_data->search_cmpl.status); + if(m_gattc_if != gattc_if) break; + if (evtParam->search_cmpl.status != ESP_GATT_OK){ + ESP_LOGE(LOG_TAG, "search service failed, error status = %x", evtParam->search_cmpl.status); } #ifndef ARDUINO_ARCH_ESP32 // commented out just for now to keep backward compatibility // if(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) { - // log_i("Get service information from remote device"); + // ESP_LOGI(LOG_TAG, "Get service information from remote device"); // } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) { - // log_i("Get service information from flash"); + // ESP_LOGI(LOG_TAG, "Get service information from flash"); // } else { - // log_i("unknown service source"); + // ESP_LOGI(LOG_TAG, "unknown service source"); // } #endif - m_semaphoreSearchCmplEvt.give(0); + m_semaphoreSearchCmplEvt.give(evtParam->search_cmpl.status); break; } // ESP_GATTC_SEARCH_CMPL_EVT @@ -285,6 +309,9 @@ void BLEClient::gattClientEventHandler( // - esp_gatt_id_t srvc_id // case ESP_GATTC_SEARCH_RES_EVT: { + if(m_gattc_if != gattc_if) + break; + BLEUUID uuid = BLEUUID(evtParam->search_res.srvc_id); BLERemoteService* pRemoteService = new BLERemoteService( evtParam->search_res.srvc_id, @@ -337,9 +364,9 @@ BLEAddress BLEClient::getPeerAddress() { * @return The RSSI value. */ int BLEClient::getRssi() { - log_v(">> getRssi()"); + ESP_LOGD(LOG_TAG, ">> getRssi()"); if (!isConnected()) { - log_v("<< getRssi(): Not connected"); + ESP_LOGD(LOG_TAG, "<< getRssi(): Not connected"); return 0; } // We make the API call to read the RSSI value which is an asynchronous operation. We expect to receive @@ -348,11 +375,11 @@ int BLEClient::getRssi() { m_semaphoreRssiCmplEvt.take("getRssi"); esp_err_t rc = ::esp_ble_gap_read_rssi(*getPeerAddress().getNative()); if (rc != ESP_OK) { - log_e("<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc)); + ESP_LOGE(LOG_TAG, "<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc)); return 0; } int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi"); - log_v("<< getRssi(): %d", rssiValue); + ESP_LOGD(LOG_TAG, "<< getRssi(): %d", rssiValue); return rssiValue; } // getRssi @@ -374,7 +401,7 @@ BLERemoteService* BLEClient::getService(const char* uuid) { * @throws BLEUuidNotFound */ BLERemoteService* BLEClient::getService(BLEUUID uuid) { - log_v(">> getService: uuid: %s", uuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> getService: uuid: %s", uuid.toString().c_str()); // Design // ------ // We wish to retrieve the service given its UUID. It is possible that we have not yet asked the @@ -387,11 +414,11 @@ BLERemoteService* BLEClient::getService(BLEUUID uuid) { std::string uuidStr = uuid.toString(); for (auto &myPair : m_servicesMap) { if (myPair.first == uuidStr) { - log_v("<< getService: found the service with uuid: %s", uuid.toString().c_str()); + ESP_LOGD(LOG_TAG, "<< getService: found the service with uuid: %s", uuid.toString().c_str()); return myPair.second; } } // End of each of the services. - log_v("<< getService: not found"); + ESP_LOGD(LOG_TAG, "<< getService: not found"); return nullptr; } // getService @@ -410,7 +437,7 @@ std::map* BLEClient::getServices() { * peer BLE partner to be returned as events. Each event will be an an instance of ESP_GATTC_SEARCH_RES_EVT * and will culminate with an ESP_GATTC_SEARCH_CMPL_EVT when all have been received. */ - log_v(">> getServices"); + ESP_LOGD(LOG_TAG, ">> getServices"); // TODO implement retrieving services from cache clearServices(); // Clear any services that may exist. @@ -422,12 +449,12 @@ std::map* BLEClient::getServices() { m_semaphoreSearchCmplEvt.take("getServices"); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_search_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_search_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return &m_servicesMap; } // If sucessfull, remember that we now have services. m_haveServices = (m_semaphoreSearchCmplEvt.wait("getServices") == 0); - log_v("<< getServices"); + ESP_LOGD(LOG_TAG, "<< getServices"); return &m_servicesMap; } // getServices @@ -439,9 +466,9 @@ std::map* BLEClient::getServices() { * @throws BLEUuidNotFound */ std::string BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) { - log_v(">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); std::string ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue(); - log_v("<> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value); - log_v("<< setValue"); + ESP_LOGD(LOG_TAG, "<< setValue"); } // setValue uint16_t BLEClient::getMTU() { @@ -516,13 +544,14 @@ uint16_t BLEClient::getMTU() { * @return A string representation of this client. */ std::string BLEClient::toString() { - std::string res = "peer address: " + m_peerAddress.toString(); - res += "\nServices:\n"; + std::ostringstream ss; + ss << "peer address: " << m_peerAddress.toString(); + ss << "\nServices:\n"; for (auto &myPair : m_servicesMap) { - res += myPair.second->toString() + "\n"; + ss << myPair.second->toString() << "\n"; // myPair.second is the value } - return res; + return ss.str(); } // toString diff --git a/libraries/BLE/src/BLEClient.h b/libraries/BLE/src/BLEClient.h index 75a288e4329..4b3c7eeabbc 100644 --- a/libraries/BLE/src/BLEClient.h +++ b/libraries/BLE/src/BLEClient.h @@ -15,7 +15,7 @@ #include #include #include -//#include "BLEExceptions.h" +#include "BLEExceptions.h" #include "BLERemoteService.h" #include "BLEService.h" #include "BLEAddress.h" @@ -50,7 +50,7 @@ class BLEClient { bool isConnected(); // Return true if we are connected. - void setClientCallbacks(BLEClientCallbacks *pClientCallbacks); + void setClientCallbacks(BLEClientCallbacks *pClientCallbacks, bool deleteCallbacks = true); void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a given characteristic at a given service. std::string toString(); // Return a string representation of this client. @@ -65,19 +65,16 @@ uint16_t m_appId; friend class BLERemoteCharacteristic; friend class BLERemoteDescriptor; - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param); + void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* param); BLEAddress m_peerAddress = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); // The BD address of the remote server. uint16_t m_conn_id; -// int m_deviceType; esp_gatt_if_t m_gattc_if; bool m_haveServices = false; // Have we previously obtain the set of services from the remote server. bool m_isConnected = false; // Are we currently connected. + bool m_deleteCallbacks = true; - BLEClientCallbacks* m_pClientCallbacks; + BLEClientCallbacks* m_pClientCallbacks = nullptr; FreeRTOS::Semaphore m_semaphoreRegEvt = FreeRTOS::Semaphore("RegEvt"); FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); FreeRTOS::Semaphore m_semaphoreSearchCmplEvt = FreeRTOS::Semaphore("SearchCmplEvt"); diff --git a/libraries/BLE/src/BLEDescriptor.cpp b/libraries/BLE/src/BLEDescriptor.cpp index 96b2de87c95..ba5753dea2e 100644 --- a/libraries/BLE/src/BLEDescriptor.cpp +++ b/libraries/BLE/src/BLEDescriptor.cpp @@ -15,7 +15,16 @@ #include "BLEService.h" #include "BLEDescriptor.h" #include "GeneralUtils.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEDescriptor"; +#endif + + + #define NULL_HANDLE (0xffff) @@ -54,10 +63,10 @@ BLEDescriptor::~BLEDescriptor() { * @param [in] pCharacteristic The characteristic to which to register this descriptor. */ void BLEDescriptor::executeCreate(BLECharacteristic* pCharacteristic) { - log_v(">> executeCreate(): %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> executeCreate(): %s", toString().c_str()); if (m_handle != NULL_HANDLE) { - log_e("Descriptor already has a handle."); + ESP_LOGE(LOG_TAG, "Descriptor already has a handle."); return; } @@ -73,12 +82,12 @@ void BLEDescriptor::executeCreate(BLECharacteristic* pCharacteristic) { &m_value, &control); if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_add_char_descr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_add_char_descr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreCreateEvt.wait("executeCreate"); - log_v("<< executeCreate"); + ESP_LOGD(LOG_TAG, "<< executeCreate"); } // executeCreate @@ -204,9 +213,9 @@ void BLEDescriptor::handleGATTServerEvent( * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor. */ void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks* pCallback) { - log_v(">> setCallbacks: 0x%x", (uint32_t) pCallback); + ESP_LOGD(LOG_TAG, ">> setCallbacks: 0x%x", (uint32_t) pCallback); m_pCallback = pCallback; - log_v("<< setCallbacks"); + ESP_LOGD(LOG_TAG, "<< setCallbacks"); } // setCallbacks @@ -217,9 +226,9 @@ void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks* pCallback) { * @return N/A. */ void BLEDescriptor::setHandle(uint16_t handle) { - log_v(">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle); + ESP_LOGD(LOG_TAG, ">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle); m_handle = handle; - log_v("<< setHandle()"); + ESP_LOGD(LOG_TAG, "<< setHandle()"); } // setHandle @@ -230,7 +239,7 @@ void BLEDescriptor::setHandle(uint16_t handle) { */ void BLEDescriptor::setValue(uint8_t* data, size_t length) { if (length > ESP_GATT_MAX_ATTR_LEN) { - log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); + ESP_LOGE(LOG_TAG, "Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); return; } m_value.attr_len = length; @@ -255,10 +264,10 @@ void BLEDescriptor::setAccessPermissions(esp_gatt_perm_t perm) { * @return A string representation of the descriptor. */ std::string BLEDescriptor::toString() { - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", m_handle); - std::string res = "UUID: " + m_bleUUID.toString() + ", handle: 0x" + hex; - return res; + std::stringstream stringstream; + stringstream << std::hex << std::setfill('0'); + stringstream << "UUID: " << m_bleUUID.toString() + ", handle: 0x" << std::setw(2) << m_handle; + return stringstream.str(); } // toString @@ -269,8 +278,8 @@ BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {} * @param [in] pDescriptor The descriptor that is the source of the event. */ void BLEDescriptorCallbacks::onRead(BLEDescriptor* pDescriptor) { - log_d("BLEDescriptorCallbacks", ">> onRead: default"); - log_d("BLEDescriptorCallbacks", "<< onRead"); + ESP_LOGD("BLEDescriptorCallbacks", ">> onRead: default"); + ESP_LOGD("BLEDescriptorCallbacks", "<< onRead"); } // onRead @@ -279,8 +288,8 @@ void BLEDescriptorCallbacks::onRead(BLEDescriptor* pDescriptor) { * @param [in] pDescriptor The descriptor that is the source of the event. */ void BLEDescriptorCallbacks::onWrite(BLEDescriptor* pDescriptor) { - log_d("BLEDescriptorCallbacks", ">> onWrite: default"); - log_d("BLEDescriptorCallbacks", "<< onWrite"); + ESP_LOGD("BLEDescriptorCallbacks", ">> onWrite: default"); + ESP_LOGD("BLEDescriptorCallbacks", "<< onWrite"); } // onWrite diff --git a/libraries/BLE/src/BLEDescriptorMap.cpp b/libraries/BLE/src/BLEDescriptorMap.cpp index 0b5d3175a9d..6b8458330c8 100644 --- a/libraries/BLE/src/BLEDescriptorMap.cpp +++ b/libraries/BLE/src/BLEDescriptorMap.cpp @@ -90,18 +90,17 @@ void BLEDescriptorMap::setByHandle(uint16_t handle, BLEDescriptor* pDescriptor) * @return A string representation of the descriptor map. */ std::string BLEDescriptorMap::toString() { - std::string res; - char hex[5]; + std::stringstream stringStream; + stringStream << std::hex << std::setfill('0'); int count = 0; for (auto &myPair : m_uuidMap) { - if (count > 0) {res += "\n";} - snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); + if (count > 0) { + stringStream << "\n"; + } count++; - res += "handle: 0x"; - res += hex; - res += ", uuid: " + myPair.first->getUUID().toString(); + stringStream << "handle: 0x" << std::setw(2) << myPair.first->getHandle() << ", uuid: " + myPair.first->getUUID().toString(); } - return res; + return stringStream.str(); } // toString diff --git a/libraries/BLE/src/BLEDevice.cpp b/libraries/BLE/src/BLEDevice.cpp index 128ede98d84..78bd13d3401 100644 --- a/libraries/BLE/src/BLEDevice.cpp +++ b/libraries/BLE/src/BLEDevice.cpp @@ -27,20 +27,24 @@ #include "BLEClient.h" #include "BLEUtils.h" #include "GeneralUtils.h" +#if defined(CONFIG_ARDUHAL_ESP_LOG) +#include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEDevice"; +#endif -#if defined(ARDUINO_ARCH_ESP32) +#if defined(ARDUINO_ARCH_ESP32) #include "esp32-hal-bt.h" #endif -#include "esp32-hal-log.h" - - /** * Singletons for the BLEDevice. */ BLEServer* BLEDevice::m_pServer = nullptr; BLEScan* BLEDevice::m_pScan = nullptr; -BLEClient* BLEDevice::m_pClient = nullptr; +// BLEClient* BLEDevice::m_pClient = nullptr; bool initialized = false; esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0; BLESecurityCallbacks* BLEDevice::m_securityCallbacks = nullptr; @@ -57,13 +61,13 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @return A new instance of the client. */ /* STATIC */ BLEClient* BLEDevice::createClient() { - log_v(">> createClient"); + ESP_LOGD(LOG_TAG, ">> createClient"); #ifndef CONFIG_GATTC_ENABLE // Check that BLE GATTC is enabled in make menuconfig - log_e("BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined"); + ESP_LOGE(LOG_TAG, "BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined"); abort(); #endif // CONFIG_GATTC_ENABLE - m_pClient = new BLEClient(); - log_v("<< createClient"); + BLEClient* m_pClient = new BLEClient(); + ESP_LOGD(LOG_TAG, "<< createClient"); return m_pClient; } // createClient @@ -73,14 +77,14 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @return A new instance of the server. */ /* STATIC */ BLEServer* BLEDevice::createServer() { - log_v(">> createServer"); + ESP_LOGD(LOG_TAG, ">> createServer"); #ifndef CONFIG_GATTS_ENABLE // Check that BLE GATTS is enabled in make menuconfig - log_e("BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined"); + ESP_LOGE(LOG_TAG, "BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined"); abort(); #endif // CONFIG_GATTS_ENABLE - m_pServer = new BLEServer(); + BLEDevice::m_pServer = new BLEServer(); m_pServer->createApp(m_appId++); - log_v("<< createServer"); + ESP_LOGD(LOG_TAG, "<< createServer"); return m_pServer; } // createServer @@ -97,7 +101,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param ) { - log_d("gattServerEventHandler [esp_gatt_if: %d] ... %s", + ESP_LOGD(LOG_TAG, "gattServerEventHandler [esp_gatt_if: %d] ... %s", gatts_if, BLEUtils::gattServerEventTypeToString(event).c_str()); @@ -144,7 +148,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* param) { - log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", + ESP_LOGD(LOG_TAG, "gattClientEventHandler [esp_gatt_if: %d] ... %s", gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); BLEUtils::dumpGattClientEvent(event, gattc_if, param); @@ -188,16 +192,16 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; switch(event) { case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ - log_i("ESP_GAP_BLE_OOB_REQ_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_OOB_REQ_EVT"); break; case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ - log_i("ESP_GAP_BLE_LOCAL_IR_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_LOCAL_IR_EVT"); break; case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ - log_i("ESP_GAP_BLE_LOCAL_ER_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_LOCAL_ER_EVT"); break; case ESP_GAP_BLE_NC_REQ_EVT: /* NUMERIC CONFIRMATION */ - log_i("ESP_GAP_BLE_NC_REQ_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_NC_REQ_EVT"); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig if(BLEDevice::m_securityCallbacks != nullptr){ esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey)); @@ -205,8 +209,8 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; #endif // CONFIG_BLE_SMP_ENABLE break; case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ - log_i("ESP_GAP_BLE_PASSKEY_REQ_EVT: "); - // esp_log_buffer_hex(m_remote_bda, sizeof(m_remote_bda)); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_PASSKEY_REQ_EVT: "); + // esp_log_buffer_hex(LOG_TAG, m_remote_bda, sizeof(m_remote_bda)); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig if(BLEDevice::m_securityCallbacks != nullptr){ esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest()); @@ -219,7 +223,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; case ESP_GAP_BLE_SEC_REQ_EVT: /* send the positive(true) security response to the peer device to accept the security request. If not accept the security request, should sent the security response with negative(false) accept value*/ - log_i("ESP_GAP_BLE_SEC_REQ_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_SEC_REQ_EVT"); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig if(BLEDevice::m_securityCallbacks!=nullptr){ esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest()); @@ -234,9 +238,9 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; */ case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: //the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. //display the passkey number to the user to input it in the peer deivce within 30 seconds - log_i("ESP_GAP_BLE_PASSKEY_NOTIF_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_PASSKEY_NOTIF_EVT"); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - log_i("passKey = %d", param->ble_security.key_notif.passkey); + ESP_LOGI(LOG_TAG, "passKey = %d", param->ble_security.key_notif.passkey); if(BLEDevice::m_securityCallbacks!=nullptr){ BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey); } @@ -244,13 +248,13 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; break; case ESP_GAP_BLE_KEY_EVT: //shows the ble key type info share with peer device to the user. - log_d("ESP_GAP_BLE_KEY_EVT"); + ESP_LOGD(LOG_TAG, "ESP_GAP_BLE_KEY_EVT"); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - log_i("key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type)); + ESP_LOGI(LOG_TAG, "key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type)); #endif // CONFIG_BLE_SMP_ENABLE break; case ESP_GAP_BLE_AUTH_CMPL_EVT: - log_i("ESP_GAP_BLE_AUTH_CMPL_EVT"); + ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_AUTH_CMPL_EVT"); #ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig if(BLEDevice::m_securityCallbacks != nullptr){ BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl); @@ -262,10 +266,6 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; } } // switch - if (BLEDevice::m_pClient != nullptr) { - BLEDevice::m_pClient->handleGAPEvent(event, param); - } - if (BLEDevice::m_pScan != nullptr) { BLEDevice::getScan()->handleGAPEvent(event, param); } @@ -299,12 +299,12 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * try and release/delete it. */ /* STATIC */ BLEScan* BLEDevice::getScan() { - //log_v(">> getScan"); + //ESP_LOGD(LOG_TAG, ">> getScan"); if (m_pScan == nullptr) { m_pScan = new BLEScan(); - //log_d(" - creating a new scan object"); + //ESP_LOGD(LOG_TAG, " - creating a new scan object"); } - //log_v("<< getScan: Returning object at 0x%x", (uint32_t)m_pScan); + //ESP_LOGD(LOG_TAG, "<< getScan: Returning object at 0x%x", (uint32_t)m_pScan); return m_pScan; } // getScan @@ -316,12 +316,12 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @param [in] characteristicUUID */ /* STATIC */ std::string BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) { - log_v(">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); BLEClient* pClient = createClient(); pClient->connect(bdAddress); std::string ret = pClient->getValue(serviceUUID, characteristicUUID); pClient->disconnect(); - log_v("<< getValue"); + ESP_LOGD(LOG_TAG, "<< getValue"); return ret; } // getValue @@ -343,7 +343,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; #else errRc = ::nvs_flash_init(); if (errRc != ESP_OK) { - log_e("nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } @@ -353,20 +353,20 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); errRc = esp_bt_controller_init(&bt_cfg); if (errRc != ESP_OK) { - log_e("esp_bt_controller_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_bt_controller_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #ifndef CLASSIC_BT_ENABLED errRc = esp_bt_controller_enable(ESP_BT_MODE_BLE); if (errRc != ESP_OK) { - log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #else errRc = esp_bt_controller_enable(ESP_BT_MODE_BTDM); if (errRc != ESP_OK) { - log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #endif @@ -376,7 +376,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED) { errRc = esp_bluedroid_init(); if (errRc != ESP_OK) { - log_e("esp_bluedroid_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_bluedroid_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } } @@ -384,21 +384,21 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; if (bt_state != ESP_BLUEDROID_STATUS_ENABLED) { errRc = esp_bluedroid_enable(); if (errRc != ESP_OK) { - log_e("esp_bluedroid_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_bluedroid_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } } errRc = esp_ble_gap_register_callback(BLEDevice::gapEventHandler); if (errRc != ESP_OK) { - log_e("esp_ble_gap_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #ifdef CONFIG_GATTC_ENABLE // Check that BLE client is configured in make menuconfig errRc = esp_ble_gattc_register_callback(BLEDevice::gattClientEventHandler); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #endif // CONFIG_GATTC_ENABLE @@ -406,14 +406,14 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; #ifdef CONFIG_GATTS_ENABLE // Check that BLE server is configured in make menuconfig errRc = esp_ble_gatts_register_callback(BLEDevice::gattServerEventHandler); if (errRc != ESP_OK) { - log_e("esp_ble_gatts_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } #endif // CONFIG_GATTS_ENABLE errRc = ::esp_ble_gap_set_device_name(deviceName.c_str()); if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_device_name: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_set_device_name: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; }; @@ -421,7 +421,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; errRc = ::esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_security_param: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_set_security_param: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; }; #endif // CONFIG_BLE_SMP_ENABLE @@ -441,30 +441,15 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * * ESP_PWR_LVL_P1 * * ESP_PWR_LVL_P4 * * ESP_PWR_LVL_P7 - * - * The power types can be one of: - * * ESP_BLE_PWR_TYPE_CONN_HDL0 - * * ESP_BLE_PWR_TYPE_CONN_HDL1 - * * ESP_BLE_PWR_TYPE_CONN_HDL2 - * * ESP_BLE_PWR_TYPE_CONN_HDL3 - * * ESP_BLE_PWR_TYPE_CONN_HDL4 - * * ESP_BLE_PWR_TYPE_CONN_HDL5 - * * ESP_BLE_PWR_TYPE_CONN_HDL6 - * * ESP_BLE_PWR_TYPE_CONN_HDL7 - * * ESP_BLE_PWR_TYPE_CONN_HDL8 - * * ESP_BLE_PWR_TYPE_ADV - * * ESP_BLE_PWR_TYPE_SCAN - * * ESP_BLE_PWR_TYPE_DEFAULT - * @param [in] powerType. * @param [in] powerLevel. */ -/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) { - log_v(">> setPower: %d (type: %d)", powerLevel, powerType); - esp_err_t errRc = ::esp_ble_tx_power_set(powerType, powerLevel); +/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel) { + ESP_LOGD(LOG_TAG, ">> setPower: %d", powerLevel); + esp_err_t errRc = ::esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT, powerLevel); if (errRc != ESP_OK) { - log_e("esp_ble_tx_power_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_tx_power_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); }; - log_v("<< setPower"); + ESP_LOGD(LOG_TAG, "<< setPower"); } // setPower @@ -475,7 +460,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @param [in] characteristicUUID */ /* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { - log_v(">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); BLEClient* pClient = createClient(); pClient->connect(bdAddress); pClient->setValue(serviceUUID, characteristicUUID, value); @@ -488,8 +473,9 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @return A string representation of the nature of this device. */ /* STATIC */ std::string BLEDevice::toString() { - std::string res = "BD Address: " + getAddress().toString(); - return res; + std::ostringstream oss; + oss << "BD Address: " << getAddress().toString(); + return oss.str(); } // toString @@ -498,12 +484,12 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @param [in] address The address to add to the white list. */ void BLEDevice::whiteListAdd(BLEAddress address) { - log_v(">> whiteListAdd: %s", address.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> whiteListAdd: %s", address.toString().c_str()); esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative()); // True to add an entry. if (errRc != ESP_OK) { - log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } - log_v("<< whiteListAdd"); + ESP_LOGD(LOG_TAG, "<< whiteListAdd"); } // whiteListAdd @@ -512,12 +498,12 @@ void BLEDevice::whiteListAdd(BLEAddress address) { * @param [in] address The address to remove from the white list. */ void BLEDevice::whiteListRemove(BLEAddress address) { - log_v(">> whiteListRemove: %s", address.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> whiteListRemove: %s", address.toString().c_str()); esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative()); // False to remove an entry. if (errRc != ESP_OK) { - log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } - log_v("<< whiteListRemove"); + ESP_LOGD(LOG_TAG, "<< whiteListRemove"); } // whiteListRemove /* @@ -541,14 +527,14 @@ void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks* callbacks) { * @param [in] mtu Value to set local mtu, should be larger than 23 and lower or equal to 517 */ esp_err_t BLEDevice::setMTU(uint16_t mtu) { - log_v(">> setLocalMTU: %d", mtu); + ESP_LOGD(LOG_TAG, ">> setLocalMTU: %d", mtu); esp_err_t err = esp_ble_gatt_set_local_mtu(mtu); if (err == ESP_OK) { m_localMTU = mtu; } else { - log_e("can't set local mtu value: %d", mtu); + ESP_LOGE(LOG_TAG, "can't set local mtu value: %d", mtu); } - log_v("<< setLocalMTU"); + ESP_LOGD(LOG_TAG, "<< setLocalMTU"); return err; } @@ -566,24 +552,18 @@ bool BLEDevice::getInitialized() { BLEAdvertising* BLEDevice::getAdvertising() { if(m_bleAdvertising == nullptr) { m_bleAdvertising = new BLEAdvertising(); - log_i("create advertising"); + ESP_LOGI(LOG_TAG, "create advertising"); } - log_d("get advertising"); + ESP_LOGD(LOG_TAG, "get advertising"); return m_bleAdvertising; } void BLEDevice::startAdvertising() { - log_v(">> startAdvertising"); + ESP_LOGD(LOG_TAG, ">> startAdvertising"); getAdvertising()->start(); - log_v("<< startAdvertising"); + ESP_LOGD(LOG_TAG, "<< startAdvertising"); } // startAdvertising -void BLEDevice::stopAdvertising() { - log_v(">> stopAdvertising"); - getAdvertising()->stop(); - log_v("<< stopAdvertising"); -} // stopAdvertising - /* multi connect support */ /* requires a little more work */ std::map BLEDevice::getPeerDevices(bool _client) { @@ -595,7 +575,7 @@ BLEClient* BLEDevice::getClientByGattIf(uint16_t conn_id) { } void BLEDevice::updatePeerDevice(void* peer, bool _client, uint16_t conn_id) { - log_d("update conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); + ESP_LOGD(LOG_TAG, "update conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); std::map::iterator it = m_connectedClientsMap.find(ESP_GATT_IF_NONE); if (it != m_connectedClientsMap.end()) { std::swap(m_connectedClientsMap[conn_id], it->second); @@ -611,7 +591,7 @@ void BLEDevice::updatePeerDevice(void* peer, bool _client, uint16_t conn_id) { } void BLEDevice::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { - log_i("add conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); + ESP_LOGI(LOG_TAG, "add conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); conn_status_t status = { .peer_device = peer, .connected = true, @@ -622,7 +602,7 @@ void BLEDevice::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { } void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) { - log_i("remove: %d, GATT role %s", conn_id, _client?"client":"server"); + ESP_LOGI(LOG_TAG, "remove: %d, GATT role %s", conn_id, _client?"client":"server"); if(m_connectedClientsMap.find(conn_id) != m_connectedClientsMap.end()) m_connectedClientsMap.erase(conn_id); } @@ -640,7 +620,7 @@ void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) { esp_bluedroid_deinit(); esp_bt_controller_disable(); esp_bt_controller_deinit(); -#ifdef ARDUINO_ARCH_ESP32 +#ifndef ARDUINO_ARCH_ESP32 if (release_memory) { esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); // <-- require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it) } else { diff --git a/libraries/BLE/src/BLEDevice.h b/libraries/BLE/src/BLEDevice.h index 4ecdf04c97c..b01f09bee35 100644 --- a/libraries/BLE/src/BLEDevice.h +++ b/libraries/BLE/src/BLEDevice.h @@ -37,7 +37,7 @@ class BLEDevice { static BLEScan* getScan(); // Get the scan object static std::string getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a characteristic of a service on a server. static void init(std::string deviceName); // Initialize the local BLE environment. - static void setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType=ESP_BLE_PWR_TYPE_DEFAULT); // Set our power level. + static void setPower(esp_power_level_t powerLevel); // Set our power level. static void setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a characteristic on a service on a server. static std::string toString(); // Return a string representation of our device. static void whiteListAdd(BLEAddress address); // Add an entry to the BLE white list. @@ -50,7 +50,6 @@ class BLEDevice { /* move advertising to BLEDevice for saving ram and flash in beacons */ static BLEAdvertising* getAdvertising(); static void startAdvertising(); - static void stopAdvertising(); static uint16_t m_appId; /* multi connect */ static std::map getPeerDevices(bool client); @@ -68,7 +67,7 @@ class BLEDevice { private: static BLEServer* m_pServer; static BLEScan* m_pScan; - static BLEClient* m_pClient; + // static BLEClient* m_pClient; static BLESecurityCallbacks* m_securityCallbacks; static BLEAdvertising* m_bleAdvertising; static esp_gatt_if_t getGattcIF(); diff --git a/libraries/BLE/src/BLEEddystoneTLM.cpp b/libraries/BLE/src/BLEEddystoneTLM.cpp old mode 100644 new mode 100755 index 1ab794932e2..a92bcdb2b40 --- a/libraries/BLE/src/BLEEddystoneTLM.cpp +++ b/libraries/BLE/src/BLEEddystoneTLM.cpp @@ -7,8 +7,8 @@ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include -#include -#include "esp32-hal-log.h" +#include +#include #include "BLEEddystoneTLM.h" static const char LOG_TAG[] = "BLEEddystoneTLM"; @@ -54,44 +54,62 @@ uint32_t BLEEddystoneTLM::getTime() { } // getTime std::string BLEEddystoneTLM::toString() { - std::string out = ""; - uint32_t rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil); - char val[6]; - - out += "Version " + m_eddystoneData.version; - out += "\n"; - out += "Battery Voltage " + ENDIAN_CHANGE_U16(m_eddystoneData.volt); - out += " mV\n"; - - out += "Temperature "; - snprintf(val, sizeof(val), "%d", m_eddystoneData.temp); - out += val; - out += ".0 °C\n"; - - out += "Adv. Count "; - snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U32(m_eddystoneData.advCount)); - out += val; - out += "\n"; - - out += "Time "; - - snprintf(val, sizeof(val), "%04d", rawsec / 864000); - out += val; - out += "."; - - snprintf(val, sizeof(val), "%02d", (rawsec / 36000) % 24); - out += val; - out += ":"; - - snprintf(val, sizeof(val), "%02d", (rawsec / 600) % 60); - out += val; - out += ":"; - - snprintf(val, sizeof(val), "%02d", (rawsec / 10) % 60); - out += val; - out += "\n"; - - return out; + std::stringstream ss; + std::string out = ""; + uint32_t rawsec; + ss << "Version "; + ss << std::dec << m_eddystoneData.version; + ss << "\n"; + + ss << "Battery Voltage "; + ss << std::dec << ENDIAN_CHANGE_U16(m_eddystoneData.volt); + ss << " mV\n"; + + ss << "Temperature "; + ss << (float) m_eddystoneData.temp; + ss << " °C\n"; + + ss << "Adv. Count "; + ss << std::dec << ENDIAN_CHANGE_U32(m_eddystoneData.advCount); + + ss << "\n"; + + ss << "Time "; + + rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil); + std::stringstream buffstream; + buffstream << "0000"; + buffstream << std::dec << rawsec / 864000; + std::string buff = buffstream.str(); + + ss << buff.substr(buff.length() - 4, buff.length()); + ss << "."; + + buffstream.str(""); + buffstream.clear(); + buffstream << "00"; + buffstream << std::dec << (rawsec / 36000) % 24; + buff = buffstream.str(); + ss << buff.substr(buff.length()-2, buff.length()); + ss << ":"; + + buffstream.str(""); + buffstream.clear(); + buffstream << "00"; + buffstream << std::dec << (rawsec / 600) % 60; + buff = buffstream.str(); + ss << buff.substr(buff.length() - 2, buff.length()); + ss << ":"; + + buffstream.str(""); + buffstream.clear(); + buffstream << "00"; + buffstream << std::dec << (rawsec / 10) % 60; + buff = buffstream.str(); + ss << buff.substr(buff.length() - 2, buff.length()); + ss << "\n"; + + return ss.str(); } // toString /** @@ -99,7 +117,7 @@ std::string BLEEddystoneTLM::toString() { */ void BLEEddystoneTLM::setData(std::string data) { if (data.length() != sizeof(m_eddystoneData)) { - log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData)); + ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData)); return; } memcpy(&m_eddystoneData, data.data(), data.length()); diff --git a/libraries/BLE/src/BLEEddystoneTLM.h b/libraries/BLE/src/BLEEddystoneTLM.h old mode 100644 new mode 100755 diff --git a/libraries/BLE/src/BLEEddystoneURL.cpp b/libraries/BLE/src/BLEEddystoneURL.cpp old mode 100644 new mode 100755 index 19a56b28b79..af3b674cbc8 --- a/libraries/BLE/src/BLEEddystoneURL.cpp +++ b/libraries/BLE/src/BLEEddystoneURL.cpp @@ -7,7 +7,7 @@ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include -#include "esp32-hal-log.h" +#include #include "BLEEddystoneURL.h" static const char LOG_TAG[] = "BLEEddystoneURL"; @@ -118,7 +118,7 @@ std::string BLEEddystoneURL::getDecodedURL() { */ void BLEEddystoneURL::setData(std::string data) { if (data.length() > sizeof(m_eddystoneData)) { - log_e("Unable to set the data ... length passed in was %d and max expected %d", data.length(), sizeof(m_eddystoneData)); + ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and max expected %d", data.length(), sizeof(m_eddystoneData)); return; } memset(&m_eddystoneData, 0, sizeof(m_eddystoneData)); @@ -136,7 +136,7 @@ void BLEEddystoneURL::setPower(int8_t advertisedTxPower) { void BLEEddystoneURL::setURL(std::string url) { if (url.length() > sizeof(m_eddystoneData.url)) { - log_e("Unable to set the url ... length passed in was %d and max expected %d", url.length(), sizeof(m_eddystoneData.url)); + ESP_LOGE(LOG_TAG, "Unable to set the url ... length passed in was %d and max expected %d", url.length(), sizeof(m_eddystoneData.url)); return; } memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); diff --git a/libraries/BLE/src/BLEEddystoneURL.h b/libraries/BLE/src/BLEEddystoneURL.h old mode 100644 new mode 100755 diff --git a/libraries/BLE/src/BLEExceptions.cpp b/libraries/BLE/src/BLEExceptions.cpp index 549e4425bd8..b6adfd82d8c 100644 --- a/libraries/BLE/src/BLEExceptions.cpp +++ b/libraries/BLE/src/BLEExceptions.cpp @@ -5,5 +5,5 @@ * Author: kolban */ -//#include "BLEExceptions.h" +#include "BLEExceptions.h" diff --git a/libraries/BLE/src/BLEHIDDevice.cpp b/libraries/BLE/src/BLEHIDDevice.cpp index 69e18be7a5f..46770b74a6a 100644 --- a/libraries/BLE/src/BLEHIDDevice.cpp +++ b/libraries/BLE/src/BLEHIDDevice.cpp @@ -194,6 +194,7 @@ BLECharacteristic* BLEHIDDevice::protocolMode() { void BLEHIDDevice::setBatteryLevel(uint8_t level) { m_batteryLevelCharacteristic->setValue(&level, 1); + m_batteryLevelCharacteristic->notify(); } /* * @brief Returns battery level characteristic diff --git a/libraries/BLE/src/BLERemoteCharacteristic.cpp b/libraries/BLE/src/BLERemoteCharacteristic.cpp index 6a5413893a1..ef16da7b908 100644 --- a/libraries/BLE/src/BLERemoteCharacteristic.cpp +++ b/libraries/BLE/src/BLERemoteCharacteristic.cpp @@ -14,11 +14,18 @@ #include #include -//#include "BLEExceptions.h" +#include "BLEExceptions.h" #include "BLEUtils.h" #include "GeneralUtils.h" #include "BLERemoteDescriptor.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLERemoteCharacteristic"; // The logging tag for this class. +#endif + /** @@ -33,17 +40,15 @@ BLERemoteCharacteristic::BLERemoteCharacteristic( BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService) { - log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str()); m_handle = handle; m_uuid = uuid; m_charProp = charProp; m_pRemoteService = pRemoteService; m_notifyCallback = nullptr; - m_rawData = nullptr; - m_auth = ESP_GATT_AUTH_REQ_NONE; retrieveDescriptors(); // Get the descriptors for this characteristic - log_v("<< BLERemoteCharacteristic"); + ESP_LOGD(LOG_TAG, "<< BLERemoteCharacteristic"); } // BLERemoteCharacteristic @@ -52,6 +57,7 @@ BLERemoteCharacteristic::BLERemoteCharacteristic( */ BLERemoteCharacteristic::~BLERemoteCharacteristic() { removeDescriptors(); // Release resources for any descriptor information we may have allocated. + if(m_rawData != nullptr) free(m_rawData); } // ~BLERemoteCharacteristic @@ -161,7 +167,7 @@ void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, case ESP_GATTC_NOTIFY_EVT: { if (evtParam->notify.handle != getHandle()) break; if (m_notifyCallback != nullptr) { - log_d("Invoking callback for notification on characteristic %s", toString().c_str()); + ESP_LOGD(LOG_TAG, "Invoking callback for notification on characteristic %s", toString().c_str()); m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify); } // End we have a callback function ... break; @@ -248,7 +254,7 @@ void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, * @brief Populate the descriptors (if any) for this characteristic. */ void BLERemoteCharacteristic::retrieveDescriptors() { - log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); removeDescriptors(); // Remove any existing descriptors. @@ -257,7 +263,7 @@ void BLERemoteCharacteristic::retrieveDescriptors() { uint16_t offset = 0; esp_gattc_descr_elem_t result; while(true) { - uint16_t count = 10; + uint16_t count = 1; esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr( getRemoteService()->getClient()->getGattcIf(), getRemoteService()->getClient()->getConnId(), @@ -267,18 +273,18 @@ void BLERemoteCharacteristic::retrieveDescriptors() { offset ); - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. + if (status == ESP_GATT_INVALID_OFFSET || status == ESP_GATT_NOT_FOUND) { // We have reached the end of the entries. break; } if (status != ESP_GATT_OK) { - log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str()); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str()); break; } if (count == 0) break; - log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str()); + ESP_LOGD(LOG_TAG, "Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str()); // We now have a new characteristic ... let us add that to our set of known characteristics BLERemoteDescriptor* pNewRemoteDescriptor = new BLERemoteDescriptor( @@ -292,7 +298,7 @@ void BLERemoteCharacteristic::retrieveDescriptors() { offset++; } // while true //m_haveCharacteristics = true; // Remember that we have received the characteristics. - log_v("<< retrieveDescriptors(): Found %d descriptors.", offset); + ESP_LOGD(LOG_TAG, "<< retrieveDescriptors(): Found %d descriptors.", offset); } // getDescriptors @@ -309,8 +315,8 @@ std::map* BLERemoteCharacteristic::getDescrip * @return The handle for this characteristic. */ uint16_t BLERemoteCharacteristic::getHandle() { - //log_v(">> getHandle: Characteristic: %s", getUUID().toString().c_str()); - //log_v("<< getHandle: %d 0x%.2x", m_handle, m_handle); + //ESP_LOGD(LOG_TAG, ">> getHandle: Characteristic: %s", getUUID().toString().c_str()); + //ESP_LOGD(LOG_TAG, "<< getHandle: %d 0x%.2x", m_handle, m_handle); return m_handle; } // getHandle @@ -321,15 +327,15 @@ uint16_t BLERemoteCharacteristic::getHandle() { * @return The Remote descriptor (if present) or null if not present. */ BLERemoteDescriptor* BLERemoteCharacteristic::getDescriptor(BLEUUID uuid) { - log_v(">> getDescriptor: uuid: %s", uuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> getDescriptor: uuid: %s", uuid.toString().c_str()); std::string v = uuid.toString(); for (auto &myPair : m_descriptorMap) { if (myPair.first == v) { - log_v("<< getDescriptor: found"); + ESP_LOGD(LOG_TAG, "<< getDescriptor: found"); return myPair.second; } } - log_v("<< getDescriptor: Not found"); + ESP_LOGD(LOG_TAG, "<< getDescriptor: Not found"); return nullptr; } // getDescriptor @@ -390,29 +396,18 @@ uint8_t BLERemoteCharacteristic::readUInt8() { return 0; } // readUInt8 -/** - * @brief Read a float value. - * @return the float value. - */ -float BLERemoteCharacteristic::readFloat() { - std::string value = readValue(); - if (value.length() >= 4) { - return *(float*)(value.data()); - } - return 0.0; -} // readFloat /** * @brief Read the value of the remote characteristic. * @return The value of the remote characteristic. */ std::string BLERemoteCharacteristic::readValue() { - log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle()); + ESP_LOGD(LOG_TAG, ">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle()); // Check to see that we are connected. if (!getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return std::string(); + ESP_LOGE(LOG_TAG, "Disconnected"); + throw BLEDisconnectedException(); } m_semaphoreReadCharEvt.take("readValue"); @@ -424,10 +419,10 @@ std::string BLERemoteCharacteristic::readValue() { m_pRemoteService->getClient()->getGattcIf(), m_pRemoteService->getClient()->getConnId(), // The connection ID to the BLE server getHandle(), // The handle of this characteristic - m_auth); // Security + ESP_GATT_AUTH_REQ_NONE); // Security if (errRc != ESP_OK) { - log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return ""; } @@ -435,7 +430,7 @@ std::string BLERemoteCharacteristic::readValue() { // in m_value will contain our data. m_semaphoreReadCharEvt.wait("readValue"); - log_v("<< readValue(): length: %d", m_value.length()); + ESP_LOGD(LOG_TAG, "<< readValue(): length: %d", m_value.length()); return m_value; } // readValue @@ -447,7 +442,7 @@ std::string BLERemoteCharacteristic::readValue() { * @return N/A. */ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, bool notifications) { - log_v(">> registerForNotify(): %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> registerForNotify(): %s", toString().c_str()); m_notifyCallback = notifyCallback; // Save the notification callback. @@ -461,13 +456,14 @@ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } uint8_t val[] = {0x01, 0x00}; if(!notifications) val[0] = 0x02; BLERemoteDescriptor* desc = getDescriptor(BLEUUID((uint16_t)0x2902)); - desc->writeValue(val, 2); + if(desc != nullptr) + desc->writeValue(val, 2); } // End Register else { // If we weren't passed a callback function, then this is an unregistration. esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify( @@ -477,17 +473,18 @@ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } uint8_t val[] = {0x00, 0x00}; BLERemoteDescriptor* desc = getDescriptor((uint16_t)0x2902); - desc->writeValue(val, 2); + if(desc != nullptr) + desc->writeValue(val, 2); } // End Unregister m_semaphoreRegForNotifyEvt.wait("registerForNotify"); - log_v("<< registerForNotify()"); + ESP_LOGD(LOG_TAG, "<< registerForNotify()"); } // registerForNotify @@ -513,16 +510,11 @@ void BLERemoteCharacteristic::removeDescriptors() { * @return a String representation. */ std::string BLERemoteCharacteristic::toString() { - std::string res = "Characteristic: uuid: " + m_uuid.toString(); - char val[6]; - res += ", handle: "; - snprintf(val, sizeof(val), "%d", getHandle()); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", getHandle()); - res += val; - res += ", props: " + BLEUtils::characteristicPropertiesToString(m_charProp); - return res; + std::ostringstream ss; + ss << "Characteristic: uuid: " << m_uuid.toString() << + ", handle: " << getHandle() << " 0x" << std::hex << getHandle() << + ", props: " << BLEUtils::characteristicPropertiesToString(m_charProp); + return ss.str(); } // toString @@ -530,10 +522,10 @@ std::string BLERemoteCharacteristic::toString() { * @brief Write the new value for the characteristic. * @param [in] newValue The new value to write. * @param [in] response Do we expect a response? - * @return N/A. + * @return false if not connected or cant perform write for some reason. */ -void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { - writeValue((uint8_t*)newValue.c_str(), strlen(newValue.c_str()), response); +bool BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { + return writeValue((uint8_t*)newValue.c_str(), strlen(newValue.c_str()), response); } // writeValue @@ -543,10 +535,10 @@ void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { * This is a convenience function. Many BLE characteristics are a single byte of data. * @param [in] newValue The new byte value to write. * @param [in] response Whether we require a response from the write. - * @return N/A. + * @return false if not connected or cant perform write for some reason. */ -void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { - writeValue(&newValue, 1, response); +bool BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { + return writeValue(&newValue, 1, response); } // writeValue @@ -555,15 +547,16 @@ void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { * @param [in] data A pointer to a data buffer. * @param [in] length The length of the data in the data buffer. * @param [in] response Whether we require a response from the write. + * @return false if not connected or cant perform write for some reason. */ -void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) { +bool BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) { // writeValue(std::string((char*)data, length), response); - log_v(">> writeValue(), length: %d", length); + ESP_LOGD(LOG_TAG, ">> writeValue(), length: %d", length); // Check to see that we are connected. if (!getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return; + ESP_LOGE(LOG_TAG, "Disconnected"); + return false; } m_semaphoreWriteCharEvt.take("writeValue"); @@ -575,17 +568,18 @@ void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool resp length, data, response?ESP_GATT_WRITE_TYPE_RSP:ESP_GATT_WRITE_TYPE_NO_RSP, - m_auth + ESP_GATT_AUTH_REQ_NONE ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; + ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + return false; } m_semaphoreWriteCharEvt.wait("writeValue"); - log_v("<< writeValue"); + ESP_LOGD(LOG_TAG, "<< writeValue"); + return true; } // writeValue /** @@ -596,12 +590,4 @@ uint8_t* BLERemoteCharacteristic::readRawData() { return m_rawData; } -/** - * @brief Set authentication request type for characteristic - * @param [in] auth Authentication request type. - */ -void BLERemoteCharacteristic::setAuth(esp_gatt_auth_req_t auth) { - m_auth = auth; -} - #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteCharacteristic.h b/libraries/BLE/src/BLERemoteCharacteristic.h index 5ba0f2c6381..910b11a456e 100644 --- a/libraries/BLE/src/BLERemoteCharacteristic.h +++ b/libraries/BLE/src/BLERemoteCharacteristic.h @@ -45,14 +45,13 @@ class BLERemoteCharacteristic { uint8_t readUInt8(); uint16_t readUInt16(); uint32_t readUInt32(); - float readFloat(); void registerForNotify(notify_callback _callback, bool notifications = true); - void writeValue(uint8_t* data, size_t length, bool response = false); - void writeValue(std::string newValue, bool response = false); - void writeValue(uint8_t newValue, bool response = false); + bool writeValue(uint8_t* data, size_t length, bool response = false); + bool writeValue(std::string newValue, bool response = false); + bool writeValue(uint8_t newValue, bool response = false); std::string toString(); uint8_t* readRawData(); - void setAuth(esp_gatt_auth_req_t auth); + BLERemoteService* getRemoteService(); private: BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService); @@ -63,22 +62,20 @@ class BLERemoteCharacteristic { // Private member functions void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam); - BLERemoteService* getRemoteService(); void removeDescriptors(); void retrieveDescriptors(); // Private properties BLEUUID m_uuid; esp_gatt_char_prop_t m_charProp; - esp_gatt_auth_req_t m_auth; uint16_t m_handle; BLERemoteService* m_pRemoteService; FreeRTOS::Semaphore m_semaphoreReadCharEvt = FreeRTOS::Semaphore("ReadCharEvt"); FreeRTOS::Semaphore m_semaphoreRegForNotifyEvt = FreeRTOS::Semaphore("RegForNotifyEvt"); FreeRTOS::Semaphore m_semaphoreWriteCharEvt = FreeRTOS::Semaphore("WriteCharEvt"); std::string m_value; - uint8_t *m_rawData; - notify_callback m_notifyCallback; + uint8_t *m_rawData = nullptr; + notify_callback m_notifyCallback = nullptr; // We maintain a map of descriptors owned by this characteristic keyed by a string representation of the UUID. std::map m_descriptorMap; diff --git a/libraries/BLE/src/BLERemoteDescriptor.cpp b/libraries/BLE/src/BLERemoteDescriptor.cpp index ad506aae9b3..96a8a5779a2 100644 --- a/libraries/BLE/src/BLERemoteDescriptor.cpp +++ b/libraries/BLE/src/BLERemoteDescriptor.cpp @@ -9,7 +9,16 @@ #include #include "BLERemoteDescriptor.h" #include "GeneralUtils.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLERemoteDescriptor"; +#endif + + + BLERemoteDescriptor::BLERemoteDescriptor( uint16_t handle, @@ -19,7 +28,6 @@ BLERemoteDescriptor::BLERemoteDescriptor( m_handle = handle; m_uuid = uuid; m_pRemoteCharacteristic = pRemoteCharacteristic; - m_auth = ESP_GATT_AUTH_REQ_NONE; } @@ -51,12 +59,12 @@ BLEUUID BLERemoteDescriptor::getUUID() { std::string BLERemoteDescriptor::readValue() { - log_v(">> readValue: %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> readValue: %s", toString().c_str()); // Check to see that we are connected. if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return std::string(); + ESP_LOGE(LOG_TAG, "Disconnected"); + throw BLEDisconnectedException(); } m_semaphoreReadDescrEvt.take("readValue"); @@ -66,10 +74,10 @@ std::string BLERemoteDescriptor::readValue() { m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), // The connection ID to the BLE server getHandle(), // The handle of this characteristic - m_auth); // Security + ESP_GATT_AUTH_REQ_NONE); // Security if (errRc != ESP_OK) { - log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return ""; } @@ -77,7 +85,7 @@ std::string BLERemoteDescriptor::readValue() { // in m_value will contain our data. m_semaphoreReadDescrEvt.wait("readValue"); - log_v("<< readValue(): length: %d", m_value.length()); + ESP_LOGD(LOG_TAG, "<< readValue(): length: %d", m_value.length()); return m_value; } // readValue @@ -114,12 +122,9 @@ uint32_t BLERemoteDescriptor::readUInt32() { * @retun A string representation of this BLE Remote Descriptor. */ std::string BLERemoteDescriptor::toString() { - char val[6]; - snprintf(val, sizeof(val), "%d", getHandle()); - std::string res = "handle: "; - res += val; - res += ", uuid: " + getUUID().toString(); - return res; + std::stringstream ss; + ss << "handle: " << getHandle() << ", uuid: " << getUUID().toString(); + return ss.str(); } // toString @@ -130,11 +135,11 @@ std::string BLERemoteDescriptor::toString() { * @param [in] response True if we expect a response. */ void BLERemoteDescriptor::writeValue(uint8_t* data, size_t length, bool response) { - log_v(">> writeValue: %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> writeValue: %s", toString().c_str()); // Check to see that we are connected. if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return; + ESP_LOGE(LOG_TAG, "Disconnected"); + throw BLEDisconnectedException(); } esp_err_t errRc = ::esp_ble_gattc_write_char_descr( @@ -144,12 +149,12 @@ void BLERemoteDescriptor::writeValue(uint8_t* data, size_t length, bool response length, // Data length data, // Data response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, - m_auth + ESP_GATT_AUTH_REQ_NONE ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_write_char_descr: %d", errRc); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char_descr: %d", errRc); } - log_v("<< writeValue"); + ESP_LOGD(LOG_TAG, "<< writeValue"); } // writeValue @@ -172,12 +177,5 @@ void BLERemoteDescriptor::writeValue(uint8_t newValue, bool response) { writeValue(&newValue, 1, response); } // writeValue -/** - * @brief Set authentication request type for characteristic - * @param [in] auth Authentication request type. - */ -void BLERemoteDescriptor::setAuth(esp_gatt_auth_req_t auth) { - m_auth = auth; -} #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteDescriptor.h b/libraries/BLE/src/BLERemoteDescriptor.h index 29efe573bfe..7bbc48f12d9 100644 --- a/libraries/BLE/src/BLERemoteDescriptor.h +++ b/libraries/BLE/src/BLERemoteDescriptor.h @@ -34,7 +34,6 @@ class BLERemoteDescriptor { void writeValue(uint8_t* data, size_t length, bool response = false); void writeValue(std::string newValue, bool response = false); void writeValue(uint8_t newValue, bool response = false); - void setAuth(esp_gatt_auth_req_t auth); private: @@ -49,7 +48,6 @@ class BLERemoteDescriptor { std::string m_value; // Last received value of the descriptor. BLERemoteCharacteristic* m_pRemoteCharacteristic; // Reference to the Remote characteristic of which this descriptor is associated. FreeRTOS::Semaphore m_semaphoreReadDescrEvt = FreeRTOS::Semaphore("ReadDescrEvt"); - esp_gatt_auth_req_t m_auth; }; diff --git a/libraries/BLE/src/BLERemoteService.cpp b/libraries/BLE/src/BLERemoteService.cpp index 278e9c1cab4..91089eab480 100644 --- a/libraries/BLE/src/BLERemoteService.cpp +++ b/libraries/BLE/src/BLERemoteService.cpp @@ -12,9 +12,15 @@ #include "BLEUtils.h" #include "GeneralUtils.h" #include +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLERemoteService"; +#endif + -#pragma GCC diagnostic warning "-Wunused-but-set-parameter" BLERemoteService::BLERemoteService( esp_gatt_id_t srvcId, @@ -23,7 +29,7 @@ BLERemoteService::BLERemoteService( uint16_t endHandle ) { - log_v(">> BLERemoteService()"); + ESP_LOGD(LOG_TAG, ">> BLERemoteService()"); m_srvcId = srvcId; m_pClient = pClient; m_uuid = BLEUUID(m_srvcId); @@ -31,7 +37,7 @@ BLERemoteService::BLERemoteService( m_startHandle = startHandle; m_endHandle = endHandle; - log_v("<< BLERemoteService()"); + ESP_LOGD(LOG_TAG, "<< BLERemoteService()"); } @@ -59,52 +65,6 @@ void BLERemoteService::gattClientEventHandler( esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) { switch (event) { - // - // ESP_GATTC_GET_CHAR_EVT - // - // get_char: - // - esp_gatt_status_t status - // - uin1t6_t conn_id - // - esp_gatt_srvc_id_t srvc_id - // - esp_gatt_id_t char_id - // - esp_gatt_char_prop_t char_prop - // - /* - case ESP_GATTC_GET_CHAR_EVT: { - // Is this event for this service? If yes, then the local srvc_id and the event srvc_id will be - // the same. - if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) { - break; - } - - // If the status is NOT OK then we have a problem and continue. - if (evtParam->get_char.status != ESP_GATT_OK) { - m_semaphoreGetCharEvt.give(); - break; - } - - // This is an indication that we now have the characteristic details for a characteristic owned - // by this service so remember it. - m_characteristicMap.insert(std::pair( - BLEUUID(evtParam->get_char.char_id.uuid).toString(), - new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this) )); - - - // Now that we have received a characteristic, lets ask for the next one. - esp_err_t errRc = ::esp_ble_gattc_get_characteristic( - m_pClient->getGattcIf(), - m_pClient->getConnId(), - &m_srvcId, - &evtParam->get_char.char_id); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - break; - } - - //m_semaphoreGetCharEvt.give(); - break; - } // ESP_GATTC_GET_CHAR_EVT -*/ default: break; } // switch @@ -159,14 +119,14 @@ BLERemoteCharacteristic* BLERemoteService::getCharacteristic(BLEUUID uuid) { * @return N/A */ void BLERemoteService::retrieveCharacteristics() { - log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> retrieveCharacteristics() for service: %s", getUUID().toString().c_str()); removeCharacteristics(); // Forget any previous characteristics. uint16_t offset = 0; esp_gattc_char_elem_t result; while (true) { - uint16_t count = 1; // only room for 1 result allocated, so go one by one + uint16_t count = 1; // this value is used as in parameter that allows to search max 10 chars with the same uuid esp_gatt_status_t status = ::esp_ble_gattc_get_all_char( getClient()->getGattcIf(), getClient()->getConnId(), @@ -177,12 +137,12 @@ void BLERemoteService::retrieveCharacteristics() { offset ); - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. + if (status == ESP_GATT_INVALID_OFFSET || status == ESP_GATT_NOT_FOUND) { // We have reached the end of the entries. break; } if (status != ESP_GATT_OK) { // If we got an error, end. - log_e("esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str()); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str()); break; } @@ -190,7 +150,7 @@ void BLERemoteService::retrieveCharacteristics() { break; } - log_d("Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str()); + ESP_LOGD(LOG_TAG, "Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str()); // We now have a new characteristic ... let us add that to our set of known characteristics BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic( @@ -206,8 +166,8 @@ void BLERemoteService::retrieveCharacteristics() { } // Loop forever (until we break inside the loop). m_haveCharacteristics = true; // Remember that we have received the characteristics. - log_v("<< getCharacteristics()"); -} // getCharacteristics + ESP_LOGD(LOG_TAG, "<< retrieveCharacteristics()"); +} // retrieveCharacteristics /** @@ -215,14 +175,14 @@ void BLERemoteService::retrieveCharacteristics() { * @return A map of all the characteristics of this service. */ std::map* BLERemoteService::getCharacteristics() { - log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> getCharacteristics() for service: %s", getUUID().toString().c_str()); // If is possible that we have not read the characteristics associated with the service so do that // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking // call and does not return until all the characteristics are available. if (!m_haveCharacteristics) { retrieveCharacteristics(); } - log_v("<< getCharacteristics() for service: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, "<< getCharacteristics() for service: %s", getUUID().toString().c_str()); return &m_characteristicMap; } // getCharacteristics @@ -231,12 +191,14 @@ std::map* BLERemoteService::getCharacteri * @return A map of all the characteristics of this service. */ std::map* BLERemoteService::getCharacteristicsByHandle() { + ESP_LOGD(LOG_TAG, ">> getCharacteristicsByHandle() for service: %s", getUUID().toString().c_str()); // If is possible that we have not read the characteristics associated with the service so do that // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking // call and does not return until all the characteristics are available. if (!m_haveCharacteristics) { retrieveCharacteristics(); } + ESP_LOGD(LOG_TAG, "<< getCharacteristicsByHandle() for service: %s", getUUID().toString().c_str()); return &m_characteristicMapByHandle; } // getCharacteristicsByHandle @@ -244,7 +206,8 @@ std::map* BLERemoteService::getCharacteristi * @brief This function is designed to get characteristics map when we have multiple characteristics with the same UUID */ void BLERemoteService::getCharacteristics(std::map* pCharacteristicMap) { - pCharacteristicMap = &m_characteristicMapByHandle; +#pragma GCC diagnostic ignored "-Wunused-but-set-parameter" + *pCharacteristicMap = m_characteristicMapByHandle; } // Get the characteristics map. /** @@ -272,8 +235,8 @@ uint16_t BLERemoteService::getStartHandle() { uint16_t BLERemoteService::getHandle() { - log_v(">> getHandle: service: %s", getUUID().toString().c_str()); - log_v("<< getHandle: %d 0x%.2x", getStartHandle(), getStartHandle()); + ESP_LOGD(LOG_TAG, ">> getHandle: service: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, "<< getHandle: %d 0x%.2x", getStartHandle(), getStartHandle()); return getStartHandle(); } // getHandle @@ -286,9 +249,9 @@ BLEUUID BLERemoteService::getUUID() { * @brief Read the value of a characteristic associated with this service. */ std::string BLERemoteService::getValue(BLEUUID characteristicUuid) { - log_v(">> readValue: uuid: %s", characteristicUuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> readValue: uuid: %s", characteristicUuid.toString().c_str()); std::string ret = getCharacteristic(characteristicUuid)->readValue(); - log_v("<< readValue"); + ESP_LOGD(LOG_TAG, "<< readValue"); return ret; } // readValue @@ -302,10 +265,6 @@ std::string BLERemoteService::getValue(BLEUUID characteristicUuid) { * @return N/A. */ void BLERemoteService::removeCharacteristics() { - for (auto &myPair : m_characteristicMap) { - delete myPair.second; - //m_characteristicMap.erase(myPair.first); // Should be no need to delete as it will be deleted by the clear - } m_characteristicMap.clear(); // Clear the map for (auto &myPair : m_characteristicMapByHandle) { delete myPair.second; @@ -321,9 +280,9 @@ void BLERemoteService::removeCharacteristics() { * @throws BLEUuidNotFound */ void BLERemoteService::setValue(BLEUUID characteristicUuid, std::string value) { - log_v(">> setValue: uuid: %s", characteristicUuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setValue: uuid: %s", characteristicUuid.toString().c_str()); getCharacteristic(characteristicUuid)->writeValue(value); - log_v("<< setValue"); + ESP_LOGD(LOG_TAG, "<< setValue"); } // setValue @@ -332,25 +291,15 @@ void BLERemoteService::setValue(BLEUUID characteristicUuid, std::string value) { * @return A string representation of this remote service. */ std::string BLERemoteService::toString() { - std::string res = "Service: uuid: " + m_uuid.toString(); - char val[6]; - res += ", start_handle: "; - snprintf(val, sizeof(val), "%d", m_startHandle); - res += val; - snprintf(val, sizeof(val), "%04x", m_startHandle); - res += " 0x"; - res += val; - res += ", end_handle: "; - snprintf(val, sizeof(val), "%d", m_endHandle); - res += val; - snprintf(val, sizeof(val), "%04x", m_endHandle); - res += " 0x"; - res += val; + std::ostringstream ss; + ss << "Service: uuid: " + m_uuid.toString(); + ss << ", start_handle: " << std::dec << m_startHandle << " 0x" << std::hex << m_startHandle << + ", end_handle: " << std::dec << m_endHandle << " 0x" << std::hex << m_endHandle; for (auto &myPair : m_characteristicMap) { - res += "\n" + myPair.second->toString(); + ss << "\n" << myPair.second->toString(); // myPair.second is the value } - return res; + return ss.str(); } // toString diff --git a/libraries/BLE/src/BLEScan.cpp b/libraries/BLE/src/BLEScan.cpp index cb28dd395a7..a96e6df66c3 100644 --- a/libraries/BLE/src/BLEScan.cpp +++ b/libraries/BLE/src/BLEScan.cpp @@ -16,7 +16,16 @@ #include "BLEScan.h" #include "BLEUtils.h" #include "GeneralUtils.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEScan"; +#endif + + + /** * Constructor @@ -66,7 +75,7 @@ void BLEScan::handleGAPEvent( // Event that indicates that the duration allowed for the search has completed or that we have been // asked to stop. case ESP_GAP_SEARCH_INQ_CMPL_EVT: { - log_w("ESP_GAP_SEARCH_INQ_CMPL_EVT"); + ESP_LOGW(LOG_TAG, "ESP_GAP_SEARCH_INQ_CMPL_EVT"); m_stopped = true; m_semaphoreScanEnd.give(); if (m_scanCompleteCB != nullptr) { @@ -94,15 +103,15 @@ void BLEScan::handleGAPEvent( } if (found && !m_wantDuplicates) { // If we found a previous entry AND we don't want duplicates, then we are done. - log_d("Ignoring %s, already seen it.", advertisedAddress.toString().c_str()); + ESP_LOGD(LOG_TAG, "Ignoring %s, already seen it.", advertisedAddress.toString().c_str()); vTaskDelay(1); // <--- allow to switch task in case we scan infinity and dont have new devices to report, or we are blocked here break; } // We now construct a model of the advertised device that we have just found for the first // time. - // ESP_LOG_BUFFER_HEXDUMP((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len, ESP_LOG_DEBUG); - // log_w("bytes length: %d + %d, addr type: %d", param->scan_rst.adv_data_len, param->scan_rst.scan_rsp_len, param->scan_rst.ble_addr_type); + // ESP_LOG_BUFFER_HEXDUMP(LOG_TAG, (uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len, ESP_LOG_DEBUG); + // ESP_LOGW(LOG_TAG, "bytes length: %d + %d, addr type: %d", param->scan_rst.adv_data_len, param->scan_rst.scan_rsp_len, param->scan_rst.ble_addr_type); BLEAdvertisedDevice *advertisedDevice = new BLEAdvertisedDevice(); advertisedDevice->setAddress(advertisedAddress); advertisedDevice->setRSSI(param->scan_rst.rssi); @@ -116,6 +125,7 @@ void BLEScan::handleGAPEvent( } if (m_pAdvertisedDeviceCallbacks) { + m_pAdvertisedDeviceCallbacks->onResult(advertisedDevice); m_pAdvertisedDeviceCallbacks->onResult(*advertisedDevice); } if(found) @@ -192,7 +202,7 @@ void BLEScan::setWindow(uint16_t windowMSecs) { * @return True if scan started or false if there was an error. */ bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue) { - log_v(">> start(duration=%d)", duration); + ESP_LOGD(LOG_TAG, ">> start(duration=%d)", duration); m_semaphoreScanEnd.take(std::string("start")); m_scanCompleteCB = scanCompleteCB; // Save the callback to be invoked when the scan completes. @@ -209,7 +219,7 @@ bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), b esp_err_t errRc = ::esp_ble_gap_set_scan_params(&m_scan_params); if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_scan_params: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_set_scan_params: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); m_semaphoreScanEnd.give(); return false; } @@ -217,14 +227,14 @@ bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), b errRc = ::esp_ble_gap_start_scanning(duration); if (errRc != ESP_OK) { - log_e("esp_ble_gap_start_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_start_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); m_semaphoreScanEnd.give(); return false; } m_stopped = false; - log_v("<< start()"); + ESP_LOGD(LOG_TAG, "<< start()"); return true; } // start @@ -247,7 +257,7 @@ BLEScanResults BLEScan::start(uint32_t duration, bool is_continue) { * @return N/A. */ void BLEScan::stop() { - log_v(">> stop()"); + ESP_LOGD(LOG_TAG, ">> stop()"); esp_err_t errRc = ::esp_ble_gap_stop_scanning(); @@ -255,16 +265,16 @@ void BLEScan::stop() { m_semaphoreScanEnd.give(); if (errRc != ESP_OK) { - log_e("esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); return; } - log_v("<< stop()"); + ESP_LOGD(LOG_TAG, "<< stop()"); } // stop // delete peer device from cache after disconnecting, it is required in case we are connecting to devices with not public address void BLEScan::erase(BLEAddress address) { - log_i("erase device: %s", address.toString().c_str()); + ESP_LOGI(LOG_TAG, "erase device: %s", address.toString().c_str()); BLEAdvertisedDevice *advertisedDevice = m_scanResults.m_vectorAdvertisedDevices.find(address.toString())->second; m_scanResults.m_vectorAdvertisedDevices.erase(address.toString()); delete advertisedDevice; @@ -275,9 +285,9 @@ void BLEScan::erase(BLEAddress address) { * @brief Dump the scan results to the log. */ void BLEScanResults::dump() { - log_v(">> Dump scan results:"); + ESP_LOGD(LOG_TAG, ">> Dump scan results:"); for (int i=0; i #include +#include #include "GeneralUtils.h" #include "BLEDevice.h" #include "BLEServer.h" @@ -17,7 +18,16 @@ #include #include #include +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEServer"; +#endif + + + /** * @brief Construct a %BLE Server @@ -64,12 +74,12 @@ BLEService* BLEServer::createService(const char* uuid) { * @return A reference to the new service object. */ BLEService* BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t inst_id) { - log_v(">> createService - %s", uuid.toString().c_str()); + ESP_LOGD(LOG_TAG, ">> createService - %s", uuid.toString().c_str()); m_semaphoreCreateEvt.take("createService"); // Check that a service with the supplied UUID does not already exist. if (m_serviceMap.getByUUID(uuid) != nullptr) { - log_w("<< Attempt to create a new service with uuid %s but a service with that UUID already exists.", + ESP_LOGW(LOG_TAG, "<< Attempt to create a new service with uuid %s but a service with that UUID already exists.", uuid.toString().c_str()); } @@ -80,7 +90,7 @@ BLEService* BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t m_semaphoreCreateEvt.wait("createService"); - log_v("<< createService"); + ESP_LOGD(LOG_TAG, "<< createService"); return pService; } // createService @@ -140,7 +150,7 @@ uint16_t BLEServer::getGattsIf() { * */ void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { - log_v(">> handleGATTServerEvent: %s", + ESP_LOGD(LOG_TAG, ">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); switch(event) { @@ -202,19 +212,13 @@ void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t // If we receive a disconnect event then invoke the callback for disconnects (if one is present). // we also want to start advertising again. case ESP_GATTS_DISCONNECT_EVT: { + m_connectedCount--; // Decrement the number of connected devices count. if (m_pServerCallbacks != nullptr) { // If we have callbacks, call now. m_pServerCallbacks->onDisconnect(this); } - if(m_connId == ESP_GATT_IF_NONE) { - return; - } - - // only decrement if connection is found in map and removed - // sometimes this event triggers w/o a valid connection - if(removePeerDevice(param->disconnect.conn_id, false)) { - m_connectedCount--; // Decrement the number of connected devices count. - } - break; + startAdvertising(); //- do this with some delay from the loop() + removePeerDevice(param->disconnect.conn_id, false); + break; } // ESP_GATTS_DISCONNECT_EVT @@ -274,7 +278,7 @@ void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t // Invoke the handler for every Service we have. m_serviceMap.handleGATTServerEvent(event, gatts_if, param); - log_v("<< handleGATTServerEvent"); + ESP_LOGD(LOG_TAG, "<< handleGATTServerEvent"); } // handleGATTServerEvent @@ -284,11 +288,11 @@ void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t * @return N/A */ void BLEServer::registerApp(uint16_t m_appId) { - log_v(">> registerApp - %d", m_appId); + ESP_LOGD(LOG_TAG, ">> registerApp - %d", m_appId); m_semaphoreRegisterAppEvt.take("registerApp"); // Take the mutex, will be released by ESP_GATTS_REG_EVT event. ::esp_ble_gatts_app_register(m_appId); m_semaphoreRegisterAppEvt.wait("registerApp"); - log_v("<< registerApp"); + ESP_LOGD(LOG_TAG, "<< registerApp"); } // registerApp @@ -321,9 +325,9 @@ void BLEServer::removeService(BLEService* service) { * retrieving the advertising object and invoking start upon it. */ void BLEServer::startAdvertising() { - log_v(">> startAdvertising"); + ESP_LOGD(LOG_TAG, ">> startAdvertising"); BLEDevice::startAdvertising(); - log_v("<< startAdvertising"); + ESP_LOGD(LOG_TAG, "<< startAdvertising"); } // startAdvertising /** @@ -341,34 +345,34 @@ bool BLEServer::connect(BLEAddress address) { 1 // direct connection ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return false; } uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. - log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); + ESP_LOGD(LOG_TAG, "<< connect(), rc=%d", rc==ESP_GATT_OK); return rc == ESP_GATT_OK; } // connect void BLEServerCallbacks::onConnect(BLEServer* pServer) { - log_d("BLEServerCallbacks", ">> onConnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onConnect()"); + ESP_LOGD("BLEServerCallbacks", ">> onConnect(): Default"); + ESP_LOGD("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + ESP_LOGD("BLEServerCallbacks", "<< onConnect()"); } // onConnect void BLEServerCallbacks::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) { - log_d("BLEServerCallbacks", ">> onConnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onConnect()"); + ESP_LOGD("BLEServerCallbacks", ">> onConnect(): Default"); + ESP_LOGD("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + ESP_LOGD("BLEServerCallbacks", "<< onConnect()"); } // onConnect void BLEServerCallbacks::onDisconnect(BLEServer* pServer) { - log_d("BLEServerCallbacks", ">> onDisconnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onDisconnect()"); + ESP_LOGD("BLEServerCallbacks", ">> onDisconnect(): Default"); + ESP_LOGD("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); + ESP_LOGD("BLEServerCallbacks", "<< onDisconnect()"); } // onDisconnect /* multi connect support */ @@ -401,8 +405,8 @@ void BLEServer::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { m_connectedServersMap.insert(std::pair(conn_id, status)); } -bool BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { - return m_connectedServersMap.erase(conn_id) > 0; +void BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { + m_connectedServersMap.erase(conn_id); } /* multi connect support */ @@ -419,7 +423,7 @@ void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, esp_ble_gap_update_conn_params(&conn_params); } -void BLEServer::disconnect(uint16_t connId) { +void BLEServer::disconnect(uint16_t connId){ esp_ble_gatts_close(m_gatts_if, connId); } diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h old mode 100644 new mode 100755 index c97f093eff2..d2f8038d268 --- a/libraries/BLE/src/BLEServer.h +++ b/libraries/BLE/src/BLEServer.h @@ -79,7 +79,7 @@ class BLEServer { /* multi connection support */ std::map getPeerDevices(bool client); void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); - bool removePeerDevice(uint16_t conn_id, bool client); + void removePeerDevice(uint16_t conn_id, bool client); BLEServer* getServerByConnId(uint16_t conn_id); void updatePeerMTU(uint16_t connId, uint16_t mtu); uint16_t getPeerMTU(uint16_t conn_id); diff --git a/libraries/BLE/src/BLEService.cpp b/libraries/BLE/src/BLEService.cpp index 3ea6141c0d4..3034cf18c70 100644 --- a/libraries/BLE/src/BLEService.cpp +++ b/libraries/BLE/src/BLEService.cpp @@ -20,7 +20,14 @@ #include "BLEService.h" #include "BLEUtils.h" #include "GeneralUtils.h" + +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEService"; // Tag for logging. +#endif #define NULL_HANDLE (0xffff) @@ -57,7 +64,7 @@ BLEService::BLEService(BLEUUID uuid, uint16_t numHandles) { */ void BLEService::executeCreate(BLEServer* pServer) { - log_v(">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str()); m_pServer = pServer; m_semaphoreCreateEvt.take("executeCreate"); // Take the mutex and release at event ESP_GATTS_CREATE_EVT @@ -68,12 +75,12 @@ void BLEService::executeCreate(BLEServer* pServer) { esp_err_t errRc = ::esp_ble_gatts_create_service(getServer()->getGattsIf(), &srvc_id, m_numHandles); // The maximum number of handles associated with the service. if (errRc != ESP_OK) { - log_e("esp_ble_gatts_create_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_create_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreCreateEvt.wait("executeCreate"); - log_v("<< executeCreate"); + ESP_LOGD(LOG_TAG, "<< executeCreate"); } // executeCreate @@ -84,18 +91,18 @@ void BLEService::executeCreate(BLEServer* pServer) { */ void BLEService::executeDelete() { - log_v(">> executeDelete()"); + ESP_LOGD(LOG_TAG, ">> executeDelete()"); m_semaphoreDeleteEvt.take("executeDelete"); // Take the mutex and release at event ESP_GATTS_DELETE_EVT esp_err_t errRc = ::esp_ble_gatts_delete_service(getHandle()); if (errRc != ESP_OK) { - log_e("esp_ble_gatts_delete_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_delete_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreDeleteEvt.wait("executeDelete"); - log_v("<< executeDelete"); + ESP_LOGD(LOG_TAG, "<< executeDelete"); } // executeDelete @@ -104,10 +111,10 @@ void BLEService::executeDelete() { * @return N/A. */ void BLEService::dump() { - log_d("Service: uuid:%s, handle: 0x%.2x", + ESP_LOGD(LOG_TAG, "Service: uuid:%s, handle: 0x%.2x", m_uuid.toString().c_str(), m_handle); - log_d("Characteristics:\n%s", m_characteristicMap.toString().c_str()); + ESP_LOGD(LOG_TAG, "Characteristics:\n%s", m_characteristicMap.toString().c_str()); } // dump @@ -131,9 +138,9 @@ void BLEService::start() { // We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event // obtained as a result of calling esp_ble_gatts_create_service(). // - log_v(">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str()); if (m_handle == NULL_HANDLE) { - log_e("<< !!! We attempted to start a service but don't know its handle!"); + ESP_LOGE(LOG_TAG, "<< !!! We attempted to start a service but don't know its handle!"); return; } @@ -151,12 +158,12 @@ void BLEService::start() { esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle); if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreStartEvt.wait("start"); - log_v("<< start()"); + ESP_LOGD(LOG_TAG, "<< start()"); } // start @@ -167,9 +174,9 @@ void BLEService::stop() { // We ask the BLE runtime to start the service and then create each of the characteristics. // We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event // obtained as a result of calling esp_ble_gatts_create_service(). - log_v(">> stop(): Stopping service (esp_ble_gatts_stop_service): %s", toString().c_str()); + ESP_LOGD(LOG_TAG, ">> stop(): Stopping service (esp_ble_gatts_stop_service): %s", toString().c_str()); if (m_handle == NULL_HANDLE) { - log_e("<< !!! We attempted to stop a service but don't know its handle!"); + ESP_LOGE(LOG_TAG, "<< !!! We attempted to stop a service but don't know its handle!"); return; } @@ -177,12 +184,12 @@ void BLEService::stop() { esp_err_t errRc = ::esp_ble_gatts_stop_service(m_handle); if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_stop_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_stop_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreStopEvt.wait("stop"); - log_v("<< stop()"); + ESP_LOGD(LOG_TAG, "<< stop()"); } // start @@ -191,13 +198,13 @@ void BLEService::stop() { * @param [in] handle The handle associated with the service. */ void BLEService::setHandle(uint16_t handle) { - log_v(">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str()); + ESP_LOGD(LOG_TAG, ">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str()); if (m_handle != NULL_HANDLE) { - log_e("!!! Handle is already set %.2x", m_handle); + ESP_LOGE(LOG_TAG, "!!! Handle is already set %.2x", m_handle); return; } m_handle = handle; - log_v("<< setHandle"); + ESP_LOGD(LOG_TAG, "<< setHandle"); } // setHandle @@ -219,14 +226,14 @@ void BLEService::addCharacteristic(BLECharacteristic* pCharacteristic) { // BLECharacteristicMap class instance found in m_characteristicMap. We add the characteristic // to the map and then ask the service to add the characteristic at the BLE level (ESP-IDF). - log_v(">> addCharacteristic()"); - log_d("Adding characteristic: uuid=%s to service: %s", + ESP_LOGD(LOG_TAG, ">> addCharacteristic()"); + ESP_LOGD(LOG_TAG, "Adding characteristic: uuid=%s to service: %s", pCharacteristic->getUUID().toString().c_str(), toString().c_str()); // Check that we don't add the same characteristic twice. if (m_characteristicMap.getByUUID(pCharacteristic->getUUID()) != nullptr) { - log_w("<< Adding a new characteristic with the same UUID as a previous one"); + ESP_LOGW(LOG_TAG, "<< Adding a new characteristic with the same UUID as a previous one"); //return; } @@ -234,7 +241,7 @@ void BLEService::addCharacteristic(BLECharacteristic* pCharacteristic) { // but not by handle. The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT. m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID()); - log_v("<< addCharacteristic()"); + ESP_LOGD(LOG_TAG, "<< addCharacteristic()"); } // addCharacteristic @@ -280,7 +287,7 @@ void BLEService::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t if (m_handle == param->add_char.service_handle) { BLECharacteristic *pCharacteristic = getLastCreatedCharacteristic(); if (pCharacteristic == nullptr) { - log_e("Expected to find characteristic with UUID: %s, but didnt!", + ESP_LOGE(LOG_TAG, "Expected to find characteristic with UUID: %s, but didnt!", BLEUUID(param->add_char.char_uuid).toString().c_str()); dump(); break; @@ -381,12 +388,10 @@ BLECharacteristic* BLEService::getCharacteristic(BLEUUID uuid) { * @return A string representation of this service. */ std::string BLEService::toString() { - std::string res = "UUID: " + getUUID().toString(); - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", getHandle()); - res += ", handle: 0x"; - res += hex; - return res; + std::stringstream stringStream; + stringStream << "UUID: " << getUUID().toString() << + ", handle: 0x" << std::hex << std::setfill('0') << std::setw(2) << getHandle(); + return stringStream.str(); } // toString diff --git a/libraries/BLE/src/BLEServiceMap.cpp b/libraries/BLE/src/BLEServiceMap.cpp old mode 100644 new mode 100755 index a8a1f8e567c..cf4f75f4419 --- a/libraries/BLE/src/BLEServiceMap.cpp +++ b/libraries/BLE/src/BLEServiceMap.cpp @@ -6,7 +6,7 @@ */ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) -#include +#include #include #include "BLEService.h" @@ -73,15 +73,12 @@ void BLEServiceMap::setByHandle(uint16_t handle, BLEService* service) { * @return A string representation of the service map. */ std::string BLEServiceMap::toString() { - std::string res; - char hex[5]; + std::stringstream stringStream; + stringStream << std::hex << std::setfill('0'); for (auto &myPair: m_handleMap) { - res += "handle: 0x"; - snprintf(hex, sizeof(hex), "%04x", myPair.first); - res += hex; - res += ", uuid: " + myPair.second->getUUID().toString() + "\n"; + stringStream << "handle: 0x" << std::setw(2) << myPair.first << ", uuid: " + myPair.second->getUUID().toString() << "\n"; } - return res; + return stringStream.str(); } // toString void BLEServiceMap::handleGATTServerEvent( diff --git a/libraries/BLE/src/BLEUUID.cpp b/libraries/BLE/src/BLEUUID.cpp index 1a9473678b2..4ddf8fc27a0 100644 --- a/libraries/BLE/src/BLEUUID.cpp +++ b/libraries/BLE/src/BLEUUID.cpp @@ -13,7 +13,15 @@ #include #include #include "BLEUUID.h" + +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "BLEUUID"; +#endif + /** * @brief Copy memory from source to target but in reverse order. @@ -113,7 +121,7 @@ BLEUUID::BLEUUID(std::string value) { } } else { - log_e("ERROR: UUID value not 2, 4, 16 or 36 bytes"); + ESP_LOGE(LOG_TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes"); m_valueSet = false; } } //BLEUUID(std::string) @@ -128,7 +136,7 @@ BLEUUID::BLEUUID(std::string value) { */ BLEUUID::BLEUUID(uint8_t* pData, size_t size, bool msbFirst) { if (size != 16) { - log_e("ERROR: UUID length not 16 bytes"); + ESP_LOGE(LOG_TAG, "ERROR: UUID length not 16 bytes"); return; } m_uuid.len = ESP_UUID_LEN_128; @@ -204,7 +212,7 @@ uint8_t BLEUUID::bitSize() { case ESP_UUID_LEN_128: return 128; default: - log_e("Unknown UUID length: %d", m_uuid.len); + ESP_LOGE(LOG_TAG, "Unknown UUID length: %d", m_uuid.len); return 0; } // End of switch } // bitSize @@ -217,7 +225,7 @@ uint8_t BLEUUID::bitSize() { * @return True if the UUIDs are equal and false otherwise. */ bool BLEUUID::equals(BLEUUID uuid) { - //log_d("Comparing: %s to %s", toString().c_str(), uuid.toString().c_str()); + //ESP_LOGD(TAG, "Comparing: %s to %s", toString().c_str(), uuid.toString().c_str()); if (!m_valueSet || !uuid.m_valueSet) return false; if (uuid.m_uuid.len != m_uuid.len) { @@ -271,12 +279,12 @@ BLEUUID BLEUUID::fromString(std::string _uuid) { * @return The native UUID value or NULL if not set. */ esp_bt_uuid_t* BLEUUID::getNative() { - //log_d(">> getNative()") + //ESP_LOGD(TAG, ">> getNative()") if (m_valueSet == false) { - log_v("<< Return of un-initialized UUID!"); + ESP_LOGD(LOG_TAG, "<< Return of un-initialized UUID!"); return nullptr; } - //log_d("<< getNative()"); + //ESP_LOGD(TAG, "<< getNative()"); return &m_uuid; } // getNative @@ -288,7 +296,7 @@ esp_bt_uuid_t* BLEUUID::getNative() { * will convert 16 or 32 bit representations to the full 128bit. */ BLEUUID BLEUUID::to128() { - //log_v(">> toFull() - %s", toString().c_str()); + //ESP_LOGD(LOG_TAG, ">> toFull() - %s", toString().c_str()); // If we either don't have a value or are already a 128 bit UUID, nothing further to do. if (!m_valueSet || m_uuid.len == ESP_UUID_LEN_128) { @@ -330,7 +338,7 @@ BLEUUID BLEUUID::to128() { m_uuid.uuid.uuid128[0] = 0xfb; m_uuid.len = ESP_UUID_LEN_128; - //log_d("<< toFull <- %s", toString().c_str()); + //ESP_LOGD(TAG, "<< toFull <- %s", toString().c_str()); return *this; } // to128 @@ -349,38 +357,51 @@ BLEUUID BLEUUID::to128() { */ std::string BLEUUID::toString() { if (!m_valueSet) return ""; // If we have no value, nothing to format. + // If the UUIDs are 16 or 32 bit, pad correctly. + std::stringstream ss; if (m_uuid.len == ESP_UUID_LEN_16) { // If the UUID is 16bit, pad correctly. - char hex[9]; - snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid16); - return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; + ss << "0000" << + std::hex << + std::setfill('0') << + std::setw(4) << + m_uuid.uuid.uuid16 << + "-0000-1000-8000-00805f9b34fb"; + return ss.str(); // Return the string } // End 16bit UUID if (m_uuid.len == ESP_UUID_LEN_32) { // If the UUID is 32bit, pad correctly. - char hex[9]; - snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid32); - return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; + ss << std::hex << + std::setfill('0') << + std::setw(8) << + m_uuid.uuid.uuid32 << + "-0000-1000-8000-00805f9b34fb"; + return ss.str(); // return the string } // End 32bit UUID // The UUID is not 16bit or 32bit which means that it is 128bit. // // UUID string format: // AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP - auto size = 37; // 32 for UUID data, 4 for '-' delimiters and one for a terminator == 37 chars - char *hex = (char *)malloc(size); - snprintf(hex, size, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - m_uuid.uuid.uuid128[15], m_uuid.uuid.uuid128[14], - m_uuid.uuid.uuid128[13], m_uuid.uuid.uuid128[12], - m_uuid.uuid.uuid128[11], m_uuid.uuid.uuid128[10], - m_uuid.uuid.uuid128[9], m_uuid.uuid.uuid128[8], - m_uuid.uuid.uuid128[7], m_uuid.uuid.uuid128[6], - m_uuid.uuid.uuid128[5], m_uuid.uuid.uuid128[4], - m_uuid.uuid.uuid128[3], m_uuid.uuid.uuid128[2], - m_uuid.uuid.uuid128[1], m_uuid.uuid.uuid128[0]); - std::string res(hex); - free(hex); - return res; + ss << std::hex << std::setfill('0') << + std::setw(2) << (int) m_uuid.uuid.uuid128[15] << + std::setw(2) << (int) m_uuid.uuid.uuid128[14] << + std::setw(2) << (int) m_uuid.uuid.uuid128[13] << + std::setw(2) << (int) m_uuid.uuid.uuid128[12] << "-" << + std::setw(2) << (int) m_uuid.uuid.uuid128[11] << + std::setw(2) << (int) m_uuid.uuid.uuid128[10] << "-" << + std::setw(2) << (int) m_uuid.uuid.uuid128[9] << + std::setw(2) << (int) m_uuid.uuid.uuid128[8] << "-" << + std::setw(2) << (int) m_uuid.uuid.uuid128[7] << + std::setw(2) << (int) m_uuid.uuid.uuid128[6] << "-" << + std::setw(2) << (int) m_uuid.uuid.uuid128[5] << + std::setw(2) << (int) m_uuid.uuid.uuid128[4] << + std::setw(2) << (int) m_uuid.uuid.uuid128[3] << + std::setw(2) << (int) m_uuid.uuid.uuid128[2] << + std::setw(2) << (int) m_uuid.uuid.uuid128[1] << + std::setw(2) << (int) m_uuid.uuid.uuid128[0]; + return ss.str(); } // toString #endif /* CONFIG_BT_ENABLED */ diff --git a/libraries/BLE/src/BLEUtils.cpp b/libraries/BLE/src/BLEUtils.cpp index b9cf591f426..a9b735df14a 100644 --- a/libraries/BLE/src/BLEUtils.cpp +++ b/libraries/BLE/src/BLEUtils.cpp @@ -19,11 +19,16 @@ #include // ESP32 BLE #include // ESP32 BLE #include // ESP32 ESP-IDF +#include // ESP32 ESP-IDF #include // Part of C++ STL #include #include +#ifdef ARDUINO_ARCH_ESP32 #include "esp32-hal-log.h" +#endif + +static const char* LOG_TAG = "BLEUtils"; // Tag for logging. /* static std::map g_addressMap; @@ -604,32 +609,26 @@ static const gattService_t g_gattServices[] = { * @return A string representation of characteristic properties. */ std::string BLEUtils::characteristicPropertiesToString(esp_gatt_char_prop_t prop) { - std::string res = "broadcast: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"1":"0"); - res += ", read: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_READ)?"1":"0"); - res += ", write_nr: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"1":"0"); - res += ", write: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE)?"1":"0"); - res += ", notify: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"1":"0"); - res += ", indicate: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"1":"0"); - res += ", auth: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH)?"1":"0"); - return res; + std::stringstream stream; + stream << + "broadcast: " << ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"1":"0") << + ", read: " << ((prop & ESP_GATT_CHAR_PROP_BIT_READ)?"1":"0") << + ", write_nr: " << ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"1":"0") << + ", write: " << ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE)?"1":"0") << + ", notify: " << ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"1":"0") << + ", indicate: " << ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"1":"0") << + ", auth: " << ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH)?"1":"0"); + return stream.str(); } // characteristicPropertiesToString /** * @brief Convert an esp_gatt_id_t to a string. */ static std::string gattIdToString(esp_gatt_id_t gattId) { - std::string res = "uuid: " + BLEUUID(gattId.uuid).toString() + ", inst_id: "; - char val[8]; - snprintf(val, sizeof(val), "%d", (int)gattId.inst_id); - res += val; - return res; + std::stringstream stream; + stream << "uuid: " << BLEUUID(gattId.uuid).toString() << ", inst_id: " << (int)gattId.inst_id; + //sprintf(buffer, "uuid: %s, inst_id: %d", uuidToString(gattId.uuid).c_str(), gattId.inst_id); + return stream.str(); } // gattIdToString @@ -638,7 +637,6 @@ static std::string gattIdToString(esp_gatt_id_t gattId) { */ const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { switch (type) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case BLE_ADDR_TYPE_PUBLIC: return "BLE_ADDR_TYPE_PUBLIC"; case BLE_ADDR_TYPE_RANDOM: @@ -647,7 +645,6 @@ const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { return "BLE_ADDR_TYPE_RPA_PUBLIC"; case BLE_ADDR_TYPE_RPA_RANDOM: return "BLE_ADDR_TYPE_RPA_RANDOM"; -#endif default: return " esp_ble_addr_type_t"; } @@ -660,23 +657,23 @@ const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { * @return std::string A string representation of the advertising flags. */ std::string BLEUtils::adFlagsToString(uint8_t adFlags) { - std::string res; + std::stringstream ss; if (adFlags & (1 << 0)) { - res += "[LE Limited Discoverable Mode] "; + ss << "[LE Limited Discoverable Mode] "; } if (adFlags & (1 << 1)) { - res += "[LE General Discoverable Mode] "; + ss << "[LE General Discoverable Mode] "; } if (adFlags & (1 << 2)) { - res += "[BR/EDR Not Supported] "; + ss << "[BR/EDR Not Supported] "; } if (adFlags & (1 << 3)) { - res += "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] "; + ss << "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] "; } if (adFlags & (1 << 4)) { - res += "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] "; + ss << "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] "; } - return res; + return ss.str(); } // adFlagsToString @@ -690,7 +687,6 @@ std::string BLEUtils::adFlagsToString(uint8_t adFlags) { */ const char* BLEUtils::advTypeToString(uint8_t advType) { switch (advType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_BLE_AD_TYPE_FLAG: // 0x01 return "ESP_BLE_AD_TYPE_FLAG"; case ESP_BLE_AD_TYPE_16SRV_PART: // 0x02 @@ -741,9 +737,8 @@ const char* BLEUtils::advTypeToString(uint8_t advType) { return "ESP_BLE_AD_TYPE_128SERVICE_DATA"; case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: // 0xff return "ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE"; -#endif default: - log_v(" adv data type: 0x%x", advType); + ESP_LOGV(LOG_TAG, " adv data type: 0x%x", advType); return ""; } // End switch } // advTypeToString @@ -778,7 +773,7 @@ char* BLEUtils::buildHexData(uint8_t* target, uint8_t* source, uint8_t length) { if (target == nullptr) { target = (uint8_t*) malloc(length * 2 + 1); if (target == nullptr) { - log_e("buildHexData: malloc failed"); + ESP_LOGE(LOG_TAG, "buildHexData: malloc failed"); return nullptr; } } @@ -808,13 +803,13 @@ char* BLEUtils::buildHexData(uint8_t* target, uint8_t* source, uint8_t length) { * @return A string representation of a piece of memory. */ std::string BLEUtils::buildPrintData(uint8_t* source, size_t length) { - std::string res; + std::ostringstream ss; for (int i = 0; i < length; i++) { char c = *source; - res += (isprint(c) ? c : '.'); + ss << (isprint(c) ? c : '.'); source++; } - return res; + return ss.str(); } // buildPrintData @@ -825,7 +820,6 @@ std::string BLEUtils::buildPrintData(uint8_t* source, size_t length) { */ std::string BLEUtils::gattCloseReasonToString(esp_gatt_conn_reason_t reason) { switch (reason) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GATT_CONN_UNKNOWN: { return "ESP_GATT_CONN_UNKNOWN"; } @@ -853,7 +847,6 @@ std::string BLEUtils::gattCloseReasonToString(esp_gatt_conn_reason_t reason) { case ESP_GATT_CONN_NONE: { return "ESP_GATT_CONN_NONE"; } -#endif default: { return "Unknown"; } @@ -863,7 +856,6 @@ std::string BLEUtils::gattCloseReasonToString(esp_gatt_conn_reason_t reason) { std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType) { switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GATTC_ACL_EVT: return "ESP_GATTC_ACL_EVT"; case ESP_GATTC_ADV_DATA_EVT: @@ -946,9 +938,8 @@ std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType return "ESP_GATTC_WRITE_CHAR_EVT"; case ESP_GATTC_WRITE_DESCR_EVT: return "ESP_GATTC_WRITE_DESCR_EVT"; -#endif default: - log_v("Unknown GATT Client event type: %d", eventType); + ESP_LOGV(LOG_TAG, "Unknown GATT Client event type: %d", eventType); return "Unknown"; } } // gattClientEventTypeToString @@ -961,7 +952,6 @@ std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType */ std::string BLEUtils::gattServerEventTypeToString(esp_gatts_cb_event_t eventType) { switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GATTS_REG_EVT: return "ESP_GATTS_REG_EVT"; case ESP_GATTS_READ_EVT: @@ -1012,7 +1002,6 @@ std::string BLEUtils::gattServerEventTypeToString(esp_gatts_cb_event_t eventType return "ESP_GATTS_SET_ATTR_VAL_EVT"; case ESP_GATTS_SEND_SERVICE_CHANGE_EVT: return "ESP_GATTS_SEND_SERVICE_CHANGE_EVT"; -#endif default: return "Unknown"; } @@ -1026,14 +1015,12 @@ std::string BLEUtils::gattServerEventTypeToString(esp_gatts_cb_event_t eventType */ const char* BLEUtils::devTypeToString(esp_bt_dev_type_t type) { switch (type) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_BT_DEVICE_TYPE_BREDR: return "ESP_BT_DEVICE_TYPE_BREDR"; case ESP_BT_DEVICE_TYPE_BLE: return "ESP_BT_DEVICE_TYPE_BLE"; case ESP_BT_DEVICE_TYPE_DUMO: return "ESP_BT_DEVICE_TYPE_DUMO"; -#endif default: return "Unknown"; } @@ -1046,14 +1033,14 @@ const char* BLEUtils::devTypeToString(esp_bt_dev_type_t type) { void BLEUtils::dumpGapEvent( esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param) { - log_v("Received a GAP event: %s", gapEventToString(event)); + ESP_LOGV(LOG_TAG, "Received a GAP event: %s", gapEventToString(event)); switch (event) { #if CONFIG_LOG_DEFAULT_LEVEL > 4 // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT // adv_data_cmpl // - esp_bt_status_t case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_data_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->adv_data_cmpl.status); break; } // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT @@ -1062,7 +1049,7 @@ void BLEUtils::dumpGapEvent( // adv_data_raw_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_data_raw_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->adv_data_raw_cmpl.status); break; } // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT @@ -1071,7 +1058,7 @@ void BLEUtils::dumpGapEvent( // adv_start_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_start_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->adv_start_cmpl.status); break; } // ESP_GAP_BLE_ADV_START_COMPLETE_EVT @@ -1080,7 +1067,7 @@ void BLEUtils::dumpGapEvent( // adv_stop_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_stop_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->adv_stop_cmpl.status); break; } // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT @@ -1095,7 +1082,7 @@ void BLEUtils::dumpGapEvent( // - esp_bd_addr_type_t addr_type // - esp_bt_dev_type_t dev_type case ESP_GAP_BLE_AUTH_CMPL_EVT: { - log_v("[bd_addr: %s, key_present: %d, key: ***, key_type: %d, success: %d, fail_reason: %d, addr_type: ***, dev_type: %s]", + ESP_LOGV(LOG_TAG, "[bd_addr: %s, key_present: %d, key: ***, key_type: %d, success: %d, fail_reason: %d, addr_type: ***, dev_type: %s]", BLEAddress(param->ble_security.auth_cmpl.bd_addr).toString().c_str(), param->ble_security.auth_cmpl.key_present, param->ble_security.auth_cmpl.key_type, @@ -1111,7 +1098,7 @@ void BLEUtils::dumpGapEvent( // clear_bond_dev_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: { - log_v("[status: %d]", param->clear_bond_dev_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->clear_bond_dev_cmpl.status); break; } // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT @@ -1127,7 +1114,7 @@ void BLEUtils::dumpGapEvent( // ESP_GAP_BLE_NC_REQ_EVT case ESP_GAP_BLE_NC_REQ_EVT: { - log_v("[bd_addr: %s, passkey: %d]", + ESP_LOGV(LOG_TAG, "[bd_addr: %s, passkey: %d]", BLEAddress(param->ble_security.key_notif.bd_addr).toString().c_str(), param->ble_security.key_notif.passkey); break; @@ -1140,7 +1127,7 @@ void BLEUtils::dumpGapEvent( // - int8_t rssi // - esp_bd_addr_t remote_addr case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: { - log_v("[status: %d, rssi: %d, remote_addr: %s]", + ESP_LOGV(LOG_TAG, "[status: %d, rssi: %d, remote_addr: %s]", param->read_rssi_cmpl.status, param->read_rssi_cmpl.rssi, BLEAddress(param->read_rssi_cmpl.remote_addr).toString().c_str() @@ -1153,7 +1140,7 @@ void BLEUtils::dumpGapEvent( // scan_param_cmpl. // - esp_bt_status_t status case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_param_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->scan_param_cmpl.status); break; } // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT @@ -1174,7 +1161,7 @@ void BLEUtils::dumpGapEvent( case ESP_GAP_BLE_SCAN_RESULT_EVT: { switch (param->scan_rst.search_evt) { case ESP_GAP_SEARCH_INQ_RES_EVT: { - log_v("search_evt: %s, bda: %s, dev_type: %s, ble_addr_type: %s, ble_evt_type: %s, rssi: %d, ble_adv: ??, flag: %d (%s), num_resps: %d, adv_data_len: %d, scan_rsp_len: %d", + ESP_LOGV(LOG_TAG, "search_evt: %s, bda: %s, dev_type: %s, ble_addr_type: %s, ble_evt_type: %s, rssi: %d, ble_adv: ??, flag: %d (%s), num_resps: %d, adv_data_len: %d, scan_rsp_len: %d", searchEventTypeToString(param->scan_rst.search_evt), BLEAddress(param->scan_rst.bda).toString().c_str(), devTypeToString(param->scan_rst.dev_type), @@ -1191,7 +1178,7 @@ void BLEUtils::dumpGapEvent( } // ESP_GAP_SEARCH_INQ_RES_EVT default: { - log_v("search_evt: %s",searchEventTypeToString(param->scan_rst.search_evt)); + ESP_LOGV(LOG_TAG, "search_evt: %s",searchEventTypeToString(param->scan_rst.search_evt)); break; } } @@ -1203,13 +1190,13 @@ void BLEUtils::dumpGapEvent( // scan_rsp_data_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_rsp_data_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->scan_rsp_data_cmpl.status); break; } // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_rsp_data_raw_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->scan_rsp_data_raw_cmpl.status); break; } // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT @@ -1218,7 +1205,7 @@ void BLEUtils::dumpGapEvent( // scan_start_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_start_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->scan_start_cmpl.status); break; } // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT @@ -1227,7 +1214,7 @@ void BLEUtils::dumpGapEvent( // scan_stop_cmpl // - esp_bt_status_t status case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_stop_cmpl.status); + ESP_LOGV(LOG_TAG, "[status: %d]", param->scan_stop_cmpl.status); break; } // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT @@ -1242,7 +1229,7 @@ void BLEUtils::dumpGapEvent( // - uint16_t conn_int // - uint16_t timeout case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: { - log_v("[status: %d, bd_addr: %s, min_int: %d, max_int: %d, latency: %d, conn_int: %d, timeout: %d]", + ESP_LOGV(LOG_TAG, "[status: %d, bd_addr: %s, min_int: %d, max_int: %d, latency: %d, conn_int: %d, timeout: %d]", param->update_conn_params.status, BLEAddress(param->update_conn_params.bda).toString().c_str(), param->update_conn_params.min_int, @@ -1256,12 +1243,12 @@ void BLEUtils::dumpGapEvent( // ESP_GAP_BLE_SEC_REQ_EVT case ESP_GAP_BLE_SEC_REQ_EVT: { - log_v("[bd_addr: %s]", BLEAddress(param->ble_security.ble_req.bd_addr).toString().c_str()); + ESP_LOGV(LOG_TAG, "[bd_addr: %s]", BLEAddress(param->ble_security.ble_req.bd_addr).toString().c_str()); break; } // ESP_GAP_BLE_SEC_REQ_EVT #endif default: { - log_v("*** dumpGapEvent: Logger not coded ***"); + ESP_LOGV(LOG_TAG, "*** dumpGapEvent: Logger not coded ***"); break; } // default } // switch @@ -1280,7 +1267,7 @@ void BLEUtils::dumpGattClientEvent( esp_ble_gattc_cb_param_t* evtParam) { //esp_ble_gattc_cb_param_t* evtParam = (esp_ble_gattc_cb_param_t*) param; - log_v("GATT Event: %s", BLEUtils::gattClientEventTypeToString(event).c_str()); + ESP_LOGV(LOG_TAG, "GATT Event: %s", BLEUtils::gattClientEventTypeToString(event).c_str()); switch (event) { #if CONFIG_LOG_DEFAULT_LEVEL > 4 // ESP_GATTC_CLOSE_EVT @@ -1291,7 +1278,7 @@ void BLEUtils::dumpGattClientEvent( // - esp_bd_addr_t remote_bda // - esp_gatt_conn_reason_t reason case ESP_GATTC_CLOSE_EVT: { - log_v("[status: %s, reason:%s, conn_id: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, reason:%s, conn_id: %d]", BLEUtils::gattStatusToString(evtParam->close.status).c_str(), BLEUtils::gattCloseReasonToString(evtParam->close.reason).c_str(), evtParam->close.conn_id); @@ -1305,7 +1292,7 @@ void BLEUtils::dumpGattClientEvent( // - uint16_t conn_id // - esp_bd_addr_t remote_bda case ESP_GATTC_CONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, remote_bda: %s]", evtParam->connect.conn_id, BLEAddress(evtParam->connect.remote_bda).toString().c_str() ); @@ -1319,7 +1306,7 @@ void BLEUtils::dumpGattClientEvent( // - uint16_t conn_id // - esp_bd_addr_t remote_bda case ESP_GATTC_DISCONNECT_EVT: { - log_v("[reason: %s, conn_id: %d, remote_bda: %s]", + ESP_LOGV(LOG_TAG, "[reason: %s, conn_id: %d, remote_bda: %s]", BLEUtils::gattCloseReasonToString(evtParam->disconnect.reason).c_str(), evtParam->disconnect.conn_id, BLEAddress(evtParam->disconnect.remote_bda).toString().c_str() @@ -1345,7 +1332,7 @@ void BLEUtils::dumpGattClientEvent( if (evtParam->get_char.char_id.uuid.len == ESP_UUID_LEN_16) { description = BLEUtils::gattCharacteristicUUIDToString(evtParam->get_char.char_id.uuid.uuid.uuid16); } - log_v("[status: %s, conn_id: %d, srvc_id: %s, char_id: %s [description: %s]\nchar_prop: %s]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d, srvc_id: %s, char_id: %s [description: %s]\nchar_prop: %s]", BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), evtParam->get_char.conn_id, BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str(), @@ -1354,7 +1341,7 @@ void BLEUtils::dumpGattClientEvent( BLEUtils::characteristicPropertiesToString(evtParam->get_char.char_prop).c_str() ); } else { - log_v("[status: %s, conn_id: %d, srvc_id: %s]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d, srvc_id: %s]", BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), evtParam->get_char.conn_id, BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str() @@ -1375,7 +1362,7 @@ void BLEUtils::dumpGattClientEvent( // bool is_notify // case ESP_GATTC_NOTIFY_EVT: { - log_v("[conn_id: %d, remote_bda: %s, handle: %d 0x%.2x, value_len: %d, is_notify: %d]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, remote_bda: %s, handle: %d 0x%.2x, value_len: %d, is_notify: %d]", evtParam->notify.conn_id, BLEAddress(evtParam->notify.remote_bda).toString().c_str(), evtParam->notify.handle, @@ -1395,7 +1382,7 @@ void BLEUtils::dumpGattClientEvent( // - uint16_t mtu // case ESP_GATTC_OPEN_EVT: { - log_v("[status: %s, conn_id: %d, remote_bda: %s, mtu: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d, remote_bda: %s, mtu: %d]", BLEUtils::gattStatusToString(evtParam->open.status).c_str(), evtParam->open.conn_id, BLEAddress(evtParam->open.remote_bda).toString().c_str(), @@ -1415,7 +1402,7 @@ void BLEUtils::dumpGattClientEvent( // uint16_t value_type // uint16_t value_len case ESP_GATTC_READ_CHAR_EVT: { - log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, value_len: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d, handle: %d 0x%.2x, value_len: %d]", BLEUtils::gattStatusToString(evtParam->read.status).c_str(), evtParam->read.conn_id, evtParam->read.handle, @@ -1426,7 +1413,7 @@ void BLEUtils::dumpGattClientEvent( GeneralUtils::hexDump(evtParam->read.value, evtParam->read.value_len); /* char* pHexData = BLEUtils::buildHexData(nullptr, evtParam->read.value, evtParam->read.value_len); - log_v("value: %s \"%s\"", pHexData, BLEUtils::buildPrintData(evtParam->read.value, evtParam->read.value_len).c_str()); + ESP_LOGV(LOG_TAG, "value: %s \"%s\"", pHexData, BLEUtils::buildPrintData(evtParam->read.value, evtParam->read.value_len).c_str()); free(pHexData); */ } @@ -1439,7 +1426,7 @@ void BLEUtils::dumpGattClientEvent( // - esp_gatt_status_t status // - uint16_t app_id case ESP_GATTC_REG_EVT: { - log_v("[status: %s, app_id: 0x%x]", + ESP_LOGV(LOG_TAG, "[status: %s, app_id: 0x%x]", BLEUtils::gattStatusToString(evtParam->reg.status).c_str(), evtParam->reg.app_id); break; @@ -1451,7 +1438,7 @@ void BLEUtils::dumpGattClientEvent( // - esp_gatt_status_t status // - uint16_t handle case ESP_GATTC_REG_FOR_NOTIFY_EVT: { - log_v("[status: %s, handle: %d 0x%.2x]", + ESP_LOGV(LOG_TAG, "[status: %s, handle: %d 0x%.2x]", BLEUtils::gattStatusToString(evtParam->reg_for_notify.status).c_str(), evtParam->reg_for_notify.handle, evtParam->reg_for_notify.handle @@ -1465,7 +1452,7 @@ void BLEUtils::dumpGattClientEvent( // - esp_gatt_status_t status // - uint16_t conn_id case ESP_GATTC_SEARCH_CMPL_EVT: { - log_v("[status: %s, conn_id: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d]", BLEUtils::gattStatusToString(evtParam->search_cmpl.status).c_str(), evtParam->search_cmpl.conn_id); break; @@ -1479,7 +1466,7 @@ void BLEUtils::dumpGattClientEvent( // - uint16_t end_handle // - esp_gatt_id_t srvc_id case ESP_GATTC_SEARCH_RES_EVT: { - log_v("[conn_id: %d, start_handle: %d 0x%.2x, end_handle: %d 0x%.2x, srvc_id: %s", + ESP_LOGV(LOG_TAG, "[conn_id: %d, start_handle: %d 0x%.2x, end_handle: %d 0x%.2x, srvc_id: %s", evtParam->search_res.conn_id, evtParam->search_res.start_handle, evtParam->search_res.start_handle, @@ -1497,7 +1484,7 @@ void BLEUtils::dumpGattClientEvent( // - uint16_t handle // - uint16_t offset case ESP_GATTC_WRITE_CHAR_EVT: { - log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, offset: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: %d, handle: %d 0x%.2x, offset: %d]", BLEUtils::gattStatusToString(evtParam->write.status).c_str(), evtParam->write.conn_id, evtParam->write.handle, @@ -1527,12 +1514,12 @@ void BLEUtils::dumpGattServerEvent( esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* evtParam) { - log_v("GATT ServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); + ESP_LOGV(LOG_TAG, "GATT ServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); switch (event) { #if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GATTS_ADD_CHAR_DESCR_EVT: { - log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + ESP_LOGV(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", gattStatusToString(evtParam->add_char_descr.status).c_str(), evtParam->add_char_descr.attr_handle, evtParam->add_char_descr.attr_handle, @@ -1544,7 +1531,7 @@ void BLEUtils::dumpGattServerEvent( case ESP_GATTS_ADD_CHAR_EVT: { if (evtParam->add_char.status == ESP_GATT_OK) { - log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + ESP_LOGV(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", gattStatusToString(evtParam->add_char.status).c_str(), evtParam->add_char.attr_handle, evtParam->add_char.attr_handle, @@ -1552,7 +1539,7 @@ void BLEUtils::dumpGattServerEvent( evtParam->add_char.service_handle, BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); } else { - log_e("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", + ESP_LOGE(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", gattStatusToString(evtParam->add_char.status).c_str(), evtParam->add_char.attr_handle, evtParam->add_char.attr_handle, @@ -1570,7 +1557,7 @@ void BLEUtils::dumpGattServerEvent( // - esp_gatt_status_t status – The status code. // - uint16_t conn_id – The connection used. case ESP_GATTS_CONF_EVT: { - log_v("[status: %s, conn_id: 0x%.2x]", + ESP_LOGV(LOG_TAG, "[status: %s, conn_id: 0x%.2x]", gattStatusToString(evtParam->conf.status).c_str(), evtParam->conf.conn_id); break; @@ -1578,21 +1565,21 @@ void BLEUtils::dumpGattServerEvent( case ESP_GATTS_CONGEST_EVT: { - log_v("[conn_id: %d, congested: %d]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, congested: %d]", evtParam->congest.conn_id, evtParam->congest.congested); break; } // ESP_GATTS_CONGEST_EVT case ESP_GATTS_CONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, remote_bda: %s]", evtParam->connect.conn_id, BLEAddress(evtParam->connect.remote_bda).toString().c_str()); break; } // ESP_GATTS_CONNECT_EVT case ESP_GATTS_CREATE_EVT: { - log_v("[status: %s, service_handle: %d 0x%.2x, service_id: [%s]]", + ESP_LOGV(LOG_TAG, "[status: %s, service_handle: %d 0x%.2x, service_id: [%s]]", gattStatusToString(evtParam->create.status).c_str(), evtParam->create.service_handle, evtParam->create.service_handle, @@ -1601,7 +1588,7 @@ void BLEUtils::dumpGattServerEvent( } // ESP_GATTS_CREATE_EVT case ESP_GATTS_DISCONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, remote_bda: %s]", evtParam->connect.conn_id, BLEAddress(evtParam->connect.remote_bda).toString().c_str()); break; @@ -1632,7 +1619,7 @@ void BLEUtils::dumpGattServerEvent( break; } - log_v("[conn_id: %d, trans_id: %d, bda: %s, exec_write_flag: 0x%.2x=%s]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, exec_write_flag: 0x%.2x=%s]", evtParam->exec_write.conn_id, evtParam->exec_write.trans_id, BLEAddress(evtParam->exec_write.bda).toString().c_str(), @@ -1643,14 +1630,14 @@ void BLEUtils::dumpGattServerEvent( case ESP_GATTS_MTU_EVT: { - log_v("[conn_id: %d, mtu: %d]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, mtu: %d]", evtParam->mtu.conn_id, evtParam->mtu.mtu); break; } // ESP_GATTS_MTU_EVT case ESP_GATTS_READ_EVT: { - log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, is_long: %d, need_rsp:%d]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, is_long: %d, need_rsp:%d]", evtParam->read.conn_id, evtParam->read.trans_id, BLEAddress(evtParam->read.bda).toString().c_str(), @@ -1661,14 +1648,14 @@ void BLEUtils::dumpGattServerEvent( } // ESP_GATTS_READ_EVT case ESP_GATTS_RESPONSE_EVT: { - log_v("[status: %s, handle: 0x%.2x]", + ESP_LOGV(LOG_TAG, "[status: %s, handle: 0x%.2x]", gattStatusToString(evtParam->rsp.status).c_str(), evtParam->rsp.handle); break; } // ESP_GATTS_RESPONSE_EVT case ESP_GATTS_REG_EVT: { - log_v("[status: %s, app_id: %d]", + ESP_LOGV(LOG_TAG, "[status: %s, app_id: %d]", gattStatusToString(evtParam->reg.status).c_str(), evtParam->reg.app_id); break; @@ -1681,7 +1668,7 @@ void BLEUtils::dumpGattServerEvent( // - esp_gatt_status_t status // - uint16_t service_handle case ESP_GATTS_START_EVT: { - log_v("[status: %s, service_handle: 0x%.2x]", + ESP_LOGV(LOG_TAG, "[status: %s, service_handle: 0x%.2x]", gattStatusToString(evtParam->start.status).c_str(), evtParam->start.service_handle); break; @@ -1701,7 +1688,7 @@ void BLEUtils::dumpGattServerEvent( // - uint16_t len – The length of the incoming value part. // - uint8_t* value – The data for this value part. case ESP_GATTS_WRITE_EVT: { - log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, offset: %d, need_rsp: %d, is_prep: %d, len: %d]", + ESP_LOGV(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, offset: %d, need_rsp: %d, is_prep: %d, len: %d]", evtParam->write.conn_id, evtParam->write.trans_id, BLEAddress(evtParam->write.bda).toString().c_str(), @@ -1711,13 +1698,13 @@ void BLEUtils::dumpGattServerEvent( evtParam->write.is_prep, evtParam->write.len); char* pHex = buildHexData(nullptr, evtParam->write.value, evtParam->write.len); - log_v("[Data: %s]", pHex); + ESP_LOGV(LOG_TAG, "[Data: %s]", pHex); free(pHex); break; } // ESP_GATTS_WRITE_EVT #endif default: - log_v("dumpGattServerEvent: *** NOT CODED ***"); + ESP_LOGV(LOG_TAG, "dumpGattServerEvent: *** NOT CODED ***"); break; } } // dumpGattServerEvent @@ -1730,7 +1717,6 @@ void BLEUtils::dumpGattServerEvent( */ const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_BLE_EVT_CONN_ADV: return "ESP_BLE_EVT_CONN_ADV"; case ESP_BLE_EVT_CONN_DIR_ADV: @@ -1741,9 +1727,8 @@ const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { return "ESP_BLE_EVT_NON_CONN_ADV"; case ESP_BLE_EVT_SCAN_RSP: return "ESP_BLE_EVT_SCAN_RSP"; -#endif default: - log_v("Unknown esp_ble_evt_type_t: %d (0x%.2x)", eventType, eventType); + ESP_LOGV(LOG_TAG, "Unknown esp_ble_evt_type_t: %d (0x%.2x)", eventType, eventType); return "*** Unknown ***"; } } // eventTypeToString @@ -1757,7 +1742,6 @@ const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { */ const char* BLEUtils::gapEventToString(uint32_t eventType) { switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: return "ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT"; case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: @@ -1812,9 +1796,8 @@ const char* BLEUtils::gapEventToString(uint32_t eventType) { return "ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT"; case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: return "ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT"; -#endif default: - log_v("gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); + ESP_LOGV(LOG_TAG, "gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); return "Unknown event type"; } } // gapEventToString @@ -1854,22 +1837,14 @@ std::string BLEUtils::gattDescriptorUUIDToString(uint32_t descriptorUUID) { * @return A string representation of an esp_gattc_service_elem_t. */ std::string BLEUtils::gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement) { - std::string res; - char val[6]; - res += "[uuid: " + BLEUUID(pGATTCServiceElement->uuid).toString() + ", start_handle: "; - snprintf(val, sizeof(val), "%d", pGATTCServiceElement->start_handle); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->start_handle); - res += val; - res += ", end_handle: "; - snprintf(val, sizeof(val), "%d", pGATTCServiceElement->end_handle); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->end_handle); - res += val; - res += "]"; - return res; + std::stringstream ss; + + ss << "[uuid: " << BLEUUID(pGATTCServiceElement->uuid).toString() << + ", start_handle: " << pGATTCServiceElement->start_handle << + " 0x" << std::hex << pGATTCServiceElement->start_handle << + ", end_handle: " << std::dec << pGATTCServiceElement->end_handle << + " 0x" << std::hex << pGATTCServiceElement->end_handle << "]"; + return ss.str(); } // gattcServiceElementToString @@ -1901,7 +1876,6 @@ std::string BLEUtils::gattServiceToString(uint32_t serviceId) { */ std::string BLEUtils::gattStatusToString(esp_gatt_status_t status) { switch (status) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GATT_OK: return "ESP_GATT_OK"; case ESP_GATT_INVALID_HANDLE: @@ -1988,7 +1962,6 @@ std::string BLEUtils::gattStatusToString(esp_gatt_status_t status) { return "ESP_GATT_PRC_IN_PROGRESS"; case ESP_GATT_OUT_OF_RANGE: return "ESP_GATT_OUT_OF_RANGE"; -#endif default: return "Unknown"; } @@ -2015,7 +1988,6 @@ std::string BLEUtils::getMember(uint32_t memberId) { */ const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { switch (searchEvt) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 case ESP_GAP_SEARCH_INQ_RES_EVT: return "ESP_GAP_SEARCH_INQ_RES_EVT"; case ESP_GAP_SEARCH_INQ_CMPL_EVT: @@ -2030,9 +2002,8 @@ const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { return "ESP_GAP_SEARCH_DI_DISC_CMPL_EVT"; case ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT: return "ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT"; -#endif default: - log_v("Unknown event type: 0x%x", searchEvt); + ESP_LOGV(LOG_TAG, "Unknown event type: 0x%x", searchEvt); return "Unknown event type"; } } // searchEventTypeToString diff --git a/libraries/BLE/src/BLEValue.cpp b/libraries/BLE/src/BLEValue.cpp index 40f6a20a656..ec1e61f51fc 100644 --- a/libraries/BLE/src/BLEValue.cpp +++ b/libraries/BLE/src/BLEValue.cpp @@ -7,7 +7,16 @@ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include "BLEValue.h" + +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG="BLEValue"; +#endif + + BLEValue::BLEValue() { m_accumulation = ""; @@ -22,7 +31,7 @@ BLEValue::BLEValue() { * @param [in] part A message part being added. */ void BLEValue::addPart(std::string part) { - log_v(">> addPart: length=%d", part.length()); + ESP_LOGD(LOG_TAG, ">> addPart: length=%d", part.length()); m_accumulation += part; } // addPart @@ -34,7 +43,7 @@ void BLEValue::addPart(std::string part) { * @param [in] length The number of bytes being added. */ void BLEValue::addPart(uint8_t* pData, size_t length) { - log_v(">> addPart: length=%d", length); + ESP_LOGD(LOG_TAG, ">> addPart: length=%d", length); m_accumulation += std::string((char*) pData, length); } // addPart @@ -43,7 +52,7 @@ void BLEValue::addPart(uint8_t* pData, size_t length) { * @brief Cancel the current accumulation. */ void BLEValue::cancel() { - log_v(">> cancel"); + ESP_LOGD(LOG_TAG, ">> cancel"); m_accumulation = ""; m_readOffset = 0; } // cancel @@ -56,7 +65,7 @@ void BLEValue::cancel() { * we now have the complete message and commit the change as a unit. */ void BLEValue::commit() { - log_v(">> commit"); + ESP_LOGD(LOG_TAG, ">> commit"); // If there is nothing to commit, do nothing. if (m_accumulation.length() == 0) return; setValue(m_accumulation); diff --git a/libraries/BLE/src/FreeRTOS.cpp b/libraries/BLE/src/FreeRTOS.cpp index 2f52b99d389..1920fa43021 100644 --- a/libraries/BLE/src/FreeRTOS.cpp +++ b/libraries/BLE/src/FreeRTOS.cpp @@ -12,7 +12,13 @@ #include #include "FreeRTOS.h" #include "sdkconfig.h" +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "FreeRTOS"; +#endif /** * Sleep for the specified number of milliseconds. @@ -60,8 +66,10 @@ uint32_t FreeRTOS::getTimeSinceStart() { * @return The value associated with the semaphore. */ uint32_t FreeRTOS::Semaphore::wait(std::string owner) { - log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); + ESP_LOGV(LOG_TAG, ">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); + m_owner = owner; + if (m_usePthreads) { pthread_mutex_lock(&m_pthread_mutex); } else { @@ -74,42 +82,10 @@ uint32_t FreeRTOS::Semaphore::wait(std::string owner) { xSemaphoreGive(m_semaphore); } - log_v("<< wait: Semaphore released: %s", toString().c_str()); + ESP_LOGV(LOG_TAG, "<< wait: Semaphore released: %s", toString().c_str()); return m_value; } // wait -/** - * @brief Wait for a semaphore to be released in a given period of time by trying to take it and - * then releasing it again. The value associated with the semaphore can be taken by value() call after return - * @param [in] owner A debug tag. - * @param [in] timeoutMs timeout to wait in ms. - * @return True if we took the semaphore within timeframe. - */ -bool FreeRTOS::Semaphore::timedWait(std::string owner, uint32_t timeoutMs) { - log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); - - if (m_usePthreads && timeoutMs != portMAX_DELAY) { - assert(false); // We apparently don't have a timed wait for pthreads. - } - - auto ret = pdTRUE; - - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - ret = xSemaphoreTake(m_semaphore, timeoutMs); - } - - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } - - log_v("<< wait: Semaphore %s released: %d", toString().c_str(), ret); - return ret; -} // wait - FreeRTOS::Semaphore::Semaphore(std::string name) { m_usePthreads = false; // Are we using pThreads or FreeRTOS? @@ -140,9 +116,7 @@ FreeRTOS::Semaphore::~Semaphore() { * The Semaphore is given. */ void FreeRTOS::Semaphore::give() { - log_v("Semaphore giving: %s", toString().c_str()); - m_owner = std::string(""); - + ESP_LOGV(LOG_TAG, "Semaphore giving: %s", toString().c_str()); if (m_usePthreads) { pthread_mutex_unlock(&m_pthread_mutex); } else { @@ -152,6 +126,7 @@ void FreeRTOS::Semaphore::give() { // FreeRTOS::sleep(10); // #endif + m_owner = std::string(""); } // Semaphore::give @@ -186,7 +161,7 @@ void FreeRTOS::Semaphore::giveFromISR() { * @return True if we took the semaphore. */ bool FreeRTOS::Semaphore::take(std::string owner) { - log_v("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); + ESP_LOGD(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); bool rc = false; if (m_usePthreads) { pthread_mutex_lock(&m_pthread_mutex); @@ -195,9 +170,9 @@ bool FreeRTOS::Semaphore::take(std::string owner) { } m_owner = owner; if (rc) { - log_v("Semaphore taken: %s", toString().c_str()); + ESP_LOGD(LOG_TAG, "Semaphore taken: %s", toString().c_str()); } else { - log_e("Semaphore NOT taken: %s", toString().c_str()); + ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str()); } return rc; } // Semaphore::take @@ -211,7 +186,7 @@ bool FreeRTOS::Semaphore::take(std::string owner) { * @return True if we took the semaphore. */ bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { - log_v("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); + ESP_LOGV(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); bool rc = false; if (m_usePthreads) { assert(false); // We apparently don't have a timed wait for pthreads. @@ -220,9 +195,9 @@ bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { } m_owner = owner; if (rc) { - log_v("Semaphore taken: %s", toString().c_str()); + ESP_LOGV(LOG_TAG, "Semaphore taken: %s", toString().c_str()); } else { - log_e("Semaphore NOT taken: %s", toString().c_str()); + ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str()); } return rc; } // Semaphore::take @@ -234,12 +209,9 @@ bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { * @return A string representation of the semaphore. */ std::string FreeRTOS::Semaphore::toString() { - char hex[9]; - std::string res = "name: " + m_name + " (0x"; - snprintf(hex, sizeof(hex), "%08x", (uint32_t)m_semaphore); - res += hex; - res += "), owner: " + m_owner; - return res; + std::stringstream stringStream; + stringStream << "name: "<< m_name << " (0x" << std::hex << std::setfill('0') << (uint32_t)m_semaphore << "), owner: " << m_owner; + return stringStream.str(); } // toString diff --git a/libraries/BLE/src/FreeRTOS.h b/libraries/BLE/src/FreeRTOS.h index 4d089c81db6..b861c8757c8 100644 --- a/libraries/BLE/src/FreeRTOS.h +++ b/libraries/BLE/src/FreeRTOS.h @@ -40,8 +40,6 @@ class FreeRTOS { bool take(uint32_t timeoutMs, std::string owner = ""); std::string toString(); uint32_t wait(std::string owner = ""); - bool timedWait(std::string owner = "", uint32_t timeoutMs = portMAX_DELAY); - uint32_t value(){ return m_value; }; private: SemaphoreHandle_t m_semaphore; diff --git a/libraries/BLE/src/GeneralUtils.cpp b/libraries/BLE/src/GeneralUtils.cpp index 02736b81b1a..019c81bd8f7 100644 --- a/libraries/BLE/src/GeneralUtils.cpp +++ b/libraries/BLE/src/GeneralUtils.cpp @@ -18,7 +18,15 @@ #include #include #include + +#if defined(ARDUINO_ARCH_ESP32) && defined(CONFIG_ARDUHAL_ESP_LOG) #include "esp32-hal-log.h" +#define LOG_TAG "" +#else +#include "esp_log.h" +static const char* LOG_TAG = "GeneralUtils"; +#endif + static const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" @@ -104,13 +112,14 @@ bool GeneralUtils::base64Encode(const std::string& in, std::string* out) { * * Amount of free RAM */ void GeneralUtils::dumpInfo() { + size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); esp_chip_info_t chipInfo; esp_chip_info(&chipInfo); - log_v("--- dumpInfo ---"); - log_v("Free heap: %d", heap_caps_get_free_size(MALLOC_CAP_8BIT)); - log_v("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); - log_v("ESP-IDF version: %s", esp_get_idf_version()); - log_v("---"); + ESP_LOGV(LOG_TAG, "--- dumpInfo ---"); + ESP_LOGV(LOG_TAG, "Free heap: %d", freeHeap); + ESP_LOGV(LOG_TAG, "Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); + ESP_LOGV(LOG_TAG, "ESP-IDF version: %s", esp_get_idf_version()); + ESP_LOGV(LOG_TAG, "---"); } // dumpInfo @@ -228,7 +237,7 @@ void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { if (index % 16 == 0) { strcpy(hexBuf, hex.str().c_str()); strcpy(asciiBuf, ascii.str().c_str()); - log_v("%s %s", hexBuf, asciiBuf); + ESP_LOGV(tag, "%s %s", hexBuf, asciiBuf); hex.str(""); ascii.str(""); } @@ -240,8 +249,8 @@ void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { } strcpy(hexBuf, hex.str().c_str()); strcpy(asciiBuf, ascii.str().c_str()); - log_v("%s %s", hexBuf, asciiBuf); - //log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + ESP_LOGV(tag, "%s %s", hexBuf, asciiBuf); + //ESP_LOGV(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); } FreeRTOS::sleep(1000); } @@ -263,7 +272,7 @@ void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { } index++; if (index % 16 == 0) { - log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + ESP_LOGV(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); hex.str(""); ascii.str(""); } @@ -273,7 +282,7 @@ void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { hex << " "; index++; } - log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); + ESP_LOGV(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); } FreeRTOS::sleep(1000); } @@ -293,8 +302,8 @@ void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { char tempBuf[80]; uint32_t lineNumber = 0; - log_v(" 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f"); - log_v(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); + ESP_LOGV(LOG_TAG, " 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f"); + ESP_LOGV(LOG_TAG, " -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); strcpy(ascii, ""); strcpy(hex, ""); uint32_t index = 0; @@ -309,7 +318,7 @@ void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { strcat(ascii, tempBuf); index++; if (index % 16 == 0) { - log_v("%.4x %s %s", lineNumber * 16, hex, ascii); + ESP_LOGV(LOG_TAG, "%.4x %s %s", lineNumber * 16, hex, ascii); strcpy(ascii, ""); strcpy(hex, ""); lineNumber++; @@ -320,7 +329,7 @@ void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { strcat(hex, " "); index++; } - log_v("%.4x %s %s", lineNumber * 16, hex, ascii); + ESP_LOGV(LOG_TAG, "%.4x %s %s", lineNumber * 16, hex, ascii); } } // hexDump @@ -331,12 +340,9 @@ void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { * @return A string representation of the IP address. */ std::string GeneralUtils::ipToString(uint8_t *ip) { - auto size = 16; - char *val = (char*)malloc(size); - snprintf(val, size, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); - std::string res(val); - free(val); - return res; + std::stringstream s; + s << (int) ip[0] << '.' << (int) ip[1] << '.' << (int) ip[2] << '.' << (int) ip[3]; + return s.str(); } // ipToString @@ -349,14 +355,11 @@ std::string GeneralUtils::ipToString(uint8_t *ip) { std::vector GeneralUtils::split(std::string source, char delimiter) { // See also: https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g std::vector strings; - std::size_t current, previous = 0; - current = source.find(delimiter); - while (current != std::string::npos) { - strings.push_back(trim(source.substr(previous, current - previous))); - previous = current + 1; - current = source.find(delimiter, previous); + std::istringstream iss(source); + std::string s; + while (std::getline(iss, s, delimiter)) { + strings.push_back(trim(s)); } - strings.push_back(trim(source.substr(previous, current - previous))); return strings; } // split