From cc614d0ed10053fa2cf527cb2711ddbf065da5a2 Mon Sep 17 00:00:00 2001 From: Paul Vint Date: Fri, 5 Apr 2019 12:41:02 -0400 Subject: [PATCH 1/2] Reflects change in esp_bt_gap_set_scan_mode in esp-idf --- libraries/BluetoothSerial/src/BluetoothSerial.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.cpp b/libraries/BluetoothSerial/src/BluetoothSerial.cpp index a8332b8bc99..499a6f676c4 100644 --- a/libraries/BluetoothSerial/src/BluetoothSerial.cpp +++ b/libraries/BluetoothSerial/src/BluetoothSerial.cpp @@ -158,7 +158,7 @@ static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) { case ESP_SPP_INIT_EVT: log_i("ESP_SPP_INIT_EVT"); - esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); + esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE); esp_spp_start_srv(ESP_SPP_SEC_NONE, ESP_SPP_ROLE_SLAVE, 0, _spp_server_name); xEventGroupSetBits(_spp_event_group, SPP_RUNNING); break; From ec2333dcd28b1356087e21d689e3ec25aec35c94 Mon Sep 17 00:00:00 2001 From: Paul Vint Date: Mon, 23 Sep 2019 09:28:04 -0400 Subject: [PATCH 2/2] merge upstream --- libraries/BLE/src/BLEAddress.cpp | 15 +- libraries/BLE/src/BLEAdvertisedDevice.cpp | 48 ++--- libraries/BLE/src/BLEAdvertising.cpp | 90 ++++---- libraries/BLE/src/BLEAdvertising.h | 1 - libraries/BLE/src/BLEBeacon.cpp | 8 +- libraries/BLE/src/BLECharacteristic.cpp | 189 +++++++--------- libraries/BLE/src/BLECharacteristic.h | 16 -- libraries/BLE/src/BLECharacteristicMap.cpp | 15 +- libraries/BLE/src/BLEClient.cpp | 83 ++++---- libraries/BLE/src/BLEClient.h | 2 +- libraries/BLE/src/BLEDescriptor.cpp | 43 ++-- libraries/BLE/src/BLEDescriptorMap.cpp | 15 +- libraries/BLE/src/BLEDevice.cpp | 119 ++++++----- libraries/BLE/src/BLEEddystoneTLM.cpp | 100 +++++---- libraries/BLE/src/BLEEddystoneURL.cpp | 6 +- libraries/BLE/src/BLEExceptions.cpp | 2 +- libraries/BLE/src/BLERemoteCharacteristic.cpp | 77 +++---- libraries/BLE/src/BLERemoteDescriptor.cpp | 38 ++-- libraries/BLE/src/BLERemoteService.cpp | 63 +++--- libraries/BLE/src/BLEScan.cpp | 37 ++-- libraries/BLE/src/BLEServer.cpp | 54 ++--- libraries/BLE/src/BLEServer.h | 1 - libraries/BLE/src/BLEService.cpp | 65 +++--- libraries/BLE/src/BLEServiceMap.cpp | 13 +- libraries/BLE/src/BLEUUID.cpp | 79 ++++--- libraries/BLE/src/BLEUtils.cpp | 201 +++++++++--------- libraries/BLE/src/BLEValue.cpp | 17 +- libraries/BLE/src/FreeRTOS.cpp | 77 +++---- libraries/BLE/src/FreeRTOS.h | 2 - libraries/BLE/src/GeneralUtils.cpp | 56 ++--- 30 files changed, 758 insertions(+), 774 deletions(-) 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 1c341cf2412..3f55e8c899d 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; @@ -243,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); @@ -302,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; @@ -315,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; @@ -328,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; } @@ -340,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 @@ -380,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 @@ -392,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 @@ -404,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 @@ -415,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 @@ -444,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 @@ -475,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 @@ -484,29 +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()) { - res += ", serviceUUID: " + getServiceUUID().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() { diff --git a/libraries/BLE/src/BLEAdvertising.cpp b/libraries/BLE/src/BLEAdvertising.cpp index ec73400c6d8..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. @@ -111,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 @@ -140,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 @@ -157,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 /** @@ -174,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) @@ -186,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; @@ -205,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; } } @@ -216,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; } } @@ -231,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 @@ -244,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. @@ -364,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 @@ -378,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 @@ -467,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 @@ -488,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: { @@ -504,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 be85371ec64..3128b50f1e3 100644 --- a/libraries/BLE/src/BLEAdvertising.h +++ b/libraries/BLE/src/BLEAdvertising.h @@ -58,7 +58,6 @@ class BLEAdvertising { 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); 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 11636921b77..e3402874298 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: @@ -221,7 +226,9 @@ void BLECharacteristic::handleGATTServerEvent( 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. + if (m_pCallbacks != nullptr) { + m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. + } } else { m_value.cancel(); } @@ -231,7 +238,7 @@ void BLECharacteristic::handleGATTServerEvent( 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)); + ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); } break; } // ESP_GATTS_EXEC_WRITE_EVT @@ -281,11 +288,11 @@ void BLECharacteristic::handleGATTServerEvent( setValue(param->write.value, param->write.len); } - 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,11 +309,11 @@ 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) { + if (m_pCallbacks != nullptr && param->write.is_prep != true) { m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. } } // Match on handles. @@ -354,9 +361,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 +384,6 @@ 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); - std::string value = m_value.getValue(); if (value.length() + 1 > maxOffset) { @@ -395,12 +398,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 +416,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 +431,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 +456,7 @@ void BLECharacteristic::handleGATTServerEvent( // event. m_descriptorMap.handleGATTServerEvent(event, gatts_if, param); - log_v("<< handleGATTServerEvent"); + ESP_LOGD(LOG_TAG, "<< handleGATTServerEvent"); } // handleGATTServerEvent @@ -461,9 +468,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,18 +481,15 @@ 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; } @@ -495,53 +499,38 @@ void BLECharacteristic::notify(bool is_notification) { BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); 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 +542,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 +556,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 +573,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 +584,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 +598,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 +612,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 +628,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 @@ -710,7 +693,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 { @@ -724,7 +707,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 { @@ -738,18 +721,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 @@ -761,8 +743,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 @@ -771,31 +753,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..5eb1e8d6dde 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; @@ -119,7 +117,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 +129,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..0e552ece5f8 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 @@ -68,14 +75,14 @@ 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_haveServices = false; - log_v("<< clearServices"); + ESP_LOGD(LOG_TAG, "<< clearServices"); } // clearServices /** @@ -93,7 +100,7 @@ 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()); + ESP_LOGD(LOG_TAG, ">> 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. @@ -104,7 +111,7 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { // 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)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return false; } @@ -121,12 +128,12 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { 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 +143,13 @@ 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_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,14 +161,14 @@ 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"); + ESP_LOGI(LOG_TAG, "SERVICE CHANGED"); break; case ESP_GATTC_CLOSE_EVT: { @@ -184,11 +191,10 @@ void BLEClient::gattClientEventHandler( if (m_pClientCallbacks != nullptr) { m_pClientCallbacks->onDisconnect(this); } + BLEDevice::removePeerDevice(m_appId, true); 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); break; } // ESP_GATTC_DISCONNECT_EVT @@ -228,7 +234,7 @@ void BLEClient::gattClientEventHandler( 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; break; @@ -237,7 +243,7 @@ void BLEClient::gattClientEventHandler( 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){ @@ -257,17 +263,17 @@ void BLEClient::gattClientEventHandler( 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); + ESP_LOGE(LOG_TAG, "search service failed, error status = %x", p_data->search_cmpl.status); break; } #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); @@ -337,9 +343,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 +354,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 +380,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 +393,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 +416,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 +428,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 +445,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 +522,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..1b8144d50b3 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" 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 db45d07bd13..cb2db41f8bf 100644 --- a/libraries/BLE/src/BLEDevice.cpp +++ b/libraries/BLE/src/BLEDevice.cpp @@ -34,7 +34,7 @@ #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"; @@ -63,13 +63,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"); + ESP_LOGD(LOG_TAG, "<< createClient"); return m_pClient; } // createClient @@ -79,14 +79,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(); m_pServer->createApp(m_appId++); - log_v("<< createServer"); + ESP_LOGD(LOG_TAG, "<< createServer"); return m_pServer; } // createServer @@ -103,7 +103,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()); @@ -150,7 +150,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); @@ -194,16 +194,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)); @@ -211,8 +211,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()); @@ -225,7 +225,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()); @@ -240,9 +240,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); } @@ -250,13 +250,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); @@ -305,12 +305,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 @@ -322,12 +322,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 @@ -349,7 +349,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; } @@ -359,20 +359,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 @@ -382,7 +382,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; } } @@ -390,21 +390,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 @@ -412,14 +412,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; }; @@ -427,7 +427,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 @@ -450,12 +450,12 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; * @param [in] powerLevel. */ /* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel) { - log_v(">> setPower: %d", 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 @@ -466,7 +466,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); @@ -479,8 +479,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 @@ -489,12 +490,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 @@ -503,12 +504,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 /* @@ -532,14 +533,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; } @@ -557,16 +558,16 @@ 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 /* multi connect support */ @@ -580,7 +581,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); @@ -596,7 +597,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, @@ -607,7 +608,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); } diff --git a/libraries/BLE/src/BLEEddystoneTLM.cpp b/libraries/BLE/src/BLEEddystoneTLM.cpp index 1ab794932e2..a92bcdb2b40 100644 --- 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/BLEEddystoneURL.cpp b/libraries/BLE/src/BLEEddystoneURL.cpp index 19a56b28b79..af3b674cbc8 100644 --- 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/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/BLERemoteCharacteristic.cpp b/libraries/BLE/src/BLERemoteCharacteristic.cpp index 840076f8f2f..b6d36d886fc 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,16 +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; retrieveDescriptors(); // Get the descriptors for this characteristic - log_v("<< BLERemoteCharacteristic"); + ESP_LOGD(LOG_TAG, "<< BLERemoteCharacteristic"); } // BLERemoteCharacteristic @@ -160,7 +166,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; @@ -247,7 +253,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. @@ -271,13 +277,13 @@ void BLERemoteCharacteristic::retrieveDescriptors() { } 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( @@ -291,7 +297,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 @@ -308,8 +314,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 @@ -320,15 +326,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 @@ -395,12 +401,12 @@ uint8_t BLERemoteCharacteristic::readUInt8() { * @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"); @@ -415,7 +421,7 @@ std::string BLERemoteCharacteristic::readValue() { 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 ""; } @@ -423,7 +429,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 @@ -435,7 +441,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. @@ -449,7 +455,7 @@ 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}; @@ -465,7 +471,7 @@ 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}; @@ -475,7 +481,7 @@ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, m_semaphoreRegForNotifyEvt.wait("registerForNotify"); - log_v("<< registerForNotify()"); + ESP_LOGD(LOG_TAG, "<< registerForNotify()"); } // registerForNotify @@ -501,16 +507,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 @@ -546,12 +547,12 @@ void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { */ void 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"); + throw BLEDisconnectedException(); } m_semaphoreWriteCharEvt.take("writeValue"); @@ -567,13 +568,13 @@ void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool resp ); if (errRc != ESP_OK) { - log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); return; } m_semaphoreWriteCharEvt.wait("writeValue"); - log_v("<< writeValue"); + ESP_LOGD(LOG_TAG, "<< writeValue"); } // writeValue /** diff --git a/libraries/BLE/src/BLERemoteDescriptor.cpp b/libraries/BLE/src/BLERemoteDescriptor.cpp index 54e59759a04..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, @@ -50,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"); @@ -68,7 +77,7 @@ std::string BLERemoteDescriptor::readValue() { 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 ""; } @@ -76,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 @@ -113,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 @@ -129,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( @@ -146,9 +152,9 @@ void BLERemoteDescriptor::writeValue(uint8_t* data, size_t length, bool response 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 diff --git a/libraries/BLE/src/BLERemoteService.cpp b/libraries/BLE/src/BLERemoteService.cpp index 754e8ac22d5..c2b7d344fd9 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()"); } @@ -97,7 +103,7 @@ void BLERemoteService::gattClientEventHandler( &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)); + ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); break; } @@ -159,14 +165,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, ">> getCharacteristics() 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 = 10; // 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(), @@ -182,7 +188,7 @@ void BLERemoteService::retrieveCharacteristics() { } 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 +196,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,7 +212,7 @@ void BLERemoteService::retrieveCharacteristics() { } // Loop forever (until we break inside the loop). m_haveCharacteristics = true; // Remember that we have received the characteristics. - log_v("<< getCharacteristics()"); + ESP_LOGD(LOG_TAG, "<< getCharacteristics()"); } // getCharacteristics @@ -215,14 +221,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 @@ -230,6 +236,7 @@ std::map* BLERemoteService::getCharacteri * @brief This function is designed to get characteristics map when we have multiple characteristics with the same UUID */ void BLERemoteService::getCharacteristics(std::map* pCharacteristicMap) { +#pragma GCC diagnostic ignored "-Wunused-but-set-parameter" pCharacteristicMap = &m_characteristicMapByHandle; } // Get the characteristics map. @@ -258,8 +265,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 @@ -272,9 +279,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 @@ -307,9 +314,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 @@ -318,25 +325,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..d851a47a123 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); @@ -192,7 +201,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 +218,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 +226,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 +256,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 +264,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 +284,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 +#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 +73,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 +89,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 +149,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) { @@ -268,7 +277,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 @@ -278,11 +287,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 @@ -315,9 +324,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 /** @@ -335,34 +344,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 */ @@ -412,9 +421,4 @@ void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, conn_params.timeout = timeout; // timeout = 400*10ms = 4000ms esp_ble_gap_update_conn_params(&conn_params); } - -void BLEServer::disconnect(uint16_t connId) { - esp_ble_gatts_close(m_gatts_if, connId); -} - #endif // CONFIG_BT_ENABLED diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h index d2f8038d268..d39d8bfee1a 100644 --- a/libraries/BLE/src/BLEServer.h +++ b/libraries/BLE/src/BLEServer.h @@ -72,7 +72,6 @@ class BLEServer { BLEService* getServiceByUUID(const char* uuid); BLEService* getServiceByUUID(BLEUUID uuid); bool connect(BLEAddress address); - void disconnect(uint16_t connId); uint16_t m_appId; void updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout); 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 index a8a1f8e567c..cf4f75f4419 100644 --- 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 a1ec2148df5..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[5]; - snprintf(hex, sizeof(hex), "%04x", 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 = 35; - 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..5cd55f9324b 100644 --- a/libraries/BLE/src/BLEUtils.cpp +++ b/libraries/BLE/src/BLEUtils.cpp @@ -23,7 +23,14 @@ #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 = "BLEUtils"; // Tag for logging. +#endif + /* static std::map g_addressMap; @@ -604,32 +611,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 @@ -660,23 +661,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 @@ -743,7 +744,7 @@ const char* BLEUtils::advTypeToString(uint8_t advType) { 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 +779,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 +809,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 @@ -948,7 +949,7 @@ std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType 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 @@ -1046,14 +1047,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 +1063,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 +1072,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 +1081,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 +1096,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 +1112,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 +1128,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 +1141,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 +1154,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 +1175,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 +1192,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 +1204,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 +1219,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 +1228,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 +1243,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 +1257,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 +1281,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 +1292,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 +1306,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 +1320,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 +1346,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 +1355,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 +1376,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 +1396,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 +1416,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 +1427,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 +1440,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 +1452,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 +1466,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 +1480,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 +1498,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 +1528,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 +1545,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 +1553,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 +1571,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 +1579,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 +1602,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 +1633,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 +1644,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 +1662,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 +1682,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 +1702,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 +1712,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 @@ -1743,7 +1744,7 @@ const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { 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 @@ -1814,7 +1815,7 @@ const char* BLEUtils::gapEventToString(uint32_t eventType) { 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 +1855,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 @@ -2032,7 +2025,7 @@ const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { 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 895ba267f81..1f12c88a51e 100644 --- a/libraries/BLE/src/FreeRTOS.cpp +++ b/libraries/BLE/src/FreeRTOS.cpp @@ -12,7 +12,14 @@ #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,45 +67,15 @@ 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()); + if (m_usePthreads) { pthread_mutex_lock(&m_pthread_mutex); } else { xSemaphoreTake(m_semaphore, portMAX_DELAY); } - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } - - log_v("<< 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); - } + m_owner = owner; if (m_usePthreads) { pthread_mutex_unlock(&m_pthread_mutex); @@ -106,8 +83,9 @@ bool FreeRTOS::Semaphore::timedWait(std::string owner, uint32_t timeoutMs) { xSemaphoreGive(m_semaphore); } - log_v("<< wait: Semaphore %s released: %d", toString().c_str(), ret); - return ret; + ESP_LOGV(LOG_TAG, "<< wait: Semaphore released: %s", toString().c_str()); + m_owner = std::string(""); + return m_value; } // wait @@ -116,8 +94,7 @@ FreeRTOS::Semaphore::Semaphore(std::string name) { if (m_usePthreads) { pthread_mutex_init(&m_pthread_mutex, nullptr); } else { - m_semaphore = xSemaphoreCreateBinary(); - xSemaphoreGive(m_semaphore); + m_semaphore = xSemaphoreCreateMutex(); } m_name = name; @@ -140,9 +117,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 +127,7 @@ void FreeRTOS::Semaphore::give() { // FreeRTOS::sleep(10); // #endif + m_owner = std::string(""); } // Semaphore::give @@ -186,7 +162,7 @@ void FreeRTOS::Semaphore::giveFromISR() { * @return True if we took the semaphore. */ bool FreeRTOS::Semaphore::take(std::string owner) { - log_d("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 +171,9 @@ bool FreeRTOS::Semaphore::take(std::string owner) { } m_owner = owner; if (rc) { - log_d("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 +187,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 +196,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 +210,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 1c62af9391c..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" @@ -107,11 +115,11 @@ 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", freeHeap); - 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 @@ -229,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(""); } @@ -241,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); } @@ -264,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(""); } @@ -274,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); } @@ -294,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; @@ -310,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++; @@ -321,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 @@ -332,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 @@ -350,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