Compare commits

...

294 Commits

Author SHA1 Message Date
edfc838bef [Bugfix] allow peripheral and central roles without broadcast/scan. 2025-06-20 10:41:28 -06:00
f1ead9959d Bump idf_component version 2025-06-11 11:40:42 -06:00
b30421c19d Fix library.json version 2025-06-11 11:34:10 -06:00
bdb868d125 Release 2.3.1 2025-06-11 11:14:52 -06:00
503939c66f Update docs 2025-06-11 11:11:58 -06:00
2640c44b45 Support passing data directly from NimBLEBeacon.getData() to NimBLEAdvertisementData.setManufacturerData() 2025-06-11 11:11:11 -06:00
fec2d7a279 [Bugfix] NimBLEScan delete.
Calling NimBLEDevice::deint with the `clearAll` parameter set to `true` will delete the scan and any scan results but it was calling `clearall` which uses critical sections, this could cause a crash because the stack has already been de-initialized.
2025-06-09 17:13:30 -06:00
e2cee2d994 Fix server client read/write not returning when encryption is used.
When the client created by the server reads or writes to an attribute and it triggers a pairing action the task will not be released because the client does not get the event.
This passes the event to the client to prevent the task from being hung.
2025-06-09 17:13:12 -06:00
39f974625c Fix builds when exluding roles 2025-06-02 18:06:40 -06:00
169290f047 Allow esp_wifi_remote >= 0.5.3
`esp_wifi_remote` >= v0.10.0 is necessary to use esp-nimble-cpp with the latest ESP-IDF master branch.
2025-05-21 11:14:43 -06:00
067274973d Release 2.3.0 2025-05-19 16:54:59 -06:00
30877344bd Add support for esp32c5 2025-05-19 14:50:28 -06:00
68dd0b37b5 [Bugfix] Attribute getValue fails with some data types 2025-05-19 14:28:53 -06:00
e615deb1af Add Scan duplicate cache reset time feature.
Adds the ability to set a time for the scan duplicate filter cache to reset which will start reporting devices previously seen again.
2025-05-19 13:21:26 -06:00
e29d1ce3cf Refactor L2Cap (style) 2025-05-05 18:30:37 -06:00
a5702746c5 Add missed pointer parameter to const ref fix 2025-05-05 18:11:01 -06:00
f8e8830112 [Bugfix] Incorrectly passing a pointers to a funtion taking const reference
Passing a pointer to to NimBLEUtils::taskWait and NimBLEUtils::taskRelease would compile due to the first argument in the constructor being
a pointer to void, a surprisingly not a compiler error in this instance. Also does not cause a crash but instead a hung task when called.
2025-05-05 18:06:34 -06:00
80def6663b Fix preprocessor statement 2025-05-05 14:38:26 -06:00
7a8d10bb71 Set max connections correctly for esp32s3/c3 2025-05-05 14:38:26 -06:00
ce1b8bc2ec Fix build with non-esp devices 2025-05-05 14:38:07 -06:00
dadbc0d423 [Bugfix] Correct NimBLEClient array initialization. 2025-05-03 15:00:43 -06:00
da31f90436 Fix build when host based privacy is enabled without connection roles 2025-05-03 14:59:24 -06:00
e55ad9019c Introduce L2CAP infrastructure.
L2CAP is the underlying technology powering GATT.
BLE 5 exposes L2CAP COC (Connection Oriented Channels)
allowing a streaming API that leads to much higher throughputs
than you can achieve with updating GATT characteristics.

The patch follows the established infrastructure very closely.
The main components are:

- `NimBLEL2CAPChannel`, encapsulating an L2CAP COC.
- `NimBLEL2CAPServer`, encapsulating the L2CAP service.
- `Examples/L2CAP`, containing a client and a server application.

Apart from these, only minor adjustments to the existing code was
necessary.
2025-04-28 10:54:32 -06:00
59e111ab55 Allow PHY updates without enabling extended advertising. 2025-04-25 09:07:23 -06:00
e00dd88add [Bugfix] notify/indicate incorrectly returning success with custom value
When sending an array of data with a length value the wrong overload/template was being
used and the length value was being interpreted as the connection handle.

This updates the template to disable it when an array is passed and will now also report the error.
2025-04-24 17:08:19 -06:00
e18d78678f [Bugfix] Explicit getValue template returning nil value with convertable types. 2025-04-24 17:07:42 -06:00
54ec3f4c92 [Bugfix] Clear attribute value when zero length value is written. 2025-04-24 17:07:20 -06:00
9ac9551a2b fix(Utils): Update gapEventToString switch case 2025-04-22 16:08:57 -06:00
0172cb4b39 Only ignore scan discovery events when scan is stopped. 2025-04-14 08:52:32 -06:00
856adebad5 Fix potential exception when scan is restarted.
If the scan is restarted in NimBLEScan::start, there is a chance that a result from
the previous scan arrives and the device is deleted when the callback is called.
This change ignores any results that come when the scan has stopped.
2025-04-14 08:39:28 -06:00
033c7c27ad Fix extended server example - data too long error 2025-04-13 16:06:34 -06:00
d134276d2d Bugfix - Characteristic onRead callback not called.
Fixes detection of the original read request vs a followup read for characteristic values greater than MTU - 3.
2025-04-13 15:13:53 -06:00
01976cec54 [Bugfix] Incorrect onSubscribe value when indications are set. 2025-03-28 16:56:54 -06:00
723cdf0a66 Merge pull request #312 from iranl/patch-3
Fix ESP32-P4 compile when using Arduino as an ESP-IDF component
2025-03-10 18:30:44 -06:00
148087c508 Fix ESP32-P4 compile when using Arduino as an ESP-IDF component 2025-03-02 21:46:34 +01:00
88c5d0c7b7 Bump docs version 2025-02-28 14:56:46 -07:00
a6c03a2aaa Release 2.2.1 2025-02-28 09:51:31 -07:00
9df8445241 [Bugfix] Check if remote descriptor vector has increased. 2025-02-25 17:08:01 -07:00
e5f4d52a5a Update changelog 2025-02-25 14:26:57 -07:00
7ef247c8db Partially revert Commit 052c0a04 to restore client connect with device parameter. 2025-02-25 14:23:25 -07:00
c582c8c67e Release 2.2.0 2025-02-24 17:58:21 -07:00
74b5c59887 fix(NimBLEDevice): fix crash when pairing table is full
* Add missing definition for default device callbacks (which prevents calling the `setDeviceCallbacks` method)
* Ensure `m_pDeviceCallbacks` inital value is set to `&defaultDeviceCallbacks` to prevent crash when pairing table is full

After #295 any time the pairing table fills up, the device will crash on the next pairing attempt.
2025-02-13 06:58:54 -07:00
60efffdf2b [BugFix] Provide default task data when retrieving all descriptors.
* Update the descriptor filter when trying again with different UUID sizes.
2025-02-08 15:08:32 -07:00
b6379848ae change(2904|AdvData): Add missing parameter name in declarations 2025-02-05 15:15:49 -07:00
b29919df96 feat(Device): Implement store status handler 2025-02-05 15:14:42 -07:00
052c0a0455 feat(AdvDevice): Add convenience operator to NimBLEAddress 2025-02-05 14:07:10 -07:00
784e6f30fa Merge pull request #301 from thekurtovic/feat-log-condition
feat(Log): Add macros for conditional log print and rc handling
2025-01-28 14:59:53 -05:00
5490cef129 feat(Log): Add macros for conditional log print and rc handling 2025-01-28 13:40:19 -05:00
459e8c9fcd Release 2.1.1 2025-01-26 18:23:11 -07:00
ffa8414747 refactor(RemoteChar): Reduce nesting
* Renamed desc_filter_t to NimBLEDescriptorFilter
* Added NimBLERemoteDescriptor pointer to NimBLEDescriptorFilter
* retrieveDescriptors changed to take NimBLEDescriptorFilter pointer
* General cleanup
2025-01-26 11:28:48 -07:00
8130f88be8 Rename config macros to enable duplicate scan options on s3/c3 2025-01-26 11:09:36 -07:00
c39e288c3e Workaround for P4 CI build error. 2025-01-26 09:41:25 -07:00
8158a16fbf Fix characteristic discovery with no descriptors.
Avoid discovery of descriptors if there are no handles remaining.
2025-01-15 18:37:47 -07:00
57fe9cb77f Release 2.1.0 2025-01-12 19:17:10 -07:00
e6249623d5 Fix race condition in NimBLEScan::clearResults.
If clear results is called from more than one task a race condition exists that may delete the same advertisedDevice twice.
This prevents this by swapping with an empty vector and testing for empty before freeing the resources.
2025-01-12 18:11:57 -07:00
a9578637cb avoid unused-variable warning
Avoid warning when compiled with All warnings enabled.
.../src/NimBLEScan.cpp: In member function 'void NimBLEScanResults::dump() const':
.../src/NimBLEScan.cpp:481:22: warning: unused variable 'dev' [-Wunused-variable]
  481 |     for (const auto& dev : m_deviceVec) {
      |                      ^~~
2025-01-12 15:44:58 -07:00
765193f223 Fix incorrect TX power setting for advertising.
* Adds a new enum class to specify the tx power type to set (unused by non-esp devices).
* When all type is specified it is now ensured that all the tx power types are set to the specified level.
* Correctly sets the power level advertised for extended advertising with legacy pdu selected.
2025-01-12 15:37:44 -07:00
3b019a0c9c If privacy is not configured do not share ID keys. 2025-01-12 15:05:11 -07:00
5ac7272f5d change(NimBLEAddress): Prefer sizeof with parenthesis 2025-01-10 09:51:41 -07:00
4d8ab46e56 Update new user guide 2025-01-10 09:11:49 -07:00
8468bb50dc NimBLEAddress default to including delimiter in string format 2025-01-08 15:24:08 -07:00
1088ad8fe1 NimBLEAddress::toString allow formatting to be configured 2025-01-07 11:37:01 -07:00
0b543d9f62 Fix crash when retrieving descriptors.
If more than one descriptor is found the task would be released beofore the process completed causing a race condition.
2025-01-06 15:28:04 -07:00
fa468d360a Release 2.0.3 2025-01-05 15:11:08 -07:00
2759b1b69d Increase timeout paramter in server example. 2025-01-05 14:31:43 -07:00
1a0b7a8e31 Add missing migration information to docs. 2025-01-05 14:24:28 -07:00
1d01af0f8c NimBLEAdvertisementData emit error on failure, remove magic numbers. 2025-01-05 09:23:32 -07:00
f7d3c5e0c2 Fix characteristic value unable to be updated in callback 2025-01-05 08:57:01 -07:00
bc2bc35a8a Fix advertising data not set if scan response enabled later. 2025-01-05 08:56:57 -07:00
15cb6bc7c6 Add checks in case NIMBLE_CPP_DEBUG_ASSERT is not defined. 2025-01-04 15:20:01 -07:00
aae70dfd21 Allow the same report ID in multiple input/output/feature reports 2025-01-04 15:16:01 -07:00
ad12a48e9e Fix build error when using platformio library 2025-01-02 08:29:44 -07:00
09297fb72a NimBLEScan increment m_callbackSent before callback.
Fixes heap corruption observed on CONFIG_HEAP_POISONING_COMPREHENSIVE.
2025-01-02 08:29:17 -07:00
b50a1b50b1 Release 2.0.2 2024-12-21 17:04:48 -07:00
954ba0b5a7 Update Changelog 2024-12-21 16:05:38 -07:00
015217c764 Fix compile error for advertiser only config. 2024-12-21 15:47:13 -07:00
9a1ae677b8 NimBLELog allow custom log level colors. 2024-12-20 13:32:34 -07:00
6ee5174ba0 Fix NimBLEHIDDevice not being able to create more than one in/out/feature report + temporal coupling 2024-12-20 13:29:50 -07:00
e843c6811c Fix crash that could occur when server reconnects
* Update to not change services if they have not actually changed when starting the server
Closes #270
2024-12-20 13:25:00 -07:00
0d13044703 Release 2.0.1 2024-12-16 18:35:21 -07:00
cfca3e7500 Add missing NimBLEUtils and NimBLEConnInfo includes to NimBLEDevice.h
In some cases compilation of examples would fail due to missing these headers so they should be included in NimBLEDevice.h
2024-12-15 14:15:16 -07:00
3c80c950ae Update changelog. 2024-12-15 10:06:39 -07:00
182e3bb8a3 Fix NimBLEHIDDevice output report returning incorrect characteristic. (#805)
The input and output report characteristics share the same UUID and the `getOutputReport` was returning the input report characteristic.
This change will return the correct characteristic by finding it with the index parameter.
2024-12-15 10:02:47 -07:00
a627007a31 Fix compiling errors when central is disabled.
* Fix missing member error 'm_pClient' in NimBLEServer
2024-12-15 09:35:28 -07:00
a6ed1933bc Release 2.0.0 2024-12-14 16:25:52 -07:00
675d6bbf0d [BREAKING] Remove NimBLEAddress type default value.
When constructing a NimBLEAddress via string or other non `ble_addr_t` parameters it is important that the address type be specified.
This will help prevent issues where applications are not able to connect or identify scanned devices when comparing their addresses.
2024-12-14 13:56:50 -07:00
8753782425 Fix example 2024-12-13 21:25:27 -07:00
af1872623e Silence compiler warnings 2024-12-13 15:25:07 -07:00
62de1b23fa Add library.json
* Add fields for idf registry
2024-12-13 12:06:45 -07:00
57e583c17a [BREAKING] Refactor NimBLELog
* Cleanup style.
* Remove NIMBLE_LOGC as it's use was limited to assertions.
* Add delay after assert printf to allow time to display the message.
2024-12-13 12:06:07 -07:00
5afb5af81e Update license 2024-12-12 20:41:04 -07:00
2d1e33a75e Prepare for v2 release 2024-12-12 08:46:42 -07:00
152cc9d1b9 Fixup client logs 2024-12-10 19:04:47 -07:00
09e8eede94 Fixup server logs 2024-12-10 14:11:35 -07:00
49769f4aeb Update examples 2024-12-10 13:15:43 -07:00
e4d2e991f1 Fix crash when peer disconnects from the server.
If the server has not created a client instance then the device would crash when the peer disconnects due to nullptr access.
2024-12-09 09:54:47 -07:00
6d10f2f88f [BREAKING] - Refactor NimBLEHIDDevice
* General code cleanup.
* All functions that return a characteristic or service have been renamed to have a `get` prefix to better represent their function.
* All functions that set a value have been renamed with the prefix `set` to better represent their functionality.
* Added an `bool notify` parameter to `setBatteryLevel`, which if `true`, will send a notification of the value to the peer.
2024-12-08 17:02:17 -07:00
a874e502c5 Update doxygen 2024-12-08 15:44:39 -07:00
0c22666e51 Remove improvements and updates.
Removed as the changelog contians the notes and the class info has the details.
2024-12-08 15:44:39 -07:00
eba6d8bfbb Update migration guide 2024-12-08 15:44:39 -07:00
0e5eb9c55f 1.x to 2.x migration guide 2024-12-08 15:44:39 -07:00
45db17f948 Update changelog 2024-12-08 15:44:39 -07:00
c547733194 Remove NimBLEServer::getPeerNameOnConnect
With the implementation of the NimBLEServer::getClient function this is now redundant.
2024-12-05 16:03:33 -07:00
ac3d3575cc Add support for creating a NimBLEClient from a NimBLEServer peer.
This allows the NimBLEServer instance to create a NimBLEClient instance to read/write form/to a connected peer.
Only one instance is supported subsequent calls will overwrite the previous client connection information and data.
2024-12-05 16:03:33 -07:00
a55489fee2 Add a workaround for esp32s3 and esp32c3 tx power bug (#252)
* Add a workaround for esp32s3 and esp32c3 tx power bug

This adds a workaround to get the tx power when the function returns error due to a bug introduced in some versions of esp-idf.

* Added error checking, return value will be 0xFF if there was an error.
2024-12-04 10:46:33 -07:00
b5b46661e0 Fix compilation with esp32p4 (#253) 2024-12-03 08:47:41 -07:00
6c85cfa6c3 NimBLEDevice::get/setPower support full power range. (#229)
* Calculates the tx power level to and from dbm to `esp_power_level` types for esp32 devices.
* Add esp32 specific funtions `NimBLEDevice::setPowerLevel` and `NimBLEDevice::getPowerLevel` which take and return the related `esp_power_level* ` types.

---------

Co-authored-by: h2zero <powell.rg@gmail.com>
2024-12-02 15:19:44 -07:00
15392bf581 Add asynchronous client connection secure
* Adds parameter `rcPtr` to `NimBLEDevice::startSecurity`, default value works as the original method.
* * `rcPtr`: if not nullptr, will allow caller to obtain the internal return code.
* Adds parameter `async` to `NimBLEClient::secureConnection`, default value works as the original method.
* * `async`; if true, will send the secure command and return immediately with a true value for successfully sending the command, else false.
2024-12-02 09:54:18 -07:00
e0fe1668de [BREAKING] - Refactor NimBLEEddystoneTLM
* `NimBLEEddystoneTLM::BeaconData` struct is now public and usable by the application.
* `NimBLEEddystoneTLM::setTemp` now takes an `int16_t` parameter instead of float to be friendly to devices without floating point support.
* `NimBLEEddystoneTLM::getTemp` now returns `int16_t` to work with devices that don't have floating point support.
* `NimBLEEddystoneTLM::setData` now takes a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
* `NimBLEEddystoneTLM::getData` now returns a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
2024-12-01 16:00:44 -07:00
308b81e81a [BREAKING] Remove Eddystone URL
Removed Eddystone URL as it has been shutdown by google since 2021.
2024-12-01 16:00:28 -07:00
36d27a2413 [BREAKING] Refactor NimBLEBeacon
* General code cleanup
* The internal data struct type `BeaconData` is now public and can be used by the application.
* `NimBLEBeacon::setData` now takes `const NimBLEBeacon::BeaconData&` instead of `std::string`.
* Added overload for `NimBLEBeacon::setData` that takes a pointer to raw `uint8_t` data and length`.
* `NimBLEBeacon::getData` now returns `const NimBLEBeacon::BeaconData&` instead of `std::string`.
2024-12-01 16:00:10 -07:00
ecf1adc4d7 Fix compiler warnings for C++ versions < 17 2024-12-01 14:19:51 -07:00
b4fe046c56 Refactor 2904 descriptor
* General code cleanup.
* Added method `NimBLECharacteristic::create2904` which will specifically create a CPF(0x2904) descriptor.
2024-11-30 14:21:39 -07:00
47c3cd5b84 Refresh advertising data dynamically 2024-11-30 13:16:36 -07:00
2de3c31421 Make NimBLERemoteValueAttribute LOG_TAG static 2024-11-29 14:44:58 -07:00
70c6e89f19 Refactor service changed handling
This makes the services changes notification more accurate by waiting until the changes have taken effect and the server re-started before indicating the change.
2024-11-28 17:18:21 -07:00
a12f3d4785 Remove characteristic subscription tracking.
Removes tracking of client characteristic subscription status from `NimBLEServer` and `NimBLECharacteristic` and instead uses
the functions and tracking in the host stack.

* `NimBLECharacteristic::notify` and `NimBLECharacteristic::indicate` now return a `bool`, true = success.
2024-11-28 17:18:21 -07:00
d9178cfa9b [BREAKING] Refactor NimBLEServer
* General code cleanup
* `NimBLEServerCallbacks::onMTUChanged` renamed to `NimBLEServerCallbacks::onMTUChange` to be consistent with the client callback.
* `NimBLEServer::getPeerIDInfo` renamed to `NimBLEServer::getPeerInfoByHandle` to better describe it's use.
* Use a std::array to store client connection handles instead of std::vector to reduce memory allocation.
* `NimBLEServer::disconnect` now returns `bool`, true = success,  instead of `int` to be consistent with the rest of the library.
2024-11-28 17:18:21 -07:00
c4c9f7913a Add methods to set/get connection PHY's.
* Added `NimBLEDevice::setDefaultPhy` which will set the default preferred PHY for all connections.
* Added `NimBLEClient::updatePhy` to request a PHY change with a peer.
* Added `NimBLEClient::getPhy` to read the current connection PHY setting.
* Added `NimBLEServer::updatePhy` to request a PHY change with a peer.
* Added `NimBLEServer::getPhy` to read the PHY of a peer connection.
* Added callbacks:
* - `NimBLEClientCallbacks::onPhyUpdate`
* - `NimBLEServerCallbacks::onPhyUpdate`
 Which are called when the PHY update is complete.
2024-11-28 14:42:57 -07:00
3cb9adb61a Add extended scan features.
* Added new method `NimBLEScan::setScanPhy` to enable/disable the PHY's to scan on.
* Added new method `NimBLEScan::setScanPeriod` which will allow for setting a scan restart timer in the controller.
* Updated `NimBLEScan::start` to allow the command to be sent with updated parameters if already scanning.
* Added extended scan example.
* Removed storing and restarting of the scan on host reset as it is more appropriate to call the scanEnded callback instead.
2024-11-28 14:42:57 -07:00
db2fe36131 Refactor NimBLEExtAdvertising
* General code cleanup
* `NimBLEExtAdvertisement` : All functions that set data now return `bool`, true = success.
* Added new method, `NimBLEExtAdvertisement::removeData`, which will remove the data of the specified type from the advertisement.
* Added new method, `NimBLEExtAdvertisement::addServiceUUID`, which will append to the service uuids advertised.
* Added new method, `NimBLEExtAdvertisement::removeServiceUUID`, which will remove the service from the uuids advertised.
* Added new method, `NimBLEExtAdvertisement::removeServices`, which will remove all service uuids advertised.
* Added overloads for `NimBLEExtAdvertisement::setServiceData` with the parameters `const NimBLEUUID& uuid, const uint8_t* data, size_t length` and
  `const NimBLEUUID& uuid, const std::vector<uint8_t>& data`.
* Added new method, `NimBLEExtAdvertisement::getDataLocation`, which returns the location in the advertisment data of the type requested in parameter `uint8_t type`.
* Added new method, `toString` which returns a Hex string representation of the advertisement data.
2024-11-28 14:42:57 -07:00
4980e6a10a [BREAKING] - Refactor NimBLEAdvertising
* General code cleanup.
* `NimBLEAdvertisementData` moved to it's own .h and .cpp files.
* Added new method, `NimBLEAdvertising::setPreferredParams` that takes the min and max preferred connection parameters as an alternative for `setMinPreferred` and `setMaxPreferred`.
* Added new method, `NimBLEAdvertising::setAdvertisingInterval` Sets the advertisement interval for min and max to the same value instead of calling `setMinInterval` and `setMaxInterval` separately if there is not value difference.
* `NimBLEAdvertisementData` payload is now stored in `std::vector<uint8_t>` instead of `std::string`.
* `NimBLEAdvertisementData::getPayload` now returns `std::vector<uint8_t>` instead of `std::string`.
* `NimBLEAdvertisementData::addData` now takes either a `std::vector<uint8_t>` or `uint8_t* + length` instead of `std::string` or `char + length`.
* `NimBLEAdvertisementData::setName` now takes an optional `bool` parameter to indicate if the name is complete or incomplete, default = complete.
* `NimBLEAdvertising::start` No longer takes a callback pointer parameter, instead the new method `NimBLEAdvertising::setAdvertisingCompleteCallback` should be used.
* `NimBLEAdvertising::setAdvertisementType` has been renamed to `NimBLEAdvertising::setConnectableMode` to better reflect it's function.
* `NimBLEAdvertising::setScanResponse` has been renamed to `NimBLEAdvertising::enableScanResponse` to better reflect it's function.
* Scan response is no longer enabled by default.
* Added new method, `NimBLEAdvertising::setDiscoverableMode` to allow applications to control the discoverability of the advertiser.
* Advertising the name and TX power of the device will no longer happen by default and should be set manually by the application.
* Added overload for `NimBLEAdvertising::setManufacturerData` that takes a `const uint8_t*` and , size_t` paramter.
* Added overload for `NimBLEAdvertising::setServiceData` that takes `const NimBLEUUID& uuid`, ` const uint8_t* data`, ` size_t length` as parameters.
* Added overload for `NimBLEAdvertising::setServiceData` that takes `const NimBLEUUID& uuid`, `const std::vector<uint8_t>&` as parameters.
* All `NimBLEAdvertisementData` functions that change data values now return `bool`, true = success.
* All `NimBLEAdvertising` functions that change data values now return `bool`, true = success.
* `NimBLEAdvertising::setMinPreferred` and `NimBLEAdvertising::setMaxPreferred` have been removed, use `NimBLEAdvertising::setPreferredParams` instead.
* All advertising data is now stored in instances of `NimBLEAdvertisingData` and vectors removed from `NimBLEAdvertising`.
* `NimBLEAdvertising::setAdvertisementData` and `NimBLEAdvertising::setScanResponseData` now return `bool`, true = success.
* Added new method, `NimBLEAdvertisementData::removeData`, which takes a parameter `uint8_t type`, the data type to remove.
* Added new method, `NimBLEAdvertisementData::toString`, which will print the data in hex.
* Added new method, `NimBLEAdvertising::getAdvertisementData`, which returns a reference to the currently set advertisement data.
* Added new method, `NimBLEAdvertising::getScanData`, which returns a reference to the currently set scan response data.
* Added overloads for `NimBLEAdvertising::removeServiceUUID` and `NimBLEAdvertisementData::removeServiceUUID` to accept a `const char*`
* Added new method, `NimBLEAdvertising::clearData`, which will clear the advertisement and scan response data.
2024-11-27 11:48:33 -07:00
52291390fa Fix task not released when not exchanging MTU. 2024-11-26 17:44:44 -07:00
4a57432a47 Fix compilation errors in some situations. 2024-11-26 14:20:39 -07:00
a4043e3f04 Add NimBLEClientCallbacks::onConnectFail callback
Adds a callback that is called when the connection attempt fail while connecting asynchronously.
2024-11-25 16:08:13 -07:00
41a7aa8eb5 Add const to NimBLEAdvertisedDevice* in NimBLEClient::connect overload
Fixes an issue where the wrong connect overload is called if the NimBLEAdvertisedDevice* passed is const.
2024-11-24 16:17:01 -07:00
1b0abd273f [BREAKING] - Remove ignore list.
This removes the ignore list feature as it can be implemented by the application if desired.
The scan will now ignore any device we are connected to already by checking for any connected client with the same peer address.
2024-11-23 21:08:08 -07:00
2151386057 [BREAKING] - Refactor NimBLEScan
* General code cleanup
* `NimBLEScan::start` will no longer clear cache or results if scanning is already in progress.
* `NimBLEScan::clearResults` will now reset the vector capacity to 0.
* `NimBLEScan::stop` will no longer call the `onScanEnd` callback as the caller should know its been stopped when this is called.
* `NimBLEScan::clearDuplicateCache` has been removed as it was problematic and only for the esp32. Stop and start the scanner for the same effect.
* `NimBLEScan::start` takes a new bool parameter `restart`, default `true`, that will restart an already in progress scan and clear the duplicate filter so all devices will be discovered again.
* Scan response data that is received without advertisement first will now create the device and send a callback.
* Added new method: `NimBLEAdvertisedDevice::isScannable()` that returns true if the device is scannable.
* Added default callbacks for `NimBLEScanCallbacks`
* `NimBLEScanCallbacks` function signatures updated:
* - `onDiscovered` now takes a `const NimBLEAdvertisedDevice*`
* - `onResult` now takes a `const NimBLEAdvertisedDevice*`
* - `onScanEnd` now takes a `const NimBLEScanResults&` and `int reason`
* Added new erase overload: `NimBLEScan::erase(const NimBLEAdvertisedDevice* device)`
* `NimBLEScanResults::getDevice` methods now return `const NimBLEAdvertisedDevice*`
* `NimBLEScanResults` iterators are now `const_iterator`
2024-11-21 14:37:31 -07:00
5f2730de02 Revert #724e1a7 and replace with stack checks.
Replaces `NimBLEDevice::setConnectionInProgress` and `NimBLEDevice::isConnectionInProgress()` with lower level checks to avoid potential incorrect state reporting.
`NimBLEClient::connect` will instead call `NimBLEScan::stop` if it stopped the scan to release any resources waiting, the call the callback if set.
2024-11-18 08:56:38 -07:00
fbbcfadc0c Refactor client connection establishment and client deletion.
* Removes the connection established flag as it should not be necessary.
* Deleting the client instance from the `onDisconnect` callback is now supported.
* `NimBLEDevice::deleteClient` no longer blocks tasks
* Adds a new `Config` struct to `NimBLEClient` to efficiently set single bit config settings.
* Adds `NimBLEClient::setSelfDelete` that takes the bool parameters `deleteOnDisconnect` and `deleteOnConnectFail`
  This will configure the client to delete itself when disconnected or the connection attempt fails.
* Adds `NimBLEClient::setConfig` and `NimBLEClient::getConfig` which takes or returns a `NimBLEClient::Config` object respectively.

* Reword `BLE_HS_EAPP` error string to be more accurate.
2024-11-18 08:56:38 -07:00
a6e75b3537 Ensure events are defined inNimBLEUtils::gapEventToString 2024-11-18 08:11:44 -07:00
7bd7b1dfc2 Workaround for bug in NimBLE stack when connect re-attempt enabled.
Connect reattempt does not pass the arg parameter correctly and the disconnect event will have no client pointer in the argument.
This finds the client from the connection handle to compensate.
2024-11-17 12:20:49 -07:00
a59e8ee9e1 Refactor NimBLEClient::connect and NimBLEClient::secureConnection.
This change ensures that only the function that sets `m_pTaskData` clears it, potentially preventing a segmentation fault.

* Client will no longer disconnect if task timeout occurs when waiting for MTU exchange response.
2024-11-14 10:45:24 -07:00
6a5d6ef5e3 Set task handle in constructor of NimBLETaskData.
* Create destructor for NimBLETaskData to delete semaphore if created.
2024-11-14 10:45:24 -07:00
5aa2fb1443 Refactor NimBLEUtils::taskWait to check notification value before blocking.
Instead of incrementing the notificatin value via `xTaskNotifyGive` this will now set a specific bit in the task notification value
which will be tested before blocking a task. This will prevent a task from blocking indefinitely if the event that calls `taskRelease`
occurs before entering the blocked state.

* Adds a config setting for the bit to set in the task notification value.
2024-11-14 10:45:24 -07:00
7d2ad92ad2 Bit shift length for resize 2024-11-14 10:30:58 -07:00
ab43135f82 Fix NimBLEUtils::dataToHexString returned string, must resize before modifying. 2024-11-14 10:30:58 -07:00
84f4d4f897 Improve NimBLEUtils::dataToHexString efficiency. 2024-11-13 09:40:52 -07:00
beac19cc92 [BREAKING] - Refactor NimBLEUtils
* Add functions `NimBLEUtils::taskWait` and `NimBLEUtils::taskRelease` to simplify task blocking/messaging.
* `NimBLEUtils::buildHexData` replaced with `NimBLEUtils::dataToHexString`
* Add missing GAP event strings.
* Add missing return code strings.
* `NimBLEUtils::dumpGapEvent` function removed.
* Event/error code strings optimized.
2024-11-12 16:56:59 -07:00
65e05e6c57 Add NimBLEClient::cancelConnect
Adds a function to cancel and in-progress connection.
2024-11-12 16:14:02 -07:00
38e764d157 Add asyncronous client connect and MTU exchange.
* Adds parameters `asyncConnect` and `exchangeMTU` to `NimBLEClient::connect`, default values work as the original connect method.
* * `asyncConnect`; if true, will send the connect command and return immediately with a true value for successfully sending the command, else false.
* * `exchangeMTU`; if true will send the exchange MTU command upon connection, otherwise not and the application can choose to do this later via the `exchangeMTU` method.
* Adds `onMTUChange` callback to `NimBLEClientCallbacks`
* Add `NimBLEDevice::getConnectedClients()` which returns a vector of pointers to the currently connected client instances.
* Calling `NimBLEClient::connect` will no longer cancel already in progress connections.
2024-11-10 13:02:11 -07:00
724e1a7083 Fix endless loop when calling scan start from scan end callback.
When attempting to connect and the scanner is running `NimBLEScan::stop` is called to stop it
which then calls the `onScanEnded` callback. If the app then starts the scan again in this
callback an endless loop will be created.

This change prevents the endless loop by setting a flag in `NimBLEDevice` that is checked before
starting a scan while a client is trying to connect.

* Adds `NimBLEDevice::setConnectionInProgress` and `NimBLEDevice::isConnectionInProgress` functions.
2024-11-10 10:36:51 -07:00
7d0636bc91 Fix NimBLEClient::secureConnection incorrectly failing with BLE_HS_EAGAIN. 2024-11-10 07:43:25 -07:00
020c61700d [BREAKING]- Refactor client
* General code cleanup and rename variables to use a consistent style.
* Removes the disconnect timer and will use the BLE_GAP_EVENT_TERM_FAILURE event to handle failed disconnects.
* `NimBLEClient::getConnId` has been renamed to `getConnHandle` to be consistent with bluetooth terminology.
* `NimBLEClient::disconnect` now returns a `bool = true on success` instead of an int to be consistent with the rest of the library.
* `NimBLEClient::setPeerAddress` now returns a bool, true on success.
* `NimBLEClientCallbacks::onConfirmPIN` renamed to `NimBLEClientCallbacks::onConfirmPasskey` to be consistent with bluetooth terminology.
* `NimBLEClient::setDataLen` now returns bool, true if successful.
* `NimBLEClient::updateConnParams` now returns bool, true if successful.
* `NimBLEClient::getServices` now returns a const reference to std::vector<NimBLERemoteService*> instead of a pointer to the internal vector.
2024-11-03 18:12:20 -07:00
68b82f5b85 Add NimBLEDevice::setOwnAddr and NimBLEUtils::generateAddr functions.
Adds a utility to generate random BLE addresses and set the address used.
2024-11-02 18:46:04 -06:00
a2fe5b4780 [BREAKING] Refactor NimBLEDevice
* General code cleanup
* `NimBLEDevice::getInitialized` renamed to `NimBLEDevice::isInitialized`.
* `NimBLEDevice::setPower` no longer takes the `esp_power_level_t` and `esp_ble_power_type_t`, instead only an integer value in dbm units is accepted.
* `NimBLEDevice::setPower` now returns a bool value, true = success.
* `NimBLEDevice::setMTU` now returns a bool value, true = success.
* `NimBLEDevice::injectConfirmPIN` renamed to `NimBLEDevice::injectConfirmPasskey` to use Bluetooth naming.
* Fixes crash if `NimBLEDevice::deinit` is called when the stack has not been initialized.
* Reverts 73f0277 as it would cause a crash when the NimBLEServer instance has a connection.
* `NimBLEDevice::getAddress` will now return the address currently in use.
* `NimBLEDevice::init` now returns a bool with `true` indicating success.
* `NimBLEDevice::deinit` now returns a bool with `true` inidicating success.
* `NimBLEDevice::setDeviceName` now returns a bool with `true` indicating success.
* `NimBLEDevice::setCustomGapHandler` now returns a bool with `true` indicating success.
* `NimBLEDevice::setOwnAddrType` now returns a bool with `true` indicating success.
* `NimBLEDevice::setOwnAddrType` will now correctly apply the provided address type for all devices.
* `NimBLEDevice::setOwnAddrType` no longer takes a `bool nrpa` parameter.
2024-11-02 18:46:04 -06:00
877a29a8b1 Update cmakelists.txt (#213) 2024-11-02 17:58:51 -06:00
a7ff1beacd doc: mention 0 is forever for NimBLESCan::start
Document that setting `duration` to zero means to scan forever.
2024-11-01 15:43:14 -06:00
ed2c59d5de Add initial esp32-P4 support (#208) 2024-10-31 19:06:57 -06:00
8ca58f5a89 implement connection parameters update callback (#210) 2024-10-24 21:21:43 -06:00
3820f57076 fix: #200 Enable use of data()/size() before trying c_str()/length() (#201)
* fix: #200 Use `data()`/`size()` instead of `c_str()`/`length()`

* Reduce duplication, only allow template function in characteristic and remote value attr if the type is not a pointer (otherwise sizeof is useless). add appropriate notes

* clean up AttValue::setValue to remove unnecessary length parameter enabling requirement of non-pointer type
2024-10-14 17:02:21 -06:00
987a69f544 Fix check for arduino component (#204) 2024-10-06 18:16:48 -06:00
b807e6671f Fix Advertised device initialization. 2024-10-06 15:03:11 -06:00
758c4d0471 Remove stray debug message. 2024-09-30 16:08:51 -06:00
5b24c8d681 Fix notifications not being sent.
The connection handle was not initialized correctly when recording the subscibe status causing the call to send notification/indications to fail with BLE_HS_ENOTCONN.
2024-09-30 16:07:00 -06:00
73f0277042 fix(NimBLEDevice): clear all before port_deinit to prevent crash 2024-09-24 16:03:49 -06:00
91210b8610 [BREAKING] Refactor attributes
Refactor attributes to reduce code duplication and improve maintainability.

* Add attribute base classes to provide common code.
* Add const where possible to functions and parameters.
* `NimBLECharacteristic::notify` no longer takes a `bool is_notification` parameter, instead `indicate()` should be called to send indications.
* `NimBLECharacteristic::indicate` now takes the same parameters as `notify`.
* `NimBLECharacteristicCallbacks` and `NimBLEDescriptorCallbacks` methods now take `const NimBLEConnInfo&` instead of non-const.
* `NimBLECharacteristic::onNotify` callback removed as unnecessary, the library does not call notify without app input.
* `NimBLERemoteCharacteristic::getRemoteService` now returns a `const NimBLERemoteService*` instead of non-const.
* Add NimBLEUUID constructor that takes a reference to `ble_uuid_any_t`.
* `NimBLERemoteService::getCharacteristics` now returns a `const std::vector<NimBLERemoteCharacteristic*>&` instead of non-const `std::vector<NimBLERemoteCharacteristic*>*`
* `NimBLERemoteService::getValue` now returns `NimBLEAttValue` instead of `std::string`
* `NimBLEService::getCharacteristics` now returns a `const std::vector<NimBLECharacteristic*>&` instead of a copy of std::vector<NimBLECharacteristic *>.
* Remove const requirement for NimBLEConnInfo parameter in callbacks.
  Const is unnecessary as the data can't be changed by application code.
* Change NimBLERemoteCharacteristic::getRemoteService to return const pointer.
2024-09-24 14:59:54 -06:00
b4b3b0c455 Fix NimBLEExtAdvertisement::setServiceData data length. 2024-09-15 10:28:49 -06:00
6f03b9a6ef fix: data was renamed to adv 2024-09-15 10:26:46 -06:00
cd115f1738 fix(NimBLEAdvertising): Ensure setServiceData() includes length of data 2024-08-29 17:12:21 -06:00
12074d1cc4 Fix crash when creating address from 17 char string. 2024-08-12 07:56:38 -06:00
d22db6ef8c Fix 16 and 32 bit UUID comparison. 2024-08-02 07:18:35 -06:00
209f70a083 Fix 128 bit uuid comparison. 2024-07-25 15:30:45 -06:00
10d589162b [Breaking] Refactor NimBLEUUID.
* msbFirst parameter has been removed from constructor as it was unnecessary,
caller should reverse the data first or call the new `reverseByteOrder` method after.
* `getNative` method replaced with `getBase` which returns a read-only pointer to the UUID size underlying.
* Added `reverseByteOrder` method, this will reverse the bytes of the UUID, which can be useful for advertising/logging.
* Added `getValue` method, which returns a read-only `uint8_t` pointer to the UUID value.
* Removed `m_valueSet` member variable, `bitSize()` can be used as a replacement.
* General code cleanup.
2024-07-23 18:14:09 -06:00
d1d1b49a26 Refactor NimBLEAttValue.
* Add length parameter to `setValue()` templates, with defaults for backward compatibility.
* Changed `setValue(const char*)` to add an optional length parameter so that a NULL character can be included, defaults to strlen.
* Moved non-inline functions to `NimBLEAttValue.cpp` file.
* Corrected includes to permit compilation as a stand-alone utility.
* Removed repeated code in `setValue()` by using `append()` after clearing the value.
* General code cleanup.
2024-07-21 16:36:00 -06:00
8c4832f711 Add clang-format. 2024-07-18 17:17:54 -06:00
efa858c4cc Only trigger build on master when pushing. 2024-07-18 17:17:30 -06:00
c2ab790e1d [BREAKING] Refactor NimBLEAdvertised device.
* Construct the device with the parameters from the advertisement in the initialization list.
* Removed no longer needed methods; setAddress, setAdvType, setRSSI, setSetId, setPrimaryPhy, setSecondaryPhy, setPeriodicInterval.
* Removed `hasRSSI()` method, the RSSI is always reported so this is redundant.
* Replace setPayload with new method; `update` which will update the device info when new advertisement data is received.
* getPayload now returns `const std::vector<uint8_t>` instead of a pointer to internal memory.
* Added `begin` and `end` read-only iterators for convienience and use in range loops.
* Timestamp removed, if needed then the app should track the time in the callback.
* Consolidate some functions to use getPayloadByType.
* Add optional index parameter to getPayloadByType.
* Change payload indexing to use 0 as the first item.
* Code cleanup and apply const correctness.
2024-07-17 20:44:49 -06:00
6279817143 [BREAKING] Refactor NimBLEAddress - use NimBLE core representation.
This simplifies the NimBLEAddress code by directly using the NimBLE core `ble_addr_t` type to hold the address
and allows using NimBLE core functions and macros to replace code in some methods.

* `getNative()` replaced with `getBase()` and now returns a pointer to `const ble_addr_t` instead of a pointer to the address value.
* Adds `isNrpa()` method to test if an address is random non-resolvable.
* Adds `isStatic()` method to test if an address is random static.
* Adds `isPublic()` method to test if an address is a public address.
* Adds `isNull()` methods to test if an address is NULL.
* Adds `getValue()` method which returns a read-only pointer to the address value.
* Adds `reverseByteOrder()` method which will reverse the byte order of the address value.
* `equals()` method and == operator will now also test if the address types are the same.
* Code cleanup.
2024-07-17 19:38:35 -06:00
21e1217e4c [BREAKING] Use an array to manage created client instances.
* Replaces the use of std::list with a fixed array to track and manage created client instances.
* Removes: NimBLEDevice::getClientList
* Replaces: NimBLEDevice::getClientListSize with NimBLEDevice::getCreatedClientCount
2024-07-10 07:05:47 -06:00
a92149ac74 [BREAKING] Change NIMBLE_LOGC macro to use printf.
Replaces all use of NIMBLE_LOGC with NIMBLE_LOGE and redefines NIMBLE_LOGC to use printf.
This allows NIMBLE_CPP_DEBUG_ASSERT messages to print event when log level filtering is set to none.
2024-07-04 19:05:35 -06:00
d9f5794b57 Replace NimBLEAttValue asserts with user defineable action.
* Adds the NIMBLE_CPP_DEBUG_ASSERT macro that calls a weak function to allow user defined action, defaults to critical error message and aborts.
* Adds a config option to disable asserts using the NIMBLE_CPP_DEBUG_ASSERT macro.
2024-07-04 18:47:28 -06:00
44977cdcce Remove NimBLEUtils::checkConnParams.
This function is not required as the stack will return an error code in the case of invalid params.
2024-07-03 15:01:44 -06:00
a5dd84b2f9 Remove descriptor asserts when the connection info is not found.
* Trigger onRead callbacks when the connection handle is NONE (internal).
2024-07-03 15:01:28 -06:00
b8d6e3d87f Remove assert for 0x2902, make a dummy descriptor instead.
Rather than asserting for a harmless situation, this will just create a dummy descriptor
object, marked as removed, and print a warning.
2024-07-03 15:01:14 -06:00
fae53b8d7f Remove asserts from NimBLEDevice. 2024-07-03 15:01:00 -06:00
358170847d Remove aborts in NimBLEAdvertising::start. 2024-07-03 14:27:59 -06:00
a1bd817875 Remove NimBLEServer::start abort. 2024-07-03 14:27:31 -06:00
fd698b0212 [NimBLEServer] Add getPeerName and get peer name on connect.
* Adds a new method, getPeerName to NimBLEServer to read the name from the peers device name characteristic.
* Adds a setting to automatically get the name of the peer when connected and provide it as an additional parameter in the onConnect callback.
* Adds callback with client name after authentication as it may change.
2024-06-30 16:44:49 -06:00
3c5a2fd4a9 add h2 2024-06-18 06:30:35 -06:00
0c797d5b41 add h2 2024-06-18 06:30:35 -06:00
cabd48aef3 Add documentation to NimBLEService::isStarted 2024-06-15 09:55:40 -06:00
a2a50957b1 Create package.json 2024-06-15 09:22:31 -06:00
8acea66c10 Reset advertisment vectors when changing their data.
* Add method to erase all service UUIDS.
2024-06-14 22:02:29 -06:00
bd29e738bd Add service isStarted method, remove abort in NimBLEServer::start. 2024-06-14 18:26:42 -06:00
792359b510 Remove asserts in NimBLECharacteristic read/write. 2024-06-14 10:01:50 -06:00
bc7bfe8278 Add clearData method to NimBLEAdvertisementData. 2024-06-14 10:01:41 -06:00
20349c64a4 Add conditional checks in NimBLEDevice init/deinit. 2024-06-14 10:01:34 -06:00
70c2d83b3b Remove broken links from docs. 2024-06-14 09:57:23 -06:00
63a3301696 Add missing const in NimBLEConnInfo. 2024-06-12 21:12:09 -06:00
c156b0202c Add isRpa method to NimBLEAddress.
This provides and easy way to check if the peer address is a Resolvable Private Address.
2024-06-12 21:12:09 -06:00
ef90a8aa95 Remove address from whitelist if the procedure fails.
This prevents a situation where the whitelist contains the address but the procedure errors and the address cannot be added again.
2024-06-12 21:12:09 -06:00
aeb4334e98 Add server and client onIdentity callback.
Adds a callback that is called when the identity address of the peer is resolved, this is useful for adding it to a whitelist.
2024-06-12 21:12:09 -06:00
44daa3c687 Fix failure to reconnect to device when bonded.
iOS devices specifically expect to receive the ID key of the bonded device even when RPA is not used.
This sets the default value of the key distribution config to provide the ID key as well as the encryption key.
2024-06-12 21:12:09 -06:00
f36929963d Add disconnect overload to take NimBLEConnInfo reference. (#162)
* NimBLEConnInfo - Note that the connection handle is the same as the connection id in the comment for getConnHandle()

* NimBLEServer - int disconnect(const NimBLEConnInfo&) helper method
2024-06-08 10:06:57 -06:00
2447af6a4d Fix Error in converting EddystoneTLM negative temperatures to float | resolves h2zero/NimBLE-Arduino#675 2024-06-08 10:02:47 -06:00
9c1f1adf7a [BREAKING] Asynchronous pin injections for Numeric Comparison and PassKey Input (#165)
* Make NimBLEConnInfo functions const.

* Update callback functions and update client to use new functions.

* Update examples.

* Update migration guide.

---------

Co-authored-by: Casey Smith <csmith@morningstarcorp.com>
2024-06-06 19:36:14 -06:00
6ca61bbd9c feat(NimBLEDevice): deleteAllBonds() Add return value (#158)
Add return value to `deleteAllBonds`.
2024-06-04 16:52:55 -06:00
32c213a8a3 feat(NimBLEClient): allow connection id / established flag to be set via public API. (#156)
* Adds NimBLEClient::setConnection  to allow servers to read the name of connected clients by passing their connection info to the Client class.
* Adds NimBLEClient::clearConnection to be able to reuse the client without deleting and recreating.
2024-06-04 10:37:24 -06:00
51bf1f3c7c feat(NimBLEAdvertising): support std::function for advertising complete callback (#157)
Updates the interface to use a typedef'd std::function for the advertise callback, which is backwards compatible but also allows std::bind and lambda functions.
2024-06-04 07:12:20 -06:00
7c0300c34e Change NimBLEHIDDevice formatting for consistency. 2024-06-02 17:02:02 -06:00
6fa3783206 Bug fix on PNP info
Fixed issue #492
2024-06-02 17:02:00 -06:00
226c67f729 Initialize ble_gatt_chr_def[]. Fixes #148 (#150)
IDF 5.2 introduced a new member, cpfd, to the
ble_gatt_chr_def struct. It needs to be initialized
to nullptr in order to avoid accessing uninitialized
memory. By initializing the whole struct, we get
everything initialized in a backward-compatible way.
2024-04-20 09:14:55 -06:00
bf4b5d4ffa ESP IDF 5.2 include fix (#144) 2024-03-01 12:29:18 -07:00
58f86cb7bd Fix inconsistent use of time units (#143)
Seconds to milliseconds
2024-02-29 17:34:53 -07:00
22fb1ab801 Add generic advertisement 'type' functions (#575) 2023-11-25 08:10:30 -07:00
4e65ce5d32 Support for C2 (#131) 2023-09-01 11:56:52 -06:00
b07cab5858 gptimer is used from driver 2023-09-01 08:22:37 -06:00
2ea0f26de0 Add support for esp32c6 2023-08-13 10:40:00 -06:00
1786d0ede3 Fix compilation when CONFIG_BTDM_BLE_SCAN_DUPL is not enabled.
*  fix warning: variable 'pkey' set but not used [-Wunused-but-set-variable]
---------

Co-authored-by: Franz Höpfinger <f.hoepfinger@hr-agrartechnik.de>
2023-05-29 09:08:14 -06:00
4ff9baf68a Fixed unhandled exception on handleGapEvent (#112)
Somehow, the conn_handle can have the value of `0xffff`. Not sure why or how, but anyway it should be managed before moving forward on NimBLECharacteristic::handleGapEvent. Otherwise, an unhandled exception will occur on `assert(rc == 0);`
2023-05-29 07:56:31 -06:00
c1e7a521b7 Add overloaded setManufacturerData to allow vector of uint8_t 2023-05-28 16:23:34 -06:00
fee3829a89 Fix build with platformio IDF+Arduino (#122) 2023-05-28 10:44:17 -06:00
091c1c014c Update doxygen config 2023-05-25 10:29:53 -06:00
3145319581 Build with idf v5.1 2023-05-25 09:35:11 -06:00
d0eaf6c1e0 Set service handle in getHandle function if not set already.
If a service has been created and started but not yet added to the gatt server then the call to getHandle will result in an invalid handle. This adds a call to set the handle value in the getHandle function.
2023-05-24 15:37:53 -06:00
46e7bb9302 Add onDiscovered scan callback.
This adds a callback that is called when a device is initially discovered.
It is always called wether scanning in passive or active mode. This allows
for active scanning to receive device detection information in the case where
the scan response is not sent/received.

This callback is optional, the application may decide to implement it or not.
2023-05-24 15:37:46 -06:00
559a26b74b Add index parameter for multiple manufacturer data sets.
Adds an index parameter to NimBLEAdvertisedDevice::getManufacturerData to allow for selecting from multiple instances in the advertisements.
Adds NimBLEAdvertisedDevice::getManufacturerDataCount to get the number of manufacturer data sets present in the advertised data.
2023-05-24 15:37:38 -06:00
4423e5fbb6 Expose advertisement flags in NimBLEAdvertisedDevice 2023-05-24 15:37:30 -06:00
0aa7e9510d Add directed peer address parameter to advertising start.
Adds a parameter to NimBLEAdvertising::start to take the peer address for use with directed advertising.
2023-05-24 15:37:22 -06:00
d83cd94d5b Revert 03b22e5 sub/unsub changes, app should specify response. 2023-05-24 15:37:17 -06:00
7d2d73d8fc Fix pairing when already in progress.
If pairing is requested before performing an action on a protected attribute pairing could fail due to already being in progress.
This fix will wait for the result of the pairing process before proceeding with the action.
2023-05-24 15:37:03 -06:00
05ac9deaea Remove deprecated API in case of ESP-IDF V5. (#102)
* Remove deprecated API in case of ESP-IDF V5.

0a93ee1337/docs/en/migration-guides/release-5.x/bluetooth-low-energy.rst (id17)

* Fix initialization in case of ESP-IDF V5
2022-11-03 20:47:04 -06:00
cad022650a Fix getPower return value
Power level -3 returned the wrong value.
2022-09-11 20:34:33 -06:00
e868f37135 Add conn_handle to NimBLECharacteristic::notify to send notification/indication to a specific client (#97)
Adds the ability to send notifications/indications to specific clients individually.
2022-09-11 20:18:55 -06:00
6fb26e3809 Change type of index to int (instead of uint8_t) to fix issue with adding more than 255 Characteristics (or Descriptors) (#101) 2022-09-11 19:54:15 -06:00
6a2f558ea5 [BREAKING] Replace advertised device callbacks with scan callbacks. (#389)
This replaces NimBLEAdvertisedDeviceCallbacks with NimBLEScanCallbacks and adds a onScanEnd callback.

The callback parameter for NimBLEScan::start has been removed and the blocking overload for NimBLEScan::start
has been replaced by an overload of NimBLEScan::getResults with the same parameters.
2022-08-27 14:04:50 -06:00
562a32eda6 Add docs build. 2022-08-27 13:02:29 -06:00
0f4da63fc8 Add CI build check. 2022-08-27 13:02:29 -06:00
ba79a1bf72 [Breaking] Update callbacks to use NimBLEConnInfo.
Change the callback functions that receive a ble_gap_conn_desc pointer to instead receive a NimBLEConnInfo reference.

* Add a reason parameter to the server disconnect callback.

* Remove connect and disconnect callback that do not receive info parameters.

* Remove onRead and onWrite Characteristic callbacks that do not receive info parameters.

* Add info parameter to Descriptor onWrite and onRead callbacks.

* Add details to migration guide.
2022-08-27 13:02:29 -06:00
ca8a7c56ac [Breaking] Remove extra notification status from onStatus callback. (#80)
Removes the unnecessary NimBLECharacteristicCallbacks::Status enum and callback parameter from NimBLECharacteristic::onStatus.

This was maintained for compatibility with the Arduino BLE library and is not necessary as the return code from the stack is also provided.

* Update examples/docs.
2022-08-26 20:40:21 -06:00
03b22e53a0 [Breaking] Remove deprecated functions/response parameter from un/sub (#76)
Removes the response parameter from remote characterisitc subscrible/unsubscribe functions
as a response is always required for this operation as per BLE specs.

Removes the deprecated functions from remote characteristic/desriptor.

* Update examples/docs.
2022-08-26 20:15:25 -06:00
2b758e05c7 Fix client example. 2022-08-26 19:54:43 -06:00
bfe68f4a91 [Breaking] Add disconnect reason to client callback. (#398) (#81)
Adds the reason code as a parameter to the client onDisconnect callback.

* Update examples/docs.
2022-08-26 19:51:19 -06:00
bb3dd5f114 [Breaking] Change all time input parameters to milliseconds. (#78)
Changes all functions that accept a time parameter to use milliseconds instead of seconds.

* Adds duration input to NimBLEDevice::startAdvertising and NimBLEServer::startAdvertising.
2022-08-26 19:32:01 -06:00
0b6337538c Remove NimBLESecurity class. (#75) 2022-08-21 21:33:39 -06:00
32e7059732 add NimBLEHIDDevice::batteryLevel() 2022-08-21 21:19:54 -06:00
cd3185fe43 Added the setDeviceName functionality while BLE is running 2022-08-21 21:19:30 -06:00
efa48c0d57 Release 1.4.0
* Fix typos

* Update docs
2022-07-31 11:34:56 -06:00
70ed6e293f Don't set advertisement flags if not connectable. 2022-07-10 07:15:46 -06:00
93de7ab8ed Bugfix/onRead callback not called for non-long read commands. 2022-06-26 17:03:21 -06:00
9285a9b31f Don't call scan result callback if it was already called. 2022-06-04 14:24:30 -06:00
38a1a2013b Update docs. 2022-05-29 20:08:23 -06:00
a36655c105 Add success/fail return value to disoverAttributes. 2022-04-16 20:32:01 -06:00
c285052f6d Use write with response when writing 0x2902 descriptors.
As per Bluetooth core specification we must write to 0x2902 descriptors with response request.
This change ensures the correct procedure is used.

Todo: Remove the "response" parameter from related functions.
2022-04-16 12:47:23 -06:00
9e5db157f8 Add extended advertising support. (#72)
Adds support for advertising and connections with coded/2M PHY's.

Adds new classes `NimBLEExtAdvertising` and `NimBLEExtAdvertisement`.
When extended advertising is enabled the original advertising classes become unavailable and the new classes must be used.

Changed some return values for advertising methods for consistency with the new classes methods.
2022-04-10 10:21:45 -06:00
58787b516b Prevent crash when characteristic vector is empty. 2022-04-02 14:22:23 -06:00
a1428e63a6 Fixup client logs. 2022-02-20 10:04:13 -07:00
0f4326d3fd Check characteristic handles before fetching descriptors. 2022-02-20 10:02:09 -07:00
f414a5ac73 Release v1.3.3 2022-02-15 20:33:02 -07:00
99a23d3c19 Remove recursive calling when fetching remote attributes. 2022-02-15 20:32:18 -07:00
6cda761f13 Fix memory leak when deleting client instance. 2022-02-15 20:31:26 -07:00
288ee92d39 Added extended advertising scan support (#69) 2022-02-06 16:52:42 -07:00
2e498cef2b Fix IDF version check. 2022-02-06 12:58:26 -07:00
2386a8a68a Retrieve attributes with 16bit uuid if 128bit fails.
When retrieving attribute handles using the 128bit base version of a 16 bit UUID some devices will
report "not found". This will attempt to convert the UUID to the 16bit version and try again.

* Adds `to16()` method to NimBLEUUID.
2022-01-18 14:48:07 -07:00
6b858a0efd Fix memory leak when services changed. 2022-01-18 14:44:47 -07:00
e3ee082dd7 Add NimBLEAttValue class. (#67)
This is a specialized container class to hold BLE attribute values.

- Removes the use of std::string previously used to store the values.
- Allows for setting/getting/notifying values from std::string, std::vector<uint8_t>, Arduino String, const char*, and uint8_t buffers.
- Has operators retrieve the value as std::string, Arduino String, std::vector<uint8_t>, uint8_t* or char pointers.
- Includes iterators and subscript/random access operator.
- Introduces a max length parameter to the creation of server characteristics/descriptors to limit the size of the memory footprint.
- Nearly Seamless integration with existing code.
- Adds a config option to enable/disable timestamp storage when the value is updated.
- Adds a config option to specify the initial size of the value container if not specified in the constructor.
2022-01-16 20:11:18 -07:00
be9cdc1ab6 Update docs 2022-01-15 15:21:41 -07:00
cf482f9112 Cleanup ARM-gcc compiler warnings. 2022-01-15 12:43:17 -07:00
bbed8d1d4b Release v1.3.2 2022-01-15 09:07:08 -07:00
099e7cc326 Remove travis docs build. 2022-01-15 08:57:40 -07:00
830c4cc39e Re-enable data length extension newer IDF versions. 2022-01-15 08:51:49 -07:00
ea6e2101e3 Fix compilation on ESP32-S3 2022-01-14 21:46:30 -07:00
d47cf59ba9 Cleanup compile errors in arm-gcc. 2022-01-14 20:45:24 -07:00
ea02eb9452 Add config option for log verbosity. 2022-01-14 19:47:44 -07:00
798726c05d Update change log. 2022-01-14 10:32:47 -07:00
9824bdfe73 Update log level macro name 2022-01-14 10:02:47 -07:00
fac16f2428 Fix long data notifications.
The notification data when received was using an incorrect length value and would cut off long values, this has now been corrected.
2022-01-13 08:57:50 -07:00
0957d7f6ad The latest versions of IDF include a new esp_timer library that seems to be incrementing the task notification values in unexpected places depending on other tasks in operation.
This causes task blocking to fail in client operations leading to exceptions and crashing.

This is a workaround for this situation and will need to be reworked properly in the future.
2022-01-09 19:04:41 -07:00
5facd89a00 Update NimBLEServer.h (#65) 2022-01-01 18:00:45 -07:00
f2ade345f4 Fix missing data when reading large values.
The wrong length value was being used to set the values read from peer attributes.
This has been corrected to use the proper value size.
2021-12-29 14:01:37 -07:00
7a82067177 Add last error function to client. 2021-12-29 08:12:38 -07:00
d041a089e6 [NimBLEService] Remove unused variables/parameters. 2021-12-29 08:12:07 -07:00
9debfcd226 Use NimBLE calls for critical sections 2021-12-29 08:10:57 -07:00
8620092c90 Cleanup and add support for non-esp devices. 2021-12-29 08:08:25 -07:00
96459073a4 Initialize advertising complete callback in NimBLEAdvertising constructor.
* cleanup advertising start return.
2021-12-29 07:51:57 -07:00
a4403fe6b8 Clear client disconnect timer in constructor before initializing. 2021-12-29 07:50:42 -07:00
f841f030ae Add method to send notifications/indications with custom values (#63) 2021-12-28 20:11:37 -07:00
d793b1251e Remove data length extension in IDF (not released yet) 2021-09-13 20:45:36 -06:00
5925782a65 [Server][Client] Add function to set data length.
Enables the use of BLE data length extension to improve data transfer rates.
2021-09-12 19:11:38 -06:00
ccea428b9e Refactor include directives to use different paths for arduino/idf.
* Sets macros to allow compiling when Central role is enabled and Observer disabled, or Peripheral enabled and Broadcaster disabled.

* Adds a macro definition for CONFIG_NIMBLE_CPP_IDF to enable different include paths/functionality for IDF / Arduino.
2021-09-12 18:43:31 -06:00
e238a18a80 Update Doxygen version 2021-08-04 18:58:12 -06:00
7b40829e77 Release 1.3.1 2021-08-04 18:55:34 -06:00
b24597ac56 Remove definition of btInUse().
This reverts a previous change @2e1d78ff that caused compiling/linking errors due to the redefinition of btInUse() when another linked library uses the Arduino bluetooth code.
2021-08-03 12:43:34 -06:00
9961c5605c Update docs version. 2021-08-02 21:25:17 -06:00
d4e4074f5a Release 1.3.0 2021-08-02 21:14:12 -06:00
e5edc9d59e Add missing return documentation in NimBLEAdvertising. 2021-08-02 19:51:04 -06:00
2e1d78ff78 Code cleanup 2021-08-02 13:29:19 -06:00
6be6a111d0 [Server] Implement remove Characteristics/Descriptors. (#54)
This allows for adding and removing of characteristics and descriptors after initial setup of the server.
When used it will send a service changed notification to all clients.
The changes will not take effect until all clients have disconnected and advertising restarted.
2021-07-30 20:56:52 -06:00
0a2714c169 [Server] Add callback for MTU change. (#55)
onMTUChange callback added that is called when a connection MTU is updated.
2021-07-19 21:47:59 -06:00
7d01fa595d Fix compilation for ESP32C3. (#53) 2021-07-19 21:46:30 -06:00
2decc0682a Remove FreeRTOS from CmakeLists. 2021-07-14 10:30:41 -06:00
6ff1a49dd5 Update documentation. 2021-07-12 13:33:56 -06:00
09adf86036 Remove FreeRTOS files. 2021-07-12 10:25:32 -06:00
155 changed files with 14953 additions and 11121 deletions

42
.clang-format Normal file
View File

@ -0,0 +1,42 @@
BasedOnStyle: Google
Language: Cpp
ColumnLimit: 120
IndentWidth: 4
TabWidth: 4
UseTab: Never
SortIncludes: Never
PPIndentWidth : 1
IndentPPDirectives: AfterHash
ReflowComments: true
SpacesBeforeTrailingComments: 1
AlignTrailingComments: true
AlignAfterOpenBracket: Align
AlignConsecutiveMacros:
Enabled: true
AcrossEmptyLines: true
AcrossComments: true
AlignConsecutiveAssignments:
Enabled: true
AcrossEmptyLines: false
AcrossComments: true
AlignCompound: true
PadOperators: true
AlignConsecutiveDeclarations:
Enabled: true
AcrossEmptyLines: false
AcrossComments: true
AlignEscapedNewlines: Left
AccessModifierOffset: -2
AlignArrayOfStructures: Right
AlignOperands: Align
AllowAllArgumentsOnNextLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortBlocksOnASingleLine: Empty
BreakBeforeBinaryOperators: None
BinPackArguments: false
BinPackParameters: false
DerivePointerAlignment: false
PenaltyBreakAssignment: 4
PenaltyExcessCharacter: 4
PenaltyBreakBeforeFirstCallParameter: 1
PointerAlignment: Left

67
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,67 @@
name: Build
on:
workflow_dispatch:
pull_request:
push:
branches:
- master
jobs:
build-esp-idf-component:
name: Build with ESP-IDF ${{ matrix.idf_ver }} for ${{ matrix.idf_target }}
runs-on: ubuntu-latest
strategy:
matrix:
# The version names here correspond to the versions of espressif/idf Docker image.
# See https://hub.docker.com/r/espressif/idf/tags and
# https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-docker-image.html
# for details.
idf_ver: ["release-v4.4", "release-v5.4"]
idf_target: ["esp32", "esp32s3", "esp32c2", "esp32c3", "esp32c5", "esp32c6", "esp32h2", "esp32p4"]
example:
- NimBLE_Client
- NimBLE_Server
- Bluetooth_5/NimBLE_extended_client
- Bluetooth_5/NimBLE_extended_server
exclude:
- idf_target: "esp32"
example: Bluetooth_5/NimBLE_extended_client
- idf_target: "esp32"
example: Bluetooth_5/NimBLE_extended_server
- idf_ver: release-v4.4
idf_target: "esp32c2"
- idf_ver: release-v4.4
idf_target: "esp32c5"
- idf_ver: release-v4.4
idf_target: "esp32c6"
- idf_ver: release-v4.4
idf_target: "esp32h2"
- idf_ver: release-v4.4
idf_target: "esp32p4"
- idf_ver: release-v5.1
idf_target: "esp32p4"
container: espressif/idf:${{ matrix.idf_ver }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
path: components/esp-nimble-cpp
- name: Build examples
env:
IDF_TARGET: ${{ matrix.idf_target }}
shell: bash
run: |
. ${IDF_PATH}/export.sh
cp -r components/esp-nimble-cpp/examples/* .
idf.py -C ${{ matrix.example }} -DEXTRA_COMPONENT_DIRS=$PWD/components build
build_docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Doxygen Action
uses: mattnotmitt/doxygen-action@v1.9.8
with:
working-directory: 'docs/'

20
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Release
on:
release:
types: [published]
jobs:
build_docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Doxygen Action
uses: mattnotmitt/doxygen-action@v1.9.8
with:
working-directory: 'docs/'
- name: Deploy
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./docs/doxydocs/html

17
.github/workflows/sponsors.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: Generate Sponsors README
on:
workflow_dispatch:
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout 🛎️
uses: actions/checkout@v4
- name: Generate Sponsors 💖
uses: JamesIves/github-sponsors-readme-action@v1.5.4
with:
token: ${{ secrets.PAT }}
file: 'README.md'

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
docs/doxydocs

View File

@ -1,27 +0,0 @@
sudo: false
before_install:
- cd ${TMPDIR-/tmp}
- wget -q http://doxygen.nl/files/doxygen-1.9.0.src.tar.gz
- tar -xzvf doxygen-1.9.0.src.tar.gz
- mkdir doxygen_build
- cd doxygen_build
- cmake ../doxygen-1.9.0/
- make
- export PATH="${TMPDIR-/tmp}/doxygen_build/bin:$PATH"
- cd ${TRAVIS_BUILD_DIR}
branches:
only:
- master
script:
- doxygen ./docs/Doxyfile
deploy:
provider: pages
skip_cleanup: true
local_dir: docs/html
github_token: $GH_REPO_TOKEN
on:
branch: master

View File

@ -1,6 +1,445 @@
# Changelog
All notable changes to this project will be documented in this file.
All notable changes to this project will be documented in this file.
## [2.3.1] 2025-06-11
## Fixed
- Build errors when disabling BLE roles.
- `NimBLEClient::readValue` call not returning when the instance was created with a`NimBLEServer` and reading a secured characteristic.
- `NimBLEScan` destructor potentially causing a crash.
## Added
- `NimBLEBeacon::BeaconData` `std::vector<uint8_t>` operator to allow it to be used as a parameter to `NimBLEAdvertisementData::setManufacturerData`.
## [2.3.0] 2025-05-19
## Fixed
- Incorrect `NimBLECharacteristic::onSubscribe` value when indications are set.
- `NimBLECharacteristic::onRead` callback not called in some cases.
- Clear attribute value when zero length value is written.
- Notify/Indicate incorrectly returning success with custom value.
- Corrected NimBLEClient array initialization.
- Prevent potential exception when scan is restarted.
- Attribute getValue failing with some data types
- Incorrectly passing a pointer to a function taking const reference.
## Added
- Support for esp32c5
- L2CAP infrastructure.
- Scan duplicate cache reset time.
## Changed
- Cleaned up examples.
- Allow PHY updates without enabling extended advertising.
## [2.2.1] 2025-02-28
## Fixed
- Added back `NimBLEClient::connect` overload with `NimBLEAdvertisedDevice` parameter to resolve connection error due to NULL address.
- Crash caused by returning invalid vector entry when retrieving remote descriptors.
## [2.2.0] 2025-02-24
## Fixed
- Crash when calling `NimBLEClient::DiscoverAttributes`.
## Added
- Conditional macros for logging.
- `NimBLEDeviceCallbacks` class with a callback for handling bond storage.
## [2.1.1] 2025-01-26
## Fixed
- remote descriptor discovery error when no descriptors exist.
- scan filter settings not enabled for esp32s3/c3.
- remote descriptor discovery returning more than the desired descriptor.
## [2.1.0] 2025-01-12
## Fixed
- Crash when retrieving descriptors if more than one exists.
- Incorrect TX power value being advertised.
- New user guide code for 2.x
- Potential race condition if `NimBLEScan::clearResults1 is called from multiple tasks.
## Changed
- If privacy is not enabled identity keys will not be shared.
- `NimBLEDevice::setPower` and `NimBLEDevice::getPower` now take an additional parameter `NimBLETxPowerType` to set/get the power level for different operations.
## Added
- Config option `CONFIG_NIMBLE_CPP_ADDR_FMT_EXCLUDE_DELIMITER`, if defined will remove the ":" delimiter from the BLE address string.
- Config option `CONFIG_NIMBLE_CPP_ADDR_FMT_UPPERCASE` if defined will make the BLE address strings uppercase.
## [2.0.3] 2025-01-05
## Fixed
- Unused variable warning when log level is below info.
- Build error missing definition of CONFIG_NIMBLE_CPP_FREERTOS_TASK_BLOCK_BIT in platformio.
- Race condition in `NimBLEScan` that can cause a crash due to heap corruption if `NimBLEScan::stop` is called from the `onResult` callback.
- Advertisement data not set if scan response is enabled after the data is set.
- `NimBLECharacteristic`/`NimBLEDescriptor` not able to update their values in the `onRead` callback.
- Too short of a timeout being requested in NimBLE_Server example leading to frequent disconnects.
## Changed
- `NimBLEHIDDevice` now allows for the same report ID in multiple input/output/feature reports.
## Added
- Config for custom log colors pre level.
- Error logs in the case that NIMBLE_CPP_DEBUG_ASSERT is not defined.
- Error logs when setting advertisement data fails.
- Missing documentation in the migration guide about enabling automatic advertising on disconnect, which was disabled by default in 2.x.
## [2.0.2] 2024-12-21
## Fixed
- Compile error when only advertising role is enabled.
- Possible crash if bonded client reconnects.
## Changed
- `NimBLEHIDDevice` can now create more than one in/out/feature report map.
## [2.0.1] 2024-12-16
## Fixed
- `NimBLEHIDDevice::getOutputReport` will now return the correct characteristic.
- Compile error when central is disabled, class `NimBLEServer` has no member named `m_pClient`.
## Changed
- Added missing includes for `NimBLEConnInfo` and `NimBLEUtils` to `NimBLEDevice.h`.
## [2.0.0] 2024-12-14
## **Breaking changes**
- All connection oriented callbacks now receive a reference to `NimBLEConnInfo`, the `ble_gap_conn_desc` has also been replace with `NimBLEConnInfo` in the functions that received it.
- All functions that take a time input parameter now expect the value to be in milliseconds instead of seconds.
- Removed Eddystone URL as it has been shutdown by google since 2021.
- NimBLESecurity class removed.
- `NimBLEDevice` Ignore list functions removed.
- `NimBLEDevice::startSecurity` now returns a `bool`, true on success, instead of an int to be consistent with the rest of the library.
- `NimBLEDevice::getInitialized` renamed to `NimBLEDevice::isInitialized`.
- `NimBLEDevice::setPower` no longer takes the `esp_power_level_t` and `esp_ble_power_type_t`, instead only an integer value in dbm units is accepted.
- `NimBLEDevice::setOwnAddrType` no longer takes a `bool nrpa` parameter.
- `NimBLEDevice::getClientListSize` replaced with `NimBLEDevice::getCreatedClientCount`.
- `NimBLEDevice::getClientList` was removed.
- `NimBLEServer::disconnect` now returns `bool`, true = success, instead of `int` to be consistent with the rest of the library.
- `NimBLEServerCallbacks::onMTUChanged` renamed to `NimBLEServerCallbacks::onMTUChange` to be consistent with the client callback.
- `NimBLEServer::getPeerIDInfo` renamed to `NimBLEServer::getPeerInfoByHandle` to better describe it's use.
- `NimBLEServerCallbacks::onPassKeyRequest` has been replaced with `NimBLEServer::onPassKeyDisplay` which should display the pairing pin that the client is expected to send.
- `NimBLEServerCallbacks::onAuthenticationComplete` now takes a `NimBLEConnInfo&` parameter.
- `NimBLEClient::getServices` now returns a const reference to std::vector<NimBLERemoteService*> instead of a pointer to the internal vector.
- `NimBLEClient::getConnId` has been renamed to `getConnHandle` to be consistent with bluetooth terminology.
- `NimBLEClient::disconnect` now returns a `bool`, true on success, instead of an int to be consistent with the rest of the library.
- `NimBLEClientCallbacks::onDisconnect` now takes an additional `int reason` parameter to let the application know why the disconnect occurred.
- `NimBLEClientCallbacks::onPassKeyRequest` has been changed to `NimBLEClientCallbacks::onPassKeyEntry` which takes a `NimBLEConnInfo&` parameter and does not return a value. Instead or returning a value this callback should prompt a user to enter a pin number which is sent later via `NimBLEDevice::injectPassKey`.
- `NimBLEClientCallbacks::onConfirmPIN` renamed to `NimBLEClientCallbacks::onConfirmPasskey` and no longer returns a value and now takes a `NimBLEConnInfo&` parameter. This should be used to prompt a user to confirm the pin on the display (YES/NO) after which the response should be sent with `NimBLEDevice::injectConfirmPasskey`.
- `NimBLEAdvertising::setMinPreferred` and `NimBLEAdvertising::setMaxPreferred` have been removed, use `NimBLEAdvertising::setPreferredParams` instead.
- Advertising the name and TX power of the device will no longer happen by default and should be set manually by the application.
- `NimBLEAdvertising::setAdvertisementType` has been renamed to `NimBLEAdvertising::setConnectableMode` to better reflect it's function.
- `NimBLEAdvertising::setScanResponse` has been renamed to `NimBLEAdvertising::enableScanResponse` to better reflect it's function.
- `NimBLEAdvertising`; Scan response is no longer enabled by default.
- `NimBLEAdvertising::start` No longer takes a callback pointer parameter, instead the new method `NimBLEAdvertising::setAdvertisingCompleteCallback` should be used.
- `NimBLEAdvertisementData::addData` now takes either a `std::vector<uint8_t>` or `uint8_t* + length` instead of `std::string` or `char + length`.
- `NimBLEAdvertisementData::getPayload` now returns `std::vector<uint8_t>` instead of `std::string`.
- The callback parameter for `NimBLEScan::start` has been removed and the blocking overload of `NimBLEScan::start` has been replaced by an overload of `NimBLEScan::getResults` with the same parameters.
- `NimBLEAdvertisedDeviceCallbacks` Has been replaced by `NimBLEScanCallbacks` which contains the following methods: `onResult`, `onScanEnd`, and `onDiscovered
- - `NimBLEScanCallbacks::onResult`, functions the same as the old `NimBLEAdvertisedDeviceCallbacks::onResult` but now takes aa `const NimBLEAdvertisedDevice*` instead of non-const.
- - `NimBLEScanCallbacks::onScanEnd`, replaces the scanEnded callback passed to `NimBLEScan::start` and now takes a `const NimBLEScanResults&` and `int reason` parameter.
- - `NimBLEScanCallbacks::onDiscovered`, This is called immediately when a device is first scanned, before any scan response data is available and takes a `const NimBLEAdvertisedDevice*` parameter.
- `NimBLEScan::stop` will no longer call the `onScanEnd` callback as the caller should know its been stopped when this is called.
- `NimBLEScan::clearDuplicateCache` has been removed as it was problematic and only for the esp32. Stop and start the scanner for the same effect.
- `NimBLEScanResults::getDevice` methods now return `const NimBLEAdvertisedDevice*`.
- `NimBLEScanResults` iterators are now `const_iterator`.
- `NimBLEAdvertisedDevice::hasRSSI` removed as redundant, RSSI is always available.
- `NimBLEAdvertisedDevice::getPayload` now returns `const std::vector<uint8_t>` instead of a pointer to internal memory.
- `NimBLEAdvertisedDevice` Timestamp removed, if needed then the app should track the time from the callback.
- `NimBLECharacteristic::notify` no longer takes a `bool is_notification` parameter, instead `indicate()` should be called to send indications.
- `NimBLECharacteristicCallbacks::onNotify` removed as unnecessary, the library does not call notify without app input.
- `NimBLECharacteristicCallbacks::onStatus` No longer takes a `status` parameter, refer to the return code for success/failure.
- `NimBLERemoteCharacteristic::getRemoteService` now returns a `const NimBLERemoteService*` instead of non-const.
- `NimBLERemoteCharacteristic::readUInt32` Has been removed.
- `NimBLERemoteCharacteristic::readUInt16` Has been removed.
- `NimBLERemoteCharacteristic::readUInt8` Has been removed.
- `NimBLERemoteCharacteristic::readFloat` Has been removed.
- `NimBLERemoteCharacteristic::registerForNotify` Has been removed.
- `NimBLERemoteService::getCharacteristics` now returns a `const std::vector<NimBLERemoteCharacteristic*>&` instead of non-const `std::vector<NimBLERemoteCharacteristic*>*`.
- `NimBLERemoteService::getValue` now returns `NimBLEAttValue` instead of `std::string`.
- `NimBLEService::getCharacteristics` now returns a `const std::vector<NimBLECharacteristic*>&` instead of std::vector<NimBLECharacteristic *>.
- `NimBLEUUID::getNative` method replaced with `NimBLEUUID::getBase` which returns a read-only pointer to the underlying `ble_uuid_t` struct.
- `NimBLEUUID`; `msbFirst` parameter has been removed from constructor, caller should reverse the data first or call the new `reverseByteOrder` method after.
- `NimBLEAddress` constructor; default value for the `type` parameter removed, caller should know the address type and specify it.
- `NimBLEAddress::getNative` replaced with `NimBLEAddress::getBase` and now returns a pointer to `const ble_addr_t` instead of a pointer to the address value.
- `NimBLEAddress::equals` method and `NimBLEAddress::== operator` will now also test if the address types are the same.
- `NimBLEUtils::dumpGapEvent` function removed.
- `NimBLEUtils::buildHexData` replaced with `NimBLEUtils::dataToHexString`, which returns a `std::string` containing the hex string.
- `NimBLEEddystoneTLM::setTemp` now takes an `int16_t` parameter instead of float to be friendly to devices without floating point support.
- `NimBLEEddystoneTLM::getTemp` now returns `int16_t` to work with devices that don't have floating point support.
- `NimBLEEddystoneTLM::setData` now takes a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
- `NimBLEEddystoneTLM::getData` now returns a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
- `NimBLEBeacon::setData` now takes `const NimBLEBeacon::BeaconData&` instead of `std::string`.
- `NimBLEBeacon::getData` now returns `const NimBLEBeacon::BeaconData&` instead of `std::string`.
- `NimBLEHIDDevice::reportMap` renamed to `NimBLEHIDDevice::getReportMap`.
- `NimBLEHIDDevice::hidControl` renamed to `NimBLEHIDDevice::getHidControl`.
- `NimBLEHIDDevice::inputReport`renamed to `NimBLEHIDDevice::getInputReport`.
- `NimBLEHIDDevice::outputReport`renamed to `NimBLEHIDDevice::getOutputReport`.
- `NimBLEHIDDevice::featureReport`renamed to `NimBLEHIDDevice::getFeatureReport`.
- `NimBLEHIDDevice::protocolMode`renamed to `NimBLEHIDDevice::getProtocolMode`.
- `NimBLEHIDDevice::bootOutput`renamed to `NimBLEHIDDevice::getBootOutput`.
- `NimBLEHIDDevice::pnp`renamed to `NimBLEHIDDevice::setPnp`.
- `NimBLEHIDDevice::hidInfo`renamed to `NimBLEHIDDevice::setHidInfo`.
- `NimBLEHIDDevice::deviceInfo`renamed to `NimBLEHIDDevice::getDeviceInfoService`.
- `NimBLEHIDDevice::hidService`renamed to `NimBLEHIDDevice::getHidService`.
- `NimBLEHIDDevice::batteryService`renamed to `NimBLEHIDDevice::getBatteryService`.
## Fixed
- `NimBLEDevice::getPower` and `NimBLEDevice::getPowerLevel` bug worked around for the esp32s3 and esp32c3.
- `NimBLEDevice::setPower` and `NimBLEDevice::getPower` now support the full power range for all esp devices.
- `NimBLEDevice::setOwnAddrType` will now correctly apply the provided address type for all devices.
- `NimBLEDevice::getPower` (esp32) return value is now calculated to support devices with different min/max ranges.
- Crash if `NimBLEDevice::deinit` is called when the stack has not been initialized.
- `NimBLEServer` service changed notifications will now wait until the changes have taken effect and the server re-started before indicating the change to peers, reducing difficultly for some clients to update their data.
- `NimBLEService::getHandle` will now fetch the handle from the stack if not valid to avoid returning an invalid value.
- `std::vector` input to set/write values template.
- `NimBLEHIDDevice::pnp` will now set the data correctly.
- Check for Arduino component
- Fixed building with esp-idf version 5.x.
- Fixed pairing failing when the process was started by the peer first.
- Fixed building with esp-idf and Arduino component.
- Workaround for esp32s3 and esp32c3 not returning the correct txPower with some IDF versions.
### Changed
- `NimBLEClient::secureConnection` now takes an additional parameter `bool async`, if true, will send the secure command and return immediately with a true value for successfully sending the command, else false. This allows for asynchronously securing a connection.
- Deleting the client instance from the `onDisconnect` callback is now supported.
- `NimBLEClient::connect` will no longer cancel already in progress connections.
- `NimBLEClient::setDataLen` now returns bool, true if successful.
- `NimBLEClient::updateConnParams` now returns bool, true if successful.
- `NimBLEClient::setPeerAddress` now returns a bool, true on success.
- `NimBLEDevice::startSecurity` now takes and additional parameter `int* rcPtr` which will provide the return code from the stack if provided.
- `NimBLEDevice::deleteClient` no longer blocks tasks.
- `NimBLEDevice::getAddress` will now return the address currently in use.
- `NimBLEDevice::init` now returns a bool with `true` indicating success.
- `NimBLEDevice::deinit` now returns a bool with `true` indicating success.
- `NimBLEDevice::setDeviceName` now returns a bool with `true` indicating success.
- `NimBLEDevice::setCustomGapHandler` now returns a bool with `true` indicating success.
- `NimBLEDevice::setOwnAddrType` now returns a bool with `true` indicating success and works with non-esp32 devices.
- `NimBLEDevice::setPower` now returns a bool value, true = success.
- `NimBLEDevice::setMTU` now returns a bool value, true = success.
- `NimBLEDevice::deleteAllBonds` now returns true on success, otherwise false.
- `NimBLEEddystoneTLM` internal data struct type `BeaconData` is now public and usable by the application.
- `NimBLEBeacon` internal data struct type `BeaconData` is now public and can be used by the application.
- Removed tracking of client characteristic subscription status from `NimBLEServer` and `NimBLECharacteristic` and instead uses
the functions and tracking in the host stack.
- `NimBLECharacteristic::indicate` now takes the same parameters as `notify`.
- `NimBLECharacteristic::notify` and `NimBLECharacteristic::indicate` now return a `bool`, true = success.
- Added optional `connHandle` parameter to `NimBLECharacteristic::notify` to allow for sending notifications to specific clients.
- `NimBLEServer` Now uses a std::array to store client connection handles instead of std::vector to reduce memory allocation.
- `NimBLEExtAdvertisement` : All functions that set data now return `bool`, true = success.
- `NimBLEAdvertising` Advertising data is now stored in instances of `NimBLEAdvertisingData` and old vectors removed.
- `NimBLEAdvertising::setAdvertisementData` and `NimBLEAdvertising::setScanResponseData` now return `bool`, true = success.
- Added optional `NimBLEAddress` parameter to `NimBLEAdvertising::start` to allow for directed advertising to a peer.
- All `NimBLEAdvertising` functions that change data values now return `bool`, true = success.
- All `NimBLEAdvertisementData` functions that change data values now return `bool`, true = success.
- `NimBLEAdvertising` advertising complete callback is now defined as std::function to allow for using std::bind for callback functions.
- `NimBLEAdvertisementData::setName` now takes an optional `bool` parameter to indicate if the name is complete or incomplete, default = complete.
- `NimBLEAdvertisementData` moved to it's own .h and .cpp files.
- `NimBLEScan::start` takes a new `bool restart` parameter, default `true`, that will restart an already in progress scan and clear the duplicate filter so all devices will be discovered again.
- Scan response data that is received without advertisement first will now create the device and send a callback.
- `NimBLEScan::start` will no longer clear cache or results if scanning is already in progress.
- `NimBLEScan::start` will now allow the start command to be sent with updated parameters if already scanning.
- `NimBLEScan::clearResults` will now reset the vector capacity to 0.
- Host reset will now no longer restart scanning and instead will call `NimBLEScanCallbacks::onScanEnd`.
- Added optional `index` parameter to `NimBLEAdvertisedDevice::getPayloadByType`
- `NimBLEAdvertisedDevice::getManufacturerData` now takes an optional index parameter for use in the case of multiple manufacturer data fields.
- `NimBLEUtils`: Add missing GAP event strings.
- `NimBLEUtils`: Add missing return code strings.
- `NimBLEUtils`: Event/error code strings optimized.
- `NimBLEAttValue` cleanup and optimization.
- cleaned up code, removed assert/abort calls, replaced with a configurable option to enable debug asserts.
### Added
- (esp32 specific) `NimBLEDevice::setPowerLevel` and `NimBLEDevice::getPowerLevel` which take and return the related `esp_power_level* ` types.
- `NimBLEDevice::setDefaultPhy` which will set the default preferred PHY for all connections.
- `NimBLEDevice::getConnectedClients`, which returns a vector of pointers to the currently connected client instances.
- `NimBLEDevice::setOwnAddr` function added, which takes a `uint8_t*` or `NimBLEAddress&` and will set the mac address of the device, returns `bool` true= success.
- `NimBLEDevice::injectPassKey` Used to send the pairing passkey instead of a return value from the client callback.
- `NimBLEDevice::injectConfirmPasskey` Used to send the numeric comparison pairing passkey confirmation instead of a return value from the client callback.
- `NimBLEDevice::setDeviceName` to change the device name after initialization.
- `NimBLECharacteristic::create2904` which will specifically create a Characteristic Presentation Format (0x2904) descriptor.
- `NimBLEAdvertising::refreshAdvertisingData` refreshes the advertisement data while still actively advertising.
- `NimBLEClient::updatePhy` to request a PHY change with a peer.
- `NimBLEClient::getPhy` to read the current connection PHY setting.
- `Config` struct to `NimBLEClient` to efficiently set single bit config settings.
- `NimBLEClient::setSelfDelete` that takes the bool parameters `deleteOnDisconnect` and `deleteOnConnectFail`, which will configure the client to delete itself when disconnected or the connection attempt fails.
- `NimBLEClient::setConfig` and `NimBLEClient::getConfig` which takes or returns a `NimBLEClient::Config` object respectively.
- `NimBLEClient::cancelConnect()` to cancel an in-progress connection, returns `bool`, true = success.
- Non-blocking `NimBLEClient::connect` option added via 2 new `bool` parameters added to the function:
- * `asyncConnect`; if true, will send the connect command and return immediately.
- * `exchangeMTU`; if true will send the exchange MTU command upon connection.
- `NimBLEClientCallbacks::onConnectFail` callback that is called when the connection attempt fail while connecting asynchronously.
- `NimBLEClientCallbacks::onMTUChange` callback which will be called when the MTU exchange completes and takes a `NimBLEClient*` and `uint16_t MTU` parameter.
- `NimBLEClientCallbacks::onPhyUpdate` and -`NimBLEServerCallbacks::onPhyUpdate` Which are called when the PHY update is complete.
- Extended scan example.
- `NimBLEServer::updatePhy` to request a PHY change with a peer.
- `NimBLEServer::getPhy` to read the PHY of a peer connection.
- `NimBLEServer::getClient` which will create a client instance from the provided peer connHandle or connInfo to facilitate reading/write from the connected client.
- `NimBLEServerCallbacks::onConnParamsUpdate` callback.
- `NimBLEScan::erase` overload that takes a `const NimBLEAdvertisedDevice*` parameter.
- `NimBLEScan::setScanPhy` to enable/disable the PHY's to scan on (extended advertising only).
- `NimBLEScan::setScanPeriod` which will allow for setting a scan restart timer in the controller (extended advertising only).
- `NimBLEAdvertisedDevice::isScannable()` that returns true if the device is scannable.
- `NimBLEAdvertisedDevice::begin` and `NimBLEAdvertisedDevice::end` read-only iterators for convenience and use in range loops.
- `NimBLEAdvertisedDevice::getAdvFlags` returns the advertisement flags of the advertiser.
- `NimBLEAdvertisedDevice::getPayloadByType` Generic use function that returns the data from the advertisement with the specified type.
- `NimBLEAdvertisedDevice::haveType` Generic use function that returns true if the advertisement data contains a field with the specified type.
- Support for esp32c6, esp32c2, esp32h2, and esp32p4.
- `NimBLEExtAdvertisement::removeData`, which will remove the data of the specified type from the advertisement.
- `NimBLEExtAdvertisement::addServiceUUID`, which will append to the service uuids advertised.
- `NimBLEExtAdvertisement::removeServiceUUID`, which will remove the service from the uuids advertised.
- `NimBLEExtAdvertisement::removeServices`, which will remove all service uuids advertised.
- New overloads for `NimBLEExtAdvertisement::setServiceData` with the parameters `const NimBLEUUID& uuid, const uint8_t* data, size_t length` and `const NimBLEUUID& uuid, const std::vector<uint8_t>& data`.
- `NimBLEExtAdvertisement::getDataLocation`, which returns the location in the advertisement data of the type requested in parameter `uint8_t type`.
- `NimBLEExtAdvertisement::toString` which returns a hex string representation of the advertisement data.
- `NimBLEAdvertising::getAdvertisementData`, which returns a reference to the currently set advertisement data.
- `NimBLEAdvertising::getScanData`, which returns a reference to the currently set scan response data.
- New overloads for `NimBLEAdvertising::removeServiceUUID` and `NimBLEAdvertisementData::removeServiceUUID` to accept a `const char*`
- `NimBLEAdvertising::clearData`, which will clear the advertisement and scan response data.
- `NimBLEAdvertising::setManufacturerData` Overload that takes a `const uint8_t*` and , size_t` parameter.
- `NimBLEAdvertising::setServiceData` Overload that takes `const NimBLEUUID& uuid`, ` const uint8_t* data`, ` size_t length` as parameters.
- `NimBLEAdvertising::setServiceData` Overload that takes `const NimBLEUUID& uuid`, `const std::vector<uint8_t>&` as parameters.
- `NimBLEAdvertising::setDiscoverableMode` to allow applications to control the discoverability of the advertiser.
- `NimBLEAdvertising::setAdvertisingCompleteCallback` sets the callback to call when advertising ends.
- `NimBLEAdvertising::setPreferredParams` that takes the min and max preferred connection parameters as an alternative for `setMinPreferred` and `setMaxPreferred`.
- `NimBLEAdvertising::setAdvertisingInterval` Sets the advertisement interval for min and max to the same value instead of calling `setMinInterval` and `setMaxInterval` separately if there is not value difference.
- `NimBLEAdvertisementData::removeData`, which takes a parameter `uint8_t type`, the data type to remove.
- `NimBLEAdvertisementData::toString`, which will print the data in hex.
- `NimBLEUtils::taskWait` which causes the calling task to wait for an event.
- `NimBLEUtils::taskRelease` releases the task from and event.
- `NimBLEUtils::generateAddr` function added with will generate a random address and takes a `bool` parameter, true = create non-resolvable private address, otherwise a random static address is created, returns `NimBLEAddress`.
- `NimBLEUUID::getValue` which returns a read-only `uint8_t` pointer to the UUID value.
- `NimBLEUUID::reverseByteOrder`, this will reverse the bytes of the UUID, which can be useful for advertising/logging.
- `NimBLEUUID` constructor overload that takes a reference to `ble_uuid_any_t`.
- `NimBLEAddress::isNrpa` method to test if an address is random non-resolvable.
- `NimBLEAddress::isStatic` method to test if an address is random static.
- `NimBLEAddress::isPublic` method to test if an address is a public address.
- `NimBLEAddress::isNull` methods to test if an address is NULL.
- `NimBLEAddress::getValue` method which returns a read-only pointer to the address value.
- `NimBLEAddress::reverseByteOrder` method which will reverse the byte order of the address value.
- `NimBLEHIDDevice::batteryLevel` returns the HID device battery level characteristic.
- `NimBLEBeacon::setData` overload that takes `uint8_t* data` and `uint8_t length`.
- `NimBLEHIDDevice::getPnp` function added to access the pnp characteristic.
- `NimBLEHIDDevice::getHidInfo` function added to access the hid info characteristic.
## [1.4.1] - 2022-10-30
### Fixed
- NimBLEDevice::getPower incorrect value when power level is -3db.
- Failed pairing when already in progress.
### Changed
- Revert previous change that forced writing with response when subscribing in favor of allowing the application to decide.
### Added
- Added NimBLEHIDDevice::batteryLevel.
- Added NimBLEDevice::setDeviceName allowing for changing the device name while the BLE stack is active.
- CI Builds
## [1.4.0] - 2022-07-31
### Fixed
- Fixed missing data from long notification values.
- Fixed NimbleCharacteristicCallbacks::onRead not being called when a non-long read command is received.
- Prevent a potential crash when retrieving characteristics from a service if the result was successful but no characteristics found.
- logs/typos.
### Changed
- AD flags are no longer set in the advertisements of non-connectable beacons, freeing up 3 bytes of advertisement room.
- Save resources when retrieving descriptors if the characteristic handle is the same as the end handle (no descriptors).
- Subscribing to characteristic notifications/indications will now always use write with response, as per BLE specifications.
- `NimBLEClient::discoverAttributes` now returns a bool value to indicate success/failure.
- Scan result callbacks are no longer called when the scan response data is updated in order to reduce duplicates.
### Added
- Preliminary support for non-esp devices, NRF51 and NRF52 devices supported with [n-able arduino core](https://github.com/h2zero/n-able-Arduino)
- Alias added for `NimBLEServerCallbacks::onMTUChange` to `onMtuChanged` in order to support porting code from original library.
- `NimBLEAttValue` Class added to reduce and control RAM footprint of characteristic/descriptor values and support conversions from Arduino Strings and many other data types.
- Bluetooth 5 extended advertising support for capable devices. CODED Phy, 2M Phy, extended advertising data, and multi-advertising are supported, periodic advertising will be implemented in the future.
## [1.3.3] - 2022-02-15
### Changed
- If attribute retrieval fails with a "not found" try again with the 16 bit version if a 128 bit base uuid is used.
### Fixed
- Memory leak when deleting client instance.
- IDf version check for data length extension.
- Memory leak when server services changed.
- Compiler warnings for non-esp32 devices.
## [1.3.2] - 2022-01-15
### Fixed
- Initialize advertising complete callback in NimBLEAdvertising constructor.
- Clear client disconnect timer in constructor before initializing.
- Fix missing data when reading large values.
- Fix missing data in notifications when using a large MTU size and more than 270 bytes of data are sent.
- Workaround fix added for cases when the task notification value is not cleared, causing various functions that should block not to block.
### Added
- `NimBLEClient::getLastError` : Gets the error code of the last function call that produces a return code from the stack.
- `NimBLECharacteristic::notify` : Overload method to send notifications/indications with custom values.
- Added conditional checks for ESP32 specific functions/values to support use of the library on non-esp32 devices.
- Added an alias to use the callback name from the original library `onMtuChanged`.
- `NimBLEClient::setDataLen` and `NimBLEServer::setDataLen`: Data length extension support (IDF version >= 4.3.2 only)
- Config option to set logging level for esp-nimble-cpp
### Changed
- Critical section calls now use the NimBLE API instead of FreeRTOS directly. This removes the need for a `portMUX_TYPE` variable in the class definitions.
- Removed unnecessary variables in `NimBLEService` and changed the constructor no no longer accept `numHandles` and `inst_id` parameters.
## [1.3.1] - 2021-08-04
### Fixed
- Corrected a compiler/linker error when an application or a library uses bluetooth classic due to the redefinition of `btInUse`.
## [1.3.0] - 2021-08-02
### Added
- `NimBLECharacteristic::removeDescriptor`: Dynamically remove a descriptor from a characteristic. Takes effect after all connections are closed and sends a service changed indication.
- `NimBLEService::removeCharacteristic`: Dynamically remove a characteristic from a service. Takes effect after all connections are closed and sends a service changed indication
- `NimBLEServerCallbacks::onMTUChange`: This is callback is called when the MTU is updated after connection with a client.
- ESP32C3 support
- Whitelist API:
- `NimBLEDevice::whiteListAdd`: Add a device to the whitelist.
- `NimBLEDevice::whiteListRemove`: Remove a device from the whitelist.
- `NimBLEDevice::onWhiteList`: Check if the device is on the whitelist.
- `NimBLEDevice::getWhiteListCount`: Gets the size of the whitelist
- `NimBLEDevice::getWhiteListAddress`: Get the address of a device on the whitelist by index value.
- Bond management API:
- `NimBLEDevice::getNumBonds`: Gets the number of bonds stored.
- `NimBLEDevice::isBonded`: Checks if the device is bonded.
- `NimBLEDevice::deleteAllBonds`: Deletes all bonds.
- `NimBLEDevice::getBondedAddress`: Gets the address of a bonded device by the index value.
- `NimBLECharacteristic::getCallbacks` to retrieve the current callback handler.
- Connection Information class: `NimBLEConnInfo`.
- `NimBLEScan::clearDuplicateCache`: This can be used to reset the cache of advertised devices so they will be immediately discovered again.
### Changed
- FreeRTOS files have been removed as they are not used by the library.
- Services, characteristics and descriptors can now be created statically and added after.
- Excess logging and some asserts removed.
- Use ESP_LOGx macros to enable using local log level filtering.
### Fixed
- `NimBLECharacteristicCallbacks::onSubscribe` Is now called after the connection is added to the vector.
- Corrected bonding failure when reinitializing the BLE stack.
- Writing to a characteristic with a std::string value now correctly writes values with null characters.
- Retrieving remote descriptors now uses the characteristic end handle correctly.
- Missing data in long writes to remote descriptors.
- Hanging on task notification when sending an indication from the characteristic callback.
- BLE controller memory could be released when using Arduino as a component.
- Compile errors with NimBLE release 1.3.0.
## [1.2.0] - 2021-02-08
@ -13,7 +452,7 @@ All notable changes to this project will be documented in this file.
- `NimBLEService::getCharacteristicByHandle`: Get a pointer to the characteristic object with the specified handle.
- `NimBLEService::getCharacteristics`: Get the vector containing pointers to each characteristic associated with this service.
- `NimBLEService::getCharacteristics`: Get the vector containing pointers to each characteristic associated with this service.
Overloads to get a vector containing pointers to all the characteristics in a service with the UUID. (supports multiple same UUID's in a service)
- `NimBLEService::getCharacteristics(const char *uuid)`
- `NimBLEService::getCharacteristics(const NimBLEUUID &uuid)`
@ -55,12 +494,12 @@ Overloads to get a vector containing pointers to all the characteristics in a se
- `NimBLEAdvertising` Transmission power is no longer advertised by default and can be added to the advertisement by calling `NimBLEAdvertising::addTxPower`
- `NimBLEAdvertising` Custom scan response data can now be used without custom advertisment.
- `NimBLEAdvertising` Custom scan response data can now be used without custom advertisement.
- `NimBLEScan` Now uses the controller duplicate filter.
- `NimBLEScan` Now uses the controller duplicate filter.
- `NimBLEAdvertisedDevice` Has been refactored to store the complete advertisement payload and no longer parses the data from each advertisement.
Instead the data will be parsed on-demand when the user application asks for specific data.
- `NimBLEAdvertisedDevice` Has been refactored to store the complete advertisement payload and no longer parses the data from each advertisement.
Instead the data will be parsed on-demand when the user application asks for specific data.
### Fixed
- `NimBLEHIDDevice` Characteristics now use encryption, this resolves an issue with communicating with devices requiring encryption for HID devices.
@ -69,84 +508,84 @@ Instead the data will be parsed on-demand when the user application asks for spe
## [1.1.0] - 2021-01-20
### Added
- `NimBLEDevice::setOwnAddrType` added to enable the use of random and random-resolvable addresses, by asukiaaa
- `NimBLEDevice::setOwnAddrType` added to enable the use of random and random-resolvable addresses, by asukiaaa
- New examples for securing and authenticating client/server connections, by mblasee.
- New examples for securing and authenticating client/server connections, by mblasee.
- `NimBLEAdvertising::SetMinPreferred` and `NimBLEAdvertising::SetMinPreferred` re-added.
- `NimBLEAdvertising::SetMinPreferred` and `NimBLEAdvertising::SetMinPreferred` re-added.
- Conditional checks added for command line config options in `nimconfig.h` to support custom configuration in platformio.
- Conditional checks added for command line config options in `nimconfig.h` to support custom configuration in platformio.
- `NimBLEClient::setValue` Now takes an extra bool parameter `response` to enable the use of write with response (default = false).
- `NimBLEClient::setValue` Now takes an extra bool parameter `response` to enable the use of write with response (default = false).
- `NimBLEClient::getCharacteristic(uint16_t handle)` Enabling the use of the characteristic handle to be used to find
the NimBLERemoteCharacteristic object.
- `NimBLEClient::getCharacteristic(uint16_t handle)` Enabling the use of the characteristic handle to be used to find
the NimBLERemoteCharacteristic object.
- `NimBLEHIDDevice` class added by wakwak-koba.
- `NimBLEHIDDevice` class added by wakwak-koba.
- `NimBLEServerCallbacks::onDisconnect` overloaded callback added to provide a ble_gap_conn_desc parameter for the application
to obtain information about the disconnected client.
- `NimBLEServerCallbacks::onDisconnect` overloaded callback added to provide a ble_gap_conn_desc parameter for the application
to obtain information about the disconnected client.
- Conditional checks in `nimconfig.h` for command line defined macros to support platformio config settings.
- Conditional checks in `nimconfig.h` for command line defined macros to support platformio config settings.
### Changed
- `NimBLEAdvertising::start` now returns a bool value to indicate success/failure.
- `NimBLEAdvertising::start` now returns a bool value to indicate success/failure.
- Some asserts were removed in `NimBLEAdvertising::start` and replaced with better return code handling and logging.
- Some asserts were removed in `NimBLEAdvertising::start` and replaced with better return code handling and logging.
- If a host reset event occurs, scanning and advertising will now only be restarted if their previous duration was indefinite.
- If a host reset event occurs, scanning and advertising will now only be restarted if their previous duration was indefinite.
- `NimBLERemoteCharacteristic::subscribe` and `NimBLERemoteCharacteristic::registerForNotify` will now set the callback
regardless of the existance of the CCCD and return true unless the descriptor write operation failed.
regardless of the existence of the CCCD and return true unless the descriptor write operation failed.
- Advertising tx power level is now sent in the advertisement packet instead of scan response.
- Advertising tx power level is now sent in the advertisement packet instead of scan response.
- `NimBLEScan` When the scan ends the scan stopped flag is now set before calling the scan complete callback (if used)
this allows the starting of a new scan from the callback function.
- `NimBLEScan` When the scan ends the scan stopped flag is now set before calling the scan complete callback (if used)
this allows the starting of a new scan from the callback function.
### Fixed
- Sometimes `NimBLEClient::connect` would hang on the task block if no event arrived to unblock.
A time limit has been added to timeout appropriately.
- Sometimes `NimBLEClient::connect` would hang on the task block if no event arrived to unblock.
A time limit has been added to timeout appropriately.
- When getting descriptors for a characterisic the end handle of the service was used as a proxy for the characteristic end
handle. This would be rejected by some devices and has been changed to use the next characteristic handle as the end when possible.
- When getting descriptors for a characteristic the end handle of the service was used as a proxy for the characteristic end
handle. This would be rejected by some devices and has been changed to use the next characteristic handle as the end when possible.
- An exception could occur when deleting a client instance if a notification arrived while the attribute vectors were being
deleted. A flag has been added to prevent this.
- An exception could occur after a host reset event when the host re-synced if the tasks that were stopped during the event did
not finish processing. A yield has been added after re-syncing to allow tasks to finish before proceeding.
- Occasionally the controller would fail to send a disconnected event causing the client to indicate it is connected
and would be unable to reconnect. A timer has been added to reset the host/controller if it expires.
- Occasionally the call to start scanning would get stuck in a loop on BLE_HS_EBUSY, this loop has been removed.
- An exception could occur when deleting a client instance if a notification arrived while the attribute vectors were being
deleted. A flag has been added to prevent this.
- 16bit and 32bit UUID's in some cases were not discovered or compared correctly if the device
advertised them as 16/32bit but resolved them to 128bits. Both are now checked.
- `FreeRTOS` compile errors resolved in latest Ardruino core and IDF v3.3.
- An exception could occur after a host reset event when the host re-synced if the tasks that were stopped during the event did
not finish processing. A yield has been added after re-syncing to allow tasks to finish before proceeding.
- Multiple instances of `time()` called inside critical sections caused sporadic crashes, these have been moved out of critical regions.
- Occasionally the controller would fail to send a disconnected event causing the client to indicate it is connected
and would be unable to reconnect. A timer has been added to reset the host/controller if it expires.
- Advertisement type now correctly set when using non-connectable (advertiser only) mode.
- Occasionally the call to start scanning would get stuck in a loop on BLE_HS_EBUSY, this loop has been removed.
- Advertising payload length correction, now accounts for appearance.
- 16bit and 32bit UUID's in some cases were not discovered or compared correctly if the device
advertised them as 16/32bit but resolved them to 128bits. Both are now checked.
- (Arduino) Ensure controller mode is set to BLE Only.
- `FreeRTOS` compile errors resolved in latest Arduino core and IDF v3.3.
- Multiple instances of `time()` called inside critical sections caused sporadic crashes, these have been moved out of critical regions.
- Advertisement type now correctly set when using non-connectable (advertiser only) mode.
- Advertising payload length correction, now accounts for appearance.
- (Arduino) Ensure controller mode is set to BLE Only.
## [1.0.2] - 2020-09-13
### Changed
- `NimBLEAdvertising::start` Now takes 2 optional parameters, the first is the duration to advertise for (in seconds), the second is a
callback that is invoked when advertsing ends and takes a pointer to a `NimBLEAdvertising` object (similar to the `NimBLEScan::start` API).
- `NimBLEAdvertising::start` Now takes 2 optional parameters, the first is the duration to advertise for (in seconds), the second is a
callback that is invoked when advertising ends and takes a pointer to a `NimBLEAdvertising` object (similar to the `NimBLEScan::start` API).
- (Arduino) Maximum BLE connections can now be altered by only changing the value of `CONFIG_BT_NIMBLE_MAX_CONNECTIONS` in `nimconfig.h`.
Any changes to the controller max connection settings in `sdkconfig.h` will now have no effect when using this library.
- (Arduino) Revert the previous change to fix the advertising start delay. Instead a replacement fix that routes all BLE controller commands from
- (Arduino) Revert the previous change to fix the advertising start delay. Instead a replacement fix that routes all BLE controller commands from
a task running on core 0 (same as the controller) has been implemented. This improves response times and reliability for all BLE functions.

View File

@ -2,50 +2,67 @@
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
idf_build_get_property(__hack_component_targets __COMPONENT_TARGETS)
if("esp-nimble-component" IN_LIST BUILD_COMPONENTS OR "__esp-nimble-component" IN_LIST __hack_component_targets)
if(__COMPONENT_TARGETS MATCHES "___idf_esp-nimble-component")
list(APPEND ESP_NIMBLE_PRIV_REQUIRES
esp-nimble-component
)
elseif("nimble" IN_LIST BUILD_COMPONENTS OR "__nimble" IN_LIST __hack_component_targets)
elseif(__COMPONENT_TARGETS MATCHES "__idf_nimble")
list(APPEND ESP_NIMBLE_PRIV_REQUIRES
nimble
)
endif()
if("arduino" IN_LIST BUILD_COMPONENTS OR __hack_component_targets MATCHES "__idf_arduino")
# Arduino install using IDF component manager
if(__COMPONENT_TARGETS MATCHES "___idf_espressif__arduino-esp32")
list(APPEND ESP_NIMBLE_PRIV_REQUIRES
arduino-esp32
)
# Manual installation of Arduino framework
elseif(__COMPONENT_TARGETS MATCHES "__idf_arduino")
list(APPEND ESP_NIMBLE_PRIV_REQUIRES
arduino
)
# PlatformIO
elseif(__COMPONENT_TARGETS MATCHES "___idf_framework-arduinoespressif32")
list(APPEND ESP_NIMBLE_PRIV_REQUIRES
framework-arduinoespressif32
)
endif()
idf_component_register(
REQUIRED_IDF_TARGETS
"esp32"
"esp32s3"
"esp32c2"
"esp32c3"
"esp32c5"
"esp32c6"
"esp32h2"
"esp32p4"
INCLUDE_DIRS
"src"
SRCS
"src/FreeRTOS.cpp"
"src/NimBLE2904.cpp"
"src/NimBLEAddress.cpp"
"src/NimBLEAdvertisedDevice.cpp"
"src/NimBLEAdvertisementData.cpp"
"src/NimBLEAdvertising.cpp"
"src/NimBLEAttValue.cpp"
"src/NimBLEBeacon.cpp"
"src/NimBLECharacteristic.cpp"
"src/NimBLEClient.cpp"
"src/NimBLEDescriptor.cpp"
"src/NimBLEDevice.cpp"
"src/NimBLEEddystoneTLM.cpp"
"src/NimBLEEddystoneURL.cpp"
"src/NimBLEExtAdvertising.cpp"
"src/NimBLEHIDDevice.cpp"
"src/NimBLEL2CAPChannel.cpp"
"src/NimBLEL2CAPServer.cpp"
"src/NimBLERemoteCharacteristic.cpp"
"src/NimBLERemoteDescriptor.cpp"
"src/NimBLERemoteService.cpp"
"src/NimBLERemoteValueAttribute.cpp"
"src/NimBLEScan.cpp"
"src/NimBLESecurity.cpp"
"src/NimBLEServer.cpp"
"src/NimBLEService.cpp"
"src/NimBLEUtils.cpp"
@ -53,6 +70,7 @@ idf_component_register(
REQUIRES
bt
nvs_flash
driver
PRIV_REQUIRES
${ESP_NIMBLE_PRIV_REQUIRES}
)

View File

@ -1,57 +0,0 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
set(SUPPORTED_TARGETS esp32)
set(COMPONENT_SRCS
"src/FreeRTOS.cpp"
"src/NimBLE2904.cpp"
"src/NimBLEAddress.cpp"
"src/NimBLEAdvertisedDevice.cpp"
"src/NimBLEAdvertising.cpp"
"src/NimBLEBeacon.cpp"
"src/NimBLECharacteristic.cpp"
"src/NimBLEClient.cpp"
"src/NimBLEDescriptor.cpp"
"src/NimBLEDevice.cpp"
"src/NimBLEEddystoneTLM.cpp"
"src/NimBLEEddystoneURL.cpp"
"src/NimBLEHIDDevice.cpp"
"src/NimBLERemoteCharacteristic.cpp"
"src/NimBLERemoteDescriptor.cpp"
"src/NimBLERemoteService.cpp"
"src/NimBLEScan.cpp"
"src/NimBLESecurity.cpp"
"src/NimBLEServer.cpp"
"src/NimBLEService.cpp"
"src/NimBLEUtils.cpp"
"src/NimBLEUUID.cpp"
)
set(COMPONENT_ADD_INCLUDEDIRS
src
)
set(COMPONENT_PRIV_REQUIRES
nvs_flash
bt
)
if(COMPONENTS MATCHES "esp-nimble-component")
list(APPEND COMPONENT_PRIV_REQUIRES
esp-nimble-component
)
elseif(COMPONENTS MATCHES "nimble")
list(APPEND COMPONENT_PRIV_REQUIRES
nimble
)
endif()
if(COMPONENTS MATCHES "arduino")
list(APPEND COMPONENT_PRIV_REQUIRES
arduino
)
endif()
register_component()

237
Kconfig
View File

@ -1,5 +1,138 @@
menu "ESP-NimBLE-CPP configuration"
choice NIMBLE_CPP_LOG_LEVEL
prompt "NimBLE CPP log verbosity"
default NIMBLE_CPP_LOG_LEVEL_NONE
help
Select NimBLE CPP log verbosity level.
config NIMBLE_CPP_LOG_LEVEL_NONE
bool "No logs"
config NIMBLE_CPP_LOG_LEVEL_ERROR
bool "Error logs"
config NIMBLE_CPP_LOG_LEVEL_WARNING
bool "Warning logs"
config NIMBLE_CPP_LOG_LEVEL_INFO
bool "Info logs"
config NIMBLE_CPP_LOG_LEVEL_DEBUG
bool "Debug logs"
endchoice #NIMBLE_CPP_LOG_LEVEL
config NIMBLE_CPP_LOG_LEVEL
int
default 0 if NIMBLE_CPP_LOG_LEVEL_NONE
default 1 if NIMBLE_CPP_LOG_LEVEL_ERROR
default 2 if NIMBLE_CPP_LOG_LEVEL_WARNING
default 3 if NIMBLE_CPP_LOG_LEVEL_INFO
default 4 if NIMBLE_CPP_LOG_LEVEL_DEBUG
config NIMBLE_CPP_LOG_OVERRIDE_COLOR
bool "Enable log color override."
default "n"
help
Enabling this option will allow NimBLE log levels to have
specific colors assigned.
menu "NIMBLE Log Override Colors"
depends on NIMBLE_CPP_LOG_OVERRIDE_COLOR
choice NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR
prompt "NimBLE CPP log override color Error"
default NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_NONE
help
Select NimBLE CPP log override error color.
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_NONE
bool "None"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_BLACK
bool "Black"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_RED
bool "Red"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_GREEN
bool "Green"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_YELLOW
bool "Yellow"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_BLUE
bool "Blue"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_PURPLE
bool "Purple"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR_CYAN
bool "Cyan"
endchoice #NIMBLE_CPP_LOG_OVERRIDE_COLOR_ERR
choice NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN
prompt "NimBLE CPP log override color Warning"
default NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_NONE
help
Select NimBLE CPP log override warning color.
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_NONE
bool "None"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_BLACK
bool "Black"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_RED
bool "Red"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_GREEN
bool "Green"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_YELLOW
bool "Yellow"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_BLUE
bool "Blue"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_PURPLE
bool "Purple"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN_CYAN
bool "Cyan"
endchoice #NIMBLE_CPP_LOG_OVERRIDE_COLOR_WARN
choice NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO
prompt "NimBLE CPP log override color Info"
default NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_NONE
help
Select NimBLE CPP log override info color.
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_NONE
bool "None"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_BLACK
bool "Black"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_RED
bool "Red"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_GREEN
bool "Green"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_YELLOW
bool "Yellow"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_BLUE
bool "Blue"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_PURPLE
bool "Purple"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO_CYAN
bool "Cyan"
endchoice #NIMBLE_CPP_LOG_OVERRIDE_COLOR_INFO
choice NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG
prompt "NimBLE CPP log override color Debug"
default NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_NONE
help
Select NimBLE CPP log override debug color.
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_NONE
bool "None"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_BLACK
bool "Black"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_RED
bool "Red"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_GREEN
bool "Green"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_YELLOW
bool "Yellow"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_BLUE
bool "Blue"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_PURPLE
bool "Purple"
config NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG_CYAN
bool "Cyan"
endchoice #NIMBLE_CPP_LOG_OVERRIDE_COLOR_DEBUG
endmenu
config NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT
bool "Show NimBLE return codes as text in debug log."
default "n"
@ -7,7 +140,7 @@ config NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT
Enabling this option will display return code values as text
messages in the debug log. This will use approximately 8kB
of flash memory.
config NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT
bool "Show NimBLE gap events as text in debug log."
default "n"
@ -16,12 +149,106 @@ config NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT
messages in the debug log. This will use approximately 1kB
of flash memory.
config NIMBLE_CPP_ENABLE_ADVERTISMENT_TYPE_TEXT
config NIMBLE_CPP_ENABLE_ADVERTISEMENT_TYPE_TEXT
bool "Show advertisment types as text in debug log."
default "n"
help
Enabling this option will display advertisment types recieved
while scanning as text messages in the debug log.
while scanning as text messages in the debug log.
This will use approximately 250 bytes of flash memory.
endmenu
config NIMBLE_CPP_ADDR_FMT_EXCLUDE_DELIMITER
bool "Exclude colon characters when printing address."
default "n"
help
Enabling this option will format MAC addresses without
colon characters when printing.
config NIMBLE_CPP_ADDR_FMT_UPPERCASE
bool "Use uppercase letters when printing address."
default "n"
help
Enabling this option will format MAC addresses in
uppercase letters when printing.
config NIMBLE_CPP_ATT_VALUE_TIMESTAMP_ENABLED
bool "Enable timestamps to be stored with attribute values."
default "n"
help
Enabling this option will store the timestamp when an attribute value is updated.
This allows for checking the last update time using getTimeStamp()
or getValue(time_t*). If disabled, the timestamp returned from these functions will be 0.
Disabling timestamps will reduce the memory used for each value.
config NIMBLE_CPP_ATT_VALUE_INIT_LENGTH
int "Initial attribute value size (bytes) for empty values."
range 1 512
default 20
help
Sets the default allocation size (bytes) for each attribute if not specified
when the constructor is called. This is also the size used when a remote
characteristic or descriptor is constructed before a value is read/notifed.
Increasing this will reduce reallocations but increase memory footprint.
config NIMBLE_CPP_DEBUG_ASSERT_ENABLED
bool "Enable debug asserts."
default "n"
help
Enabling this option will add debug asserts to the NimBLE CPP library.
This will use approximately 1kB of flash memory.
config NIMBLE_CPP_FREERTOS_TASK_BLOCK_BIT
int "FreeRTOS task block bit."
default 31
help
Configure the bit to set in the task notification value when a task is blocked waiting for an event.
This should be set to a bit that is not used by other notifications in the system.
#
# BT config
#
config BT_ENABLED
bool "Bluetooth"
default "y"
help
Select this option to enable Bluetooth and show the submenu with Bluetooth configuration choices.
config BT_NIMBLE_ENABLED
bool "NimBLE - BLE only"
default "y"
help
This option is recommended for BLE only usecases to save on memory
if IDF_TARGET_ESP32P4
config BT_NIMBLE_TRANSPORT_UART
bool "Enable Uart Transport"
default "n"
#
# Enable ESP Hosted BT
# Used as VHCI transport between BT Host and Controller
#
config ESP_ENABLE_BT
bool "Enable Hosted Bluetooth support"
default "y"
help
Enable Bluetooth Support via Hosted
choice ESP_WIFI_REMOTE_LIBRARY
prompt "Choose WiFi-remote implementation"
default ESP_WIFI_REMOTE_LIBRARY_HOSTED
help
Select type of WiFi Remote implementation
ESP-HOSTED is the default and most versatile option.
It's also possible to use EPPP, which uses PPPoS link between micros and NAPT, so it's slower
and less universal.
config ESP_WIFI_REMOTE_LIBRARY_HOSTED
bool "ESP-HOSTED"
endchoice
endif
endmenu

View File

@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {2020} {Ryan Powell}
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
@ -199,5 +199,3 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This product partly derives from esp32-snippets; Copyright 2017 Neil Kolban.

10
NOTICE Normal file
View File

@ -0,0 +1,10 @@
esp-nimble-cpp
NimBLE-Arduino
Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
esp-nimble-cpp, NimBLE-Arduino contributors.
The Initial Developer of some parts of this library, which are copied from,
derived from, or inspired by is, esp32-snippets, Copyright 2017 Neil Kolban.
If this library is used for commercial purposes, it is requested that the user consider
making a donation and/or sponsoring this project to support it's ongoing development.

View File

@ -1,19 +1,20 @@
[Latest release ![Release Version](https://img.shields.io/github/release/h2zero/esp-nimble-cpp.svg?style=plastic)
[![Release Version](https://img.shields.io/github/release/h2zero/esp-nimble-cpp.svg?style=plastic)
![Release Date](https://img.shields.io/github/release-date/h2zero/esp-nimble-cpp.svg?style=plastic)](https://github.com/h2zero/esp-nimble-cpp/releases/latest/)
Need help? Have questions or suggestions? Join the [![Gitter](https://badges.gitter.im/NimBLE-Arduino/community.svg)](https://gitter.im/NimBLE-Arduino/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
<br/>
> [!IMPORTANT]
> Version 2 is now released!
> Check out the [1.x to 2.x Migration Guide](docs/1.x_to2.x_migration_guide.md) and [Release Notes](https://github.com/h2zero/esp-nimble-cpp/releases/latest/)
# esp-nimble-cpp
NimBLE CPP library for use with ESP32 that attempts to maintain compatibility with the [nkolban cpp_uitls BLE API](https://github.com/nkolban/esp32-snippets/tree/master/cpp_utils).
NimBLE CPP library for use with ESP32 that attempts to maintain compatibility with the [nkolban cpp_utils BLE API](https://github.com/nkolban/esp32-snippets/tree/master/cpp_utils).
**An Arduino version of this library, including NimBLE, can be [found here.](https://github.com/h2zero/NimBLE-Arduino)**
This library **significantly** reduces resource usage and improves performance for ESP32 BLE applications as compared
with the bluedroid based library. The goal is to maintain, as much as reasonable, compatibility with the original
library but refactored to use the NimBLE stack. In addition, this library will be more actively developed and maintained
to provide improved capabilites and stability over the original.
library but using the NimBLE stack. In addition, this library will be more actively developed and maintained
to provide improved capabilities and stability over the original.
**Testing shows a nearly 50% reduction in flash use and approx. 100kB less ram consumed vs the original!**
*Your results may vary*
@ -35,16 +36,6 @@ Configure settings in `NimBLE Options`.
Call `NimBLEDevice::init("");` in `app_main`.
<br/>
### ESP-IDF v3.2 & v3.3
The NimBLE component does not come with these versions of IDF (now included in 3.3.2 and above).
A backport that works in these versions has been created and is [available here](https://github.com/h2zero/esp-nimble-component).
Download or clone that repo into your project/components folder and run menuconfig.
Configure settings in `main menu -> NimBLE Options`.
`#include "NimBLEDevice.h"` in main.cpp.
Call `NimBLEDevice::init("");` in `app_main`.
<br/>
# Using
This library is intended to be compatible with the original ESP32 BLE functions and types with minor changes.
@ -62,15 +53,17 @@ When using this library along with Arduino and compiling with *CMake* you must a
in your project/CMakeLists.txt after the line `include($ENV{IDF_PATH}/tools/cmake/project.cmake)` to prevent Arduino from releasing BLE memory.
<br>
# Sponsors
Thank you to all the sponsors who support this project!
<!-- sponsors --><!-- sponsors -->
If you use this library for a commercial product please consider [sponsoring the development](https://github.com/sponsors/h2zero) to ensure the continued updates and maintenance.
<br/>
# Acknowledgments
* [nkolban](https://github.com/nkolban) and [chegewara](https://github.com/chegewara) for the [original esp32 BLE library](https://github.com/nkolban/esp32-snippets/tree/master/cpp_utils) this project was derived from.
* [beegee-tokyo](https://github.com/beegee-tokyo) for contributing your time to test/debug and contributing the beacon examples.
* [Jeroen88](https://github.com/Jeroen88) for the amazing help debugging and improving the client code.
<br/>
# Todo
- Improve host reset handler
- Implement random address handling
- Implement bond management
- Add Bluetooth Mesh
<br/>

View File

@ -1,2 +0,0 @@
COMPONENT_ADD_INCLUDEDIRS := src
COMPONENT_SRCDIRS := src

View File

@ -0,0 +1,168 @@
# Migrating from 1.x to 2.x
Nearly all of the codebase has been updated and changed under the surface, which has greatly reduced the resource use of the library and improved it's performance. To be able to support these changes it required various API changes and additions.
This guide will help you migrate your application code to use the new API.
The changes listed here are only the required changes that must be made, and a short overview of options for migrating existing applications.
* [General changes](#general-changes)
* [BLE Device](#ble-device)
* [BLE Addresses](#ble-addresses)
* [BLE UUID's](#ble-uuids)
* [Server](#server)
* [Services](#services)
* [Characteristics](#characteristics)
* [Characteristic Callbacks](#characteristic-callbacks)
* [Security](#server)
* [Client](#client)
* [Client Callbacks](#client-callbacks)
* [Remote Services](#remote-services)
* [Remote characteristics](#remote-characteristics)
* [Scanning](#scan)
* [Advertise device](#advertised-device)
* [Advertising](#advertising)
* [Beacons](#beacons)
* [Utilities](#utilities)
<br/>
## General changes
- All functions that take a time parameter now require the time in milliseconds instead of seconds, i.e. `NimBLEScan::start(10000); // 10 seconds`
- `NimBLESecurity` class has been removed it's functionality has been merged into the `NimBLEServer` and `NimBLEClient` classes.
- All connection oriented callbacks now receive a reference to `NimBLEConnInfo` and the `ble_gap_conn_desc` parameter has been replaced with `NimBLEConnInfo` in the functions that received it.
For instance `onAuthenticationComplete(ble_gap_conn_desc* desc)` signature is now `onAuthenticationComplete(NimBLEConnInfo& connInfo)` and
`NimBLEServerCallbacks::onConnect(NimBLEServer* pServer)` signature is now `NimBLEServerCallbacks::onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo)`.
<br/>
## BLE Device
- Ignore list functions and vector have been removed, the application should implement this if desired. It was no longer used by the library.
- `NimBLEDevice::startSecurity` now returns a `bool`, true on success, instead of an int to be consistent with the rest of the library.
- `NimBLEDevice::getInitialized` renamed to `NimBLEDevice::isInitialized`.
- `NimBLEDevice::setPower` no longer takes the `esp_power_level_t` and `esp_ble_power_type_t`, instead only an integer value in dbm units is accepted, so instead of `ESP_PWR_LVL_P9` an `int8_t` value of `9` would be used for the same result.
- `NimBLEDevice::setOwnAddrType` no longer takes a `bool nrpa` parameter, the random address type will be determined by the bits the in the address instead.
Note: If setting a custom address, it should be set with `NimBLEDevice::setOwnAddr` first before calling `NimBLEDevice::setOwnAddrType`.
- `NimBLEDevice::getClientListSize` replaced with `NimBLEDevice::getCreatedClientCount`.
- `NimBLEDevice::getClientList` was removed and `NimBLEDevice::getConnectedClients` can be used instead which returns a `std::vector` of pointers to the connected client instances. This was done because internally the clients are managed in a `std::array` which replaced the 'std::list`.
- `NimBLEDevice::getClientByID(uint16_t conn_id);` has been changed to `NimBLEDevice::getClientByHandle(uint16_t connHandle)`
<br/>
## BLE Addresses
NimBLEAddress comparisons have changed to now consider the address type. If 2 address values are the same but the type is different then they are no longer considered equal. This is a correction to the 1.x version which did not consider the type, whereas the BLE specification states:
> Whenever two device addresses are compared, the comparison shall include the device address type (i.e. if the two addresses have different types, they are different even if the two 48-bit addresses are the same).
This means that if in your application you create a NimBLEAddress instance and are comparing a scan result or some other address created by the library and you did not define the address type then the comparison may fail.
The default address type is public `0`, whereas many devices use a random `1` address type.
If you experience this issue please create your address instances with the address type specified, i.e. `NimBLEAddress address("11:22:33:44:55:66", TYPE_HERE)`
`NimBLEAddress::getNative` has been removed and replaced with `NimBLEAddress::getBase`.
This returns a pointer to `const ble_addr_t` instead of a pointer to the address value that `getNative` did. The value can be accessed through this struct via `ble_addr_t.value` and type is in `ble_addr_t.type`.
<br/>
## BLE UUID's
- `NimBLEUUID::getNative` method replaced with `NimBLEUUID::getBase` which returns a read-only pointer to the underlying `ble_uuid_t` struct.
- `NimBLEUUID`; `msbFirst` parameter has been removed from constructor, caller should reverse the data first or call the new `NimBLEUUID::reverseByteOrder` method after.
<br/>
## Server
- `NimBLEServer::disconnect` now returns `bool`, true = success, instead of `int` to be consistent with the rest of the library.
- `NimBLEServerCallbacks::onMTUChanged` renamed to `NimBLEServerCallbacks::onMTUChange` to be consistent with the client callback.
- `NimBLEServer::getPeerIDInfo` renamed to `NimBLEServer::getPeerInfoByHandle` to better describe it's use.
- Advertising is no longer automatically restarted when a peer disconnects, to re-enable this feature either call `NimBLEServer::advertiseOnDisconnect(true);` after creating the server or manually restart advertising in the `onDisconnect` callback.
<br/>
### Services
- `NimBLEService::getCharacteristics` now returns a `const std::vector<NimBLECharacteristic*>&` instead of a copy of the vector.
<br/>
### Characteristics
- `NimBLECharacteristic::notify` no longer takes a `bool is_notification` parameter, instead `NimBLECharacteristic::indicate` should be called to send indications.
<br/>
#### Characteristic callbacks
- `NimBLECharacteristicCallbacks::onNotify` removed as unnecessary, the library does not call notify without app input.
- `NimBLECharacteristicCallbacks::onStatus` No longer takes a `status` parameter, refer to the return code parameter for success/failure.
<br/>
### Server Security
- `NimBLEServerCallbacks::onPassKeyRequest` has been renamed to `NimBLEServerCallbacks::onPassKeyDisplay` as it is intended that the device should display the passkey for the client to enter.
- `NimBLEServerCallbacks::onAuthenticationComplete` now takes a `NimBLEConnInfo&` parameter.
<br/>
## Client
- `NimBLEClient::getServices` now returns a const reference to std::vector<NimBLERemoteService*> instead of a pointer to the internal vector.
- `NimBLEClient::getConnId` has been renamed to `getConnHandle` to be consistent with bluetooth terminology.
- `NimBLEClient::disconnect` now returns a `bool`, true on success, instead of an `int` to be consistent with the rest of the library.
<br/>
### Client callbacks
- `NimBLEClientCallbacks::onConfirmPIN` renamed to `NimBLEClientCallbacks::onConfirmPasskey`, takes a `NimBLEConnInfo&` parameter and no longer returns a value. This should be used to prompt a user to confirm the pin on the display (YES/NO) after which the response should be sent with `NimBLEDevice::injectConfirmPasskey`.
- `NimBLEClientCallbacks::onPassKeyRequest` has been changed to `NimBLEClientCallbacks::onPassKeyEntry` which takes a `NimBLEConnInfo&` parameter and no longer returns a value. Instead of returning a value this callback should prompt a user to enter a passkey number which is sent later via `NimBLEDevice::injectPassKey`.
<br/>
### Remote Services
- `NimBLERemoteService::getCharacteristics` now returns a `const std::vector<NimBLERemoteCharacteristic*>&` instead of non-const `std::vector<NimBLERemoteCharacteristic*>*`.
<br/>
### Remote Characteristics
- `NimBLERemoteCharacteristic::getRemoteService` now returns a `const NimBLERemoteService*` instead of non-const.
- `NimBLERemoteCharacteristic::registerForNotify`, has been removed, the application should use `NimBLERemoteCharacteristic::subscribe` and `NimBLERemoteCharacteristic::unSubscribe`.
`NimBLERemoteCharacteristic::readUInt32`
`NimBLERemoteCharacteristic::readUInt16`
`NimBLERemoteCharacteristic::readUInt8`
`NimBLERemoteCharacteristic::readFloat`
Have been removed, instead the application should use `NimBLERemoteCharacteristic::readValue<type\>`.
<br/>
## Scan
- `NimBLEScan::stop` will no longer call the `onScanEnd` callback as the caller should know it has been stopped either by initiating a connection or calling this function itself.
- `NimBLEScan::clearDuplicateCache` has been removed as it was problematic and only for the original esp32. The application should stop and start the scanner for the same effect or call `NimBLEScan::start` with the new `bool restart` parameter set to true.
- `NimBLEScanResults::getDevice` methods now return `const NimBLEAdvertisedDevice*` instead of a non-const pointer.
- `NimBLEScanResults` iterators are now `const_iterator`.
- The callback parameter for `NimBLEScan::start` has been removed and the blocking overload of `NimBLEScan::start` has been replaced by an overload of `NimBLEScan::getResults` with the same parameters.
So if your code prior was this:
NimBLEScanResults results = pScan->start(10, false);
It should now be:
NimBLEScanResults results = pScan->getResults(10000, false); // note the time is now in milliseconds
- `NimBLEAdvertisedDeviceCallbacks` Has been replaced by `NimBLEScanCallbacks` which contains the following methods:
- - `NimBLEScanCallbacks::onResult`, functions the same as the old `NimBLEAdvertisedDeviceCallbacks::onResult` but now takes aa `const NimBLEAdvertisedDevice*` instead of non-const.
- - `NimBLEScanCallbacks::onScanEnd`, replaces the scanEnded callback passed to `NimBLEScan::start` and now takes a `const NimBLEScanResults&` and `int reason` parameter.
- - `NimBLEScanCallbacks::onDiscovered`, This is called immediately when a device is first scanned, before any scan response data is available and takes a `const NimBLEAdvertisedDevice*` parameter.
- `NimBLEScan::setAdvertisedDeviceCallbacks(NimBLEAdvertisedDeviceCallbacks* callbacks, bool wantDuplicates)` has been changed to `NimBLEScan::setScanCallbacks(NimBLEScanCallbacks* callbacks, bool wantDuplicates);`
<br/>
### Advertised Device
- `NimBLEAdvertisedDevice::hasRSSI` removed as redundant, RSSI is always available.
- `NimBLEAdvertisedDevice::getPayload` now returns `const std::vector<uint8_t>&` instead of a pointer to internal memory.
- `NimBLEAdvertisedDevice` Timestamp removed, if needed then the app should track the time from the callback.
<br/>
## Advertising
- `NimBLEAdvertising::setMinPreferred` and `NimBLEAdvertising::setMaxPreferred` have been removed and replaced by `NimBLEAdvertising::setPreferredParams` which takes both the min and max parameters.
- Advertising the name and TX power of the device will no longer happen by default and should be set manually by the application using `NimBLEAdvertising::setName` and `NimBLEAdvertising::addTxPower`.
- `NimBLEAdvertising::setAdvertisementType` has been renamed to `NimBLEAdvertising::setConnectableMode` to better reflect it's function.
- `NimBLEAdvertising::setScanResponse` has been renamed to `NimBLEAdvertising::enableScanResponse` to better reflect it's function.
- `NimBLEAdvertising`; Scan response is no longer enabled by default.
- `NimBLEAdvertising::start` No longer takes a callback pointer parameter, instead the new method `NimBLEAdvertising::setAdvertisingCompleteCallback` should be used to set the callback function.
<br/>
## Beacons
- Removed Eddystone URL as it has been shutdown by google since 2021.
- `NimBLEEddystoneTLM::setTemp` now takes an `int16_t` parameter instead of float to be friendly to devices without floating point support.
- `NimBLEEddystoneTLM::getTemp` now returns `int16_t` to work with devices that don't have floating point support.
- `NimBLEEddystoneTLM::setData` now takes a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
- `NimBLEEddystoneTLM::getData` now returns a reference to * `NimBLEEddystoneTLM::BeaconData` instead of `std::string`.
- `NimBLEBeacon::setData` now takes `const NimBLEBeacon::BeaconData&` instead of `std::string`.
- `NimBLEBeacon::getData` now returns `const NimBLEBeacon::BeaconData&` instead of `std::string`.
<br/>
## Utilities
- `NimBLEUtils::dumpGapEvent` function removed.
- `NimBLEUtils::buildHexData` replaced with `NimBLEUtils::dataToHexString`, which returns a `std::string` containing the hex string.
<br/>

View File

@ -0,0 +1,28 @@
# Bluetooth 5.x features
## About extended advertising
Extended advertising allows for much more capability and flexibility.
* Allows for 251 bytes of advertisement data and up to 1650 bytes when chained (configuration dependant) vs 31.
* New PHY's (physical layers) that allow for faster data rate (2M PHY) or long range/slower data rates (CODED PHY) as well as the original 1M PHY.
* New periodic advertising, allowing the scanning device to sync with the advertisements of a beacon. This allows for the scanning device to sleep or perform other tasks before the next expected advertisement is sent, preserving cpu cycles and power (To be implemented).
<br/>
## Enabling extended advertising
Extended advertising is supported when enabled with the config option `CONFIG_BT_NIMBLE_EXT_ADV` set to a value of 1. This is done in menuconfig under `Component config > Bluetooth > NimBLE options > Enable extended advertising`, or set in `nimconfig.h` for Arduino, or in `build_flags` in PlatformIO.
When enabled the following will occur:
* `NimBLEScan::start` method will scan on both the 1M PHY and the coded PHY standards automatically.
* `NimBLEClient::connect` will use the primary PHY the device is listening on, unless specified (see below).
* `NimBLEClient::setConnectPhy` becomes available to specify the PHY's to connect with (default is all).
* `NimBLEAdvertising` is no longer available for use and is replaced by `NimBLEExtAdvertising`. `NimBLEDevice::getAdvertising` will now return an instance of `NimBLEExtAdvertising`.
* `NimBLEAdvertisementData` is no longer available for use and is replaced by `NimBLEExtAdvertisement`. This new class is where everything about the advertisement is configured, including the advertisement intervals and advertisement ended callback.

View File

@ -1,117 +0,0 @@
# Arduino command line and platformio config options
`CONFIG_BT_NIMBLE_MAX_CONNECTIONS`
Sets the number of simultaneous connections (esp controller max is 9)
- Default value is 3
<br/>
`CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU`
Sets the default MTU size.
- Default value is 255
<br/>
`CONFIG_BT_NIMBLE_SVC_GAP_DEVICE_NAME`
Set the default device name
- Default value is "nimble"
<br/>
`CONFIG_BT_NIMBLE_DEBUG`
If defined, enables debug log messages from the NimBLE host
- Uses approx. 32kB of flash memory.
<br/>
`CONFIG_NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT`
If defined, NimBLE host return codes will be printed as text in debug log messages.
- Uses approx. 7kB of flash memory.
<br/>
`CONFIG_NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT`
If defined, GAP event codes will be printed as text in debug log messages.
- Uses approx. 1kB of flash memory.
<br/>
`CONFIG_NIMBLE_CPP_ENABLE_ADVERTISMENT_TYPE_TEXT`
If defined, advertisment types will be printed as text while scanning in debug log messages.
- Uses approx. 250 bytes of flash memory.
<br/>
`CONFIG_BT_NIMBLE_SVC_GAP_APPEARANCE`
Set the default appearance.
- Default value is 0x00
<br/>
`CONFIG_BT_NIMBLE_ROLE_CENTRAL_DISABLED`
If defined, NimBLE Client functions will not be included.
- Reduces flash size by approx. 7kB.
<br/>
`CONFIG_BT_NIMBLE_ROLE_OBSERVER_DISABLED`
If defined, NimBLE Scan functions will not be included.
- Reduces flash size by approx. 26kB.
<br/>
`CONFIG_BT_NIMBLE_ROLE_PERIPHERAL_DISABLED`
If defined NimBLE Server functions will not be included.
- Reduces flash size by approx. 16kB.
<br/>
`CONFIG_BT_NIMBLE_ROLE_BROADCASTER_DISABLED`
If defined, NimBLE Advertising functions will not be included.
- Reduces flash size by approx. 5kB.
<br/>
`CONFIG_BT_NIMBLE_MAX_BONDS`
Sets the number of devices allowed to store/bond with
- Default value is 3
<br/>
`CONFIG_BT_NIMBLE_MAX_CCCDS`
Sets the maximum number of CCCD subscriptions to store
- Default value is 8
<br/>
`CONFIG_BT_NIMBLE_RPA_TIMEOUT`
Sets the random address refresh time in seconds.
- Default value is 900
<br/>
`CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT`
Set the number of msys blocks For prepare write & prepare responses. This may need to be increased if
you are sending large blocks of data with a low MTU. E.g: 512 bytes with 23 MTU will fail.
- Default value is 12
<br/>
`CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL`
Sets the NimBLE stack to use external PSRAM will be loaded
- Must be defined with a value of 1; Default is CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL 1
<br/>
`CONFIG_BT_NIMBLE_PINNED_TO_CORE`
Sets the core the NimBLE host stack will run on
- Options: 0 or 1
<br/>
`CONFIG_BT_NIMBLE_TASK_STACK_SIZE`
Set the task stack size for the NimBLE core.
- Default is 4096
<br/>

File diff suppressed because it is too large Load Diff

View File

@ -1,148 +0,0 @@
# Improvements and updates
Many improvements have been made to this library vs the original, this is a brief overview of the most significant changes.
Refer to the [class documentation](https://h2zero.github.io/esp-nimble-cpp/annotated.html) for futher information on class specifics.
* [Server](#server)
* [Advertising](#advertising)
* [Client](#client)
* [General](#general)
<br/>
<a name="server"></a>
# Server
`NimBLECharacteristic::setValue(const T &s)`
`NimBLEDescriptor::setValue(const T &s)`
Now use a template to accomodate standard and custom types/values.
**Example**
```
struct my_struct{
uint8_t one;
uint16_t two;
uint32_t four;
uint64_t eight;
float flt;
}myStruct;
myStruct.one = 1;
myStruct.two = 2;
myStruct.four = 4;
myStruct.eight = 8;
myStruct.flt = 1234.56;
pCharacteristic->setValue(myStruct);
```
This will send the struct to the recieving client when read or a notification sent.
`NimBLECharacteristic::getValue` now takes an optional timestamp parameter which will update it's value with
the time the last value was recieved. In addition an overloaded template has been added to retrieve the value
as a type specified by the user.
**Example**
```
time_t timestamp;
myStruct = pCharacteristic->getValue<myStruct>(&timestamp); // timestamp optional
```
<br/>
**Advertising will automatically start when a client disconnects.**
A new method `NimBLEServer::advertiseOnDisconnect(bool)` has been implemented to control this, true(default) = enabled.
<br/>
`NimBLEServer::removeService` takes an additional parameter `bool deleteSvc` that if true will delete the service
and all characteristics / descriptors belonging to it and invalidating any pointers to them.
If false the service is only removed from visibility by clients. The pointers to the service and
it's characteristics / descriptors will remain valid and the service can be re-added in the future
using `NimBLEServer::addService`.
<br/>
<a name="advertising"></a>
# Advertising
`NimBLEAdvertising::start`
Now takes 2 optional parameters, the first is the duration to advertise for (in seconds), the second is a callback
that is invoked when advertsing ends and takes a pointer to a `NimBLEAdvertising` object (similar to the `NimBLEScan::start` API).
This provides an opportunity to update the advertisment data if desired.
Also now returns a bool value to indicate if advertising successfully started or not.
<br/>
<a name="client"></a>
# Client
`NimBLERemoteCharacteristic::readValue(time_t\*, bool)`
`NimBLERemoteDescriptor::readValue(bool)`
Have been added as templates to allow reading the values as any specified type.
**Example**
```
struct my_struct{
uint8_t one;
uint16_t two;
uint32_t four;
uint64_t eight;
float flt;
}myStruct;
time_t timestamp;
myStruct = pRemoteCharacteristic->readValue<myStruct>(&timestamp); // timestamp optional
```
<br/>
`NimBLERemoteCharacteristic::registerForNotify`
Has been **deprecated** as now the internally stored characteristic value is updated when notification/indication is recieved.
`NimBLERemoteCharacteristic::subscribe` and `NimBLERemoteCharacteristic::unsubscribe` have been implemented to replace it.
A callback is no longer requred to get the most recent value unless timing is important. Instead, the application can call `NimBLERemoteCharacteristic::getValue` to
get the last updated value any time.
<br/>
The `notifiy_callback` function is now defined as a `std::function` to take advantage of using `std::bind` to specifiy a class member function for the callback.
Example:
```
using namespace std::placeholders;
notify_callback callback = std::bind(&<ClassName>::<memberFunctionCallbackName>, this, _1, _2, _3, _4);
<remoteCharacteristicInstance>->subscribe(true, callback);
```
`NimBLERemoteCharacteristic::readValue` and `NimBLERemoteCharacteristic::getValue` take an optional timestamp parameter which will update it's value with
the time the last value was recieved.
> NimBLEClient::getService
> NimBLERemoteService::getCharacteristic
> NimBLERemoteCharacteristic::getDescriptor
These methods will now check the respective vectors for the attribute object and, if not found, will retrieve (only)
the specified attribute from the peripheral.
These changes allow more control for the user to manage the resources used for the attributes.
<br/>
`NimBLEClient::connect()` can now be called without an address or advertised device parameter. This will connect to the
device with the address previously set when last connected or set with `NimBLEDevice::setPeerAddress()`.
<a name="general"></a>
# General
To reduce resource use all instances of `std::map` have been replaced with `std::vector`.
Use of `FreeRTOS::Semaphore` has been removed as it was consuming too much ram, the related files have been left in place to accomodate application use.
Operators `==`, `!=` and `std::string` have been added to `NimBLEAddress` and `NimBLEUUID` for easier comparison and logging.
New constructor for `NimBLEUUID(uint32_t, uint16_t, uint16_t, uint64_t)` added to lower memory use vs string construction. See: [#21](https://github.com/h2zero/NimBLE-Arduino/pull/21).
Security/pairing operations are now handled in the respective `NimBLEClientCallbacks` and `NimBLEServerCallbacks` classes, `NimBLESecurity`(deprecated) remains for backward compatibility.
Configuration options have been added to add or remove debugging information, when disabled (default) significatly reduces binary size.
In ESP-IDF the options are in menuconfig: `Main menu -> ESP-NimBLE-cpp configuration`.
For Arduino the options must be commented / uncommented in nimconfig.h.
<br/>

View File

@ -1,102 +1,117 @@
# Migrating from Bluedroid to NimBLE
This guide describes the required changes to existing projects migrating from the original bluedroid API to NimBLE.
This guide describes the required changes to existing projects migrating from the original bluedroid API to NimBLE.
**The changes listed here are only the required changes that must be made**, and a short overview of options for migrating existing applications.
**The changes listed here are only the required changes that must be made**, and a short overview of options for migrating existing applications.
For more information on the improvements and additions please refer to the [class documentation](https://h2zero.github.io/esp-nimble-cpp/annotated.html) and [Improvements and updates](Improvements_and_updates.md)
For more information on the improvements and additions please refer to the [class documentation](https://h2zero.github.io/esp-nimble-cpp/annotated.html)
* [General Changes](#general-information)
* [Server](#server-api)
* [Services](#services)
* [characteristics](#characteristics)
* [descriptors](#descriptors)
* [Characteristics](#characteristics)
* [Characteristic Callbacks](#characteristic-callbacks)
* [Descriptors](#descriptors)
* [Descriptor Callbacks](#descriptor-callbacks)
* [Security](#server-security)
* [Advertising](#advertising-api)
* [Client](#client-api)
* [Remote Services](#remote-services)
* [Remote characteristics](#remote-characteristics)
* [Client Callbacks](#client-callbacks)
* [Security](#client-security)
* [BLE scan](#ble-scan)
* [General Security](#security-api)
* [Configuration](#arduino-configuration)
<br/>
<br/>
<a name="general-information"></a>
## General Information
### Header Files
All classes are accessible by including `NimBLEDevice.h` in your application, no further headers need to be included.
All classes are accessible by including `NimBLEDevice.h` in your application, no further headers need to be included.
(Mainly for Arduino) You may choose to include `NimBLELog.h` in your appplication if you want to use the `NIMBLE_LOGx` macros for debugging.
These macros are used the same way as the `ESP_LOGx` macros.
(Mainly for Arduino) You may choose to include `NimBLELog.h` in your application if you want to use the `NIMBLE_LOGx` macros for debugging. These macros are used the same way as the `ESP_LOGx` macros.
<br/>
### Class Names
Class names remain the same as the original with the addition of a "Nim" prefix.
For example `BLEDevice` is now `NimBLEDevice` and `BLEServer` is now `NimBLEServer` etc.
Class names remain the same as the original with the addition of a "Nim" prefix.
For example `BLEDevice` is now `NimBLEDevice` and `BLEServer` is now `NimBLEServer` etc.
For convienience definitions have been added to allow applications to use either name for all classes
this means **no class names need to be changed in existing code** and makes migrating easier.
For convenience definitions have been added to allow applications to use either name for all classes this means **no class names need to be changed in existing code** and makes migrating easier.
<br/>
### BLE Addresses
`BLEAddress` (`NimBLEAddress`) When constructing an address the constructor now takes an *(optional)* `uint8_t type` paramameter
to specify the address type. Default is (0) Public static address.
`BLEAddress` (`NimBLEAddress`) When constructing an address the constructor now takes an *(optional)* `uint8_t type` parameter to specify the address type. Default is (0) Public static address.
For example `BLEAddress addr(11:22:33:44:55:66, 1)` will create the address object with an address type of: 1 (Random).
For example `BLEAddress addr(11:22:33:44:55:66, 1)` will create the address object with an address type of: 1 (Random).
As this paramameter is optional no changes to existing code are needed, it is mentioned here for information.
<br/>
`BLEAddress::getNative` (`NimBLEAddress::getNative`) returns a uint8_t pointer to the native address byte array.
In this library the address bytes are stored in reverse order from the original library. This is due to the way
the NimBLE stack expects addresses to be presented to it. All other functions such as `toString` are
not affected as the endian change is made within them.
As this parameter is optional no changes to existing code are needed, it is mentioned here for information.
`BLEAddress::getNative` is now named `NimBLEAddress::getBase` and returns a pointer to `const ble_addr_t` instead of a pointer to the address value.
<br/>
<a name="server-api"></a>
## Server API
Creating a `BLEServer` instance is the same as original, no changes required.
For example `BLEDevice::createServer()` will work just as it did before.
For example `BLEDevice::createServer()` will work just as it did before.
`BLEServerCallbacks` (`NimBLEServerCallbacks`) has new methods for handling security operations.
<br/>
`BLEServerCallbacks::onConnect` (`NimBLEServerCallbacks::onConnect`) only has a single callback declaration which takes an additional (required) parameter `NimBLEConnInfo & connInfo`, which has methods to get information about the connected peer.
```
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo)`
```
<br/>
`BLEServerCallbacks::onDisconnect` (`NimBLEServerCallbacks::onDisconnect`) only has a single callback declaration which takes 2 additional (required) parameters `NimBLEConnInfo & connInfo`, which provides information about the peer and `int reason`, which gives the reason code for disconnection.
```
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason)`
```
<br/>
`BLEServerCallbacks::onMtuChanged` is now (`NimBLEServerCallbacks::onMtuChange`) and takes the parameter `NimBLEConnInfo & connInfo` instead of `esp_ble_gatts_cb_param_t`, which has methods to get information about the connected peer.
```
onMTUChange(uint16_t MTU, NimBLEConnInfo& connInfo)
```
**Note:** All callback methods have default implementations which allows the application to implement only the methods applicable.
<br/>
<a name="services"></a>
### Services
Creating a `BLEService` (`NimBLEService`) instance is the same as original, no changes required.
Creating a `BLEService` (`NimBLEService`) instance is the same as original, no changes required.
For example `BLEServer::createService(SERVICE_UUID)` will work just as it did before.
<br/>
<a name="characteristics"></a>
### Characteristics
The constructor for `(Nim)BLECharacteristic` is now private, so if you currently subclass it to add logic you should switch to use `NimBLEService::createCharacteristic` instead. Any custom processing logic previously in a `BLECharacteristic` subclass should be moved to a `NimBLECharacteristicCallbacks` subclass instead, and passed into `NimBLECharacteristic::setCallbacks`.
`BLEService::createCharacteristic` (`NimBLEService::createCharacteristic`) is used the same way as originally except the properties parameter has changed.
`BLEService::createCharacteristic` (`NimBLEService::createCharacteristic`) is used the same way as originally except the properties parameter has changed.
When creating a characteristic the properties are now set with `NIMBLE_PROPERTY::XXXX` instead of `BLECharacteristic::XXXX`.
#### Originally
> BLECharacteristic::PROPERTY_READ |
> BLECharacteristic::PROPERTY_WRITE
BLECharacteristic::PROPERTY_WRITE
#### Is Now
> NIMBLE_PROPERTY::READ |
> NIMBLE_PROPERTY::WRITE
NIMBLE_PROPERTY::WRITE
<br/>
#### The full list of properties
> NIMBLE_PROPERTY::READ
> NIMBLE_PROPERTY::READ_ENC
> NIMBLE_PROPERTY::READ_AUTHEN
> NIMBLE_PROPERTY::READ_AUTHOR
> NIMBLE_PROPERTY::WRITE
> NIMBLE_PROPERTY::WRITE_NR
> NIMBLE_PROPERTY::WRITE_ENC
> NIMBLE_PROPERTY::WRITE_AUTHEN
> NIMBLE_PROPERTY::WRITE_AUTHOR
> NIMBLE_PROPERTY::BROADCAST
> NIMBLE_PROPERTY::NOTIFY
> NIMBLE_PROPERTY::INDICATE
NIMBLE_PROPERTY::READ_ENC
NIMBLE_PROPERTY::READ_AUTHEN
NIMBLE_PROPERTY::READ_AUTHOR
NIMBLE_PROPERTY::WRITE
NIMBLE_PROPERTY::WRITE_NR
NIMBLE_PROPERTY::WRITE_ENC
NIMBLE_PROPERTY::WRITE_AUTHEN
NIMBLE_PROPERTY::WRITE_AUTHOR
NIMBLE_PROPERTY::BROADCAST
NIMBLE_PROPERTY::NOTIFY
NIMBLE_PROPERTY::INDICATE
<br/>
**Example:**
@ -104,7 +119,7 @@ When creating a characteristic the properties are now set with `NIMBLE_PROPERTY:
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
BLECharacteristic::PROPERTY_WRITE
);
```
@ -113,23 +128,30 @@ Needs to be changed to:
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE
NIMBLE_PROPERTY::WRITE
);
```
<br/>
`BLECharacteristicCallbacks` (`NimBLECharacteristicCallbacks`) has a new method `NimBLECharacteristicCallbacks::onSubscribe`
which is called when a client subscribes to notifications/indications.
#### Characteristic callbacks
`BLECharacteristicCallbacks` (`NimBLECharacteristicCallbacks`) has a new method `NimBLECharacteristicCallbacks::onSubscribe` which is called when a client subscribes to notifications/indications.
`BLECharacteristicCallbacks::onRead` (`NimBLECharacteristicCallbacks::onRead`) only has a single callback declaration, which takes an additional (required) parameter of `NimBLEConnInfo& connInfo`, which provides connection information about the peer.
`BLECharacteristicCallbacks::onWrite` (`NimBLECharacteristicCallbacks::onWrite`) only has a single callback declaration, which takes an additional (required) parameter of `NimBLEConnInfo& connInfo`, which provides connection information about the peer.
`BLECharacteristicCallbacks::onStatus` (`NimBLECharacteristicCallbacks::onStatus`) has had the status parameter removed as it was unnecessary since the status code from the BLE stack was also provided. The status code for success is 0 for notifications and BLE_HS_EDONE for indications, any other value is an error.
**Note:** All callback methods have default implementations which allows the application to implement only the methods applicable.
<br/>
> BLECharacteristic::getData
> BLECharacteristic::getData
**Has been removed from the API.**
Originally this returned a `uint8_t*` to the internal data, which is volatile.
To prevent possibly throwing exceptions this has been removed and `NimBLECharacteristic::getValue` should be used
to get a copy of the data first which can then safely be accessed via pointer.
**Has been removed from the API.**
Originally this returned a `uint8_t*` to the internal data, which is volatile.
To prevent possibly throwing exceptions this has been removed and `NimBLECharacteristic::getValue` should be used
to get a copy of the data first which can then safely be accessed via pointer.
**Example:**
```
@ -142,162 +164,143 @@ my_struct_t myStruct = pChr->getValue<my_struct_t>();
```
<br/>
<a name="descriptors"></a>
### Descriptors
The previous method `BLECharacteristic::addDescriptor()` has been removed.
Descriptors are now created using the `NimBLECharacteristic::createDescriptor` method.
BLE2902 or NimBLE2902 class has been removed.
NimBLE automatically creates the 0x2902 descriptor if a characteristic has a notification or indication property assigned to it.
It was no longer useful to have a class for the 0x2902 descriptor as a new callback `NimBLECharacteristicCallbacks::onSubscribe` was added
to handle callback functionality and the client subscription status is handled internally.
BLE2902 or NimBLE2902 class has been removed.
NimBLE automatically creates the 0x2902 descriptor if a characteristic has a notification or indication property assigned to it.
**Note:** Attempting to create a 0x2902 descriptor will trigger an assert to notify the error,
allowing the creation of it would cause a fault in the NimBLE stack.
It was no longer useful to have a class for the 0x2902 descriptor as a new callback `NimBLECharacteristicCallbacks::onSubscribe` was added
to handle callback functionality and the client subscription status is handled internally.
All other descriptors are now created just as characteristics are by using the `NimBLECharacteristic::createDescriptor` method (except 0x2904, see below).
**Note:** Attempting to create a 0x2902 descriptor will trigger a warning message and flag it internally as removed and will not be functional.
All other descriptors are now created just as characteristics are by using the `NimBLECharacteristic::createDescriptor` method (except 0x2904, see below).
Which are defined as:
```
NimBLEDescriptor* createDescriptor(const char* uuid,
uint32_t properties =
uint32_t properties =
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE,
uint16_t max_len = 100);
NimBLEDescriptor* createDescriptor(NimBLEUUID uuid,
uint32_t properties =
uint32_t properties =
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE,
uint16_t max_len = 100);
```
##### Example
#### Example
```
pDescriptor = pCharacteristic->createDescriptor("ABCD",
NIMBLE_PROPERTY::READ |
pDescriptor = pCharacteristic->createDescriptor("ABCD",
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE |
NIMBLE_PROPERTY::WRITE_ENC,
25);
```
Would create a descriptor with the UUID 0xABCD, publicly readable but only writable if paired/bonded (encrypted) and has a max value length of 25 bytes.
Would create a descriptor with the UUID 0xABCD, publicly readable but only writable if paired/bonded (encrypted) and has a max value length of 25 bytes.
<br/>
For the 0x2904, there is a special class that is created when you call `createDescriptor("2904").
The pointer returned is of the base class `NimBLEDescriptor` but the call will create the derived class of `NimBLE2904` so you must cast the returned pointer to
`NimBLE2904` to access the specific class methods.
##### Example
```
p2904 = (NimBLE2904*)pCharacteristic->createDescriptor("2904");
```
For the 0x2904, there is a specialized class that is created through `NimBLECharacteristic::create2904` which returns a pointer to a `NimBLE2904` instance which has specific
functions for handling the data expect in the Characteristic Presentation Format Descriptor specification.
<br/>
#### Descriptor callbacks
> `BLEDescriptorCallbacks::onRead` (`NimBLEDescriptorCallbacks::onRead`)
`BLEDescriptorCallbacks::onWrite` (`NimBLEDescriptorCallbacks::onWrite`)
The above descriptor callbacks take an additional (required) parameter `NimBLEConnInfo& connInfo`, which contains the connection information of the peer.
<br/>
<a name="server-security"></a>
### Server Security
Security is set on the characteristic or descriptor properties by applying one of the following:
> NIMBLE_PROPERTY::READ_ENC
> NIMBLE_PROPERTY::READ_AUTHEN
> NIMBLE_PROPERTY::READ_AUTHOR
> NIMBLE_PROPERTY::WRITE_ENC
> NIMBLE_PROPERTY::WRITE_AUTHEN
> NIMBLE_PROPERTY::WRITE_AUTHOR
NIMBLE_PROPERTY::READ_AUTHEN
NIMBLE_PROPERTY::READ_AUTHOR
NIMBLE_PROPERTY::WRITE_ENC
NIMBLE_PROPERTY::WRITE_AUTHEN
NIMBLE_PROPERTY::WRITE_AUTHOR
<br/>
When a peer wants to read or write a characteristic or descriptor with any of these properties applied it will trigger the pairing process. By default the "just-works" pairing will be performed automatically.
When a peer wants to read or write a characteristic or descriptor with any of these properties applied
it will trigger the pairing process. By default the "just-works" pairing will be performed automatically.
This can be changed to use passkey authentication or numeric comparison. See [Security API](#security-api) for details.
<br/>
<a name="advertising-api"></a>
## Advertising API
Advertising works the same as the original API except:
> BLEAdvertising::setMinPreferred
> BLEAdvertising::setMaxPreferred
Advertising works the same as the original API except:
These methods were found to not provide useful functionality and consumed valuable advertising space (6 bytes of 31) if used unknowingly.
If you wish to advertise these parameters you can still do so manually via `BLEAdvertisementData::addData` (`NimBLEAdvertisementData::addData`).
<br/>
Calling `NimBLEAdvertising::setAdvertisementData` will entirely replace any data set with `NimBLEAdvertising::addServiceUUID`, or
`NimBLEAdvertising::setAppearance` or similar methods. You should set all the data you wish to advertise within the `NimBLEAdvertisementData` instead.
~~Calling `NimBLEAdvertising::setScanResponseData` without also calling `NimBLEAdvertising::setAdvertisementData` will have no effect.
When using custom scan response data you must also use custom advertisement data.~~
No longer true as of release 1.2.0 and above, custom scan response is now supported without custom advertisement data.
Calling `NimBLEAdvertising::setAdvertisementData` will entirely replace any data set with `NimBLEAdvertising::addServiceUUID`, or
`NimBLEAdvertising::setAppearance` or similar methods. You should set all the data you wish to advertise within the `NimBLEAdvertisementData` instead if calling `NimBLEAdvertising::setAdvertisementData`.
<br/>
> BLEAdvertising::start (NimBLEAdvertising::start)
Now takes 2 optional parameters, the first is the duration to advertise for (in seconds), the second is a callback
that is invoked when advertsing ends and takes a pointer to a `NimBLEAdvertising` object (similar to the `NimBLEScan::start` API).
This provides an opportunity to update the advertisment data if desired.
Now takes 2 optional parameters, the first is the duration to advertise for (in milliseconds), the second `NimBLEAddress` to direct advertising to a specific device.
<br/>
<a name="client-api"></a>
## Client API
Client instances are created just as before with `BLEDevice::createClient` (`NimBLEDevice::createClient`).
Client instances are created just as before with `BLEDevice::createClient` (`NimBLEDevice::createClient`).
Multiple client instances can be created, up to the maximum number of connections set in the config file (default: 3).
To delete a client instance you must use `NimBLEDevice::deleteClient`.
Multiple client instances can be created, up to the maximum number of connections set in the config file (default: 3). To delete a client instance you must use `NimBLEDevice::deleteClient`.
`BLEClient::connect`(`NimBLEClient::connect`) Has had it's parameters altered.
`BLEClient::connect`(`NimBLEClient::connect`) Has had it's parameters altered.
Defined as:
> NimBLEClient::connect(bool deleteServices = true);
> NimBLEClient::connect(NimBLEAdvertisedDevice\* device, bool deleteServices = true);
> NimBLEClient::connect(NimBLEAddress address, bool deleteServices = true);
> NimBLEClient::connect(bool deleteServices = true, , bool asyncConnect = false, bool exchangeMTU = true);
> NimBLEClient::connect(const NimBLEAddress& address, bool deleteAttributes = true, bool asyncConnect = false, bool exchangeMTU = true);
> NimBLEClient::connect(const NimBLEAdvertisedDevice* device, bool deleteServices = true, bool asyncConnect = false, bool exchangeMTU = true);
The type parameter has been removed and a new bool parameter has been added to indicate if the client should
delete the attribute database previously retrieved (if applicable) for the peripheral, default value is true.
If set to false the client will use the attribute database it retrieved from the peripheral when previously connected.
This allows for faster connections and power saving if the devices dropped connection and are reconnecting.
The type parameter has been removed and a new bool parameter has been added to indicate if the client should delete the attribute database previously retrieved (if applicable) for the peripheral, default value is true.
If set to false the client will use the attribute database it retrieved from the peripheral when previously connected. This allows for faster connections and power saving if the devices dropped connection and are reconnecting.
The parameter `bool asyncConnect` if true, will cause the client to send the connect command to the stack and return immediately without blocking. The return value will represent wether the command was sent successfully or not and the `NimBLEClientCallbacks::onConnect` or `NimBLEClientCallbacks::onConnectFail` will be called when the operation is complete.
The parameter `bool exchangeMTU` if true, will cause the client to perform the exchange MTU process upon connecting. If false the MTU exchange will need to be performed by the application by calling `NimBLEClient::exchangeMTU`. If the connection is only sending small payloads it may be advantageous to not exchange the MTU to gain performance in the connection process.
<br/>
> `BLEClient::getServices` (`NimBLEClient::getServices`)
> `BLEClient::getServices` (`NimBLEClient::getServices`)
This method now takes an optional (bool) parameter to indicate if the services should be retrieved from the server (true) or
the currently known database returned (false : default).
This method now takes an optional (bool) parameter to indicate if the services should be retrieved from the server (true) or the currently known database returned (false : default).
Also now returns a pointer to `std::vector` instead of `std::map`.
<br/>
**Removed:** the automatic discovery of all peripheral attributes as they consumed time and resources for data
the user may not be interested in.
**Added:** `NimBLEClient::discoverAttributes` for the user to discover all the peripheral attributes
to replace the the removed automatic functionality.
**Removed:** the automatic discovery of all peripheral attributes as they consumed time and resources for data the user may not be interested in.
**Added:** `NimBLEClient::discoverAttributes` for the user to discover all the peripheral attributes to replace the the removed automatic functionality.
<br/>
<a name="remote-services"></a>
### Remote Services
`BLERemoteService` (`NimBLERemoteService`) Methods remain mostly unchanged with the exceptions of:
`BLERemoteService` (`NimBLERemoteService`) Methods remain mostly unchanged with the exceptions of:
> BLERemoteService::getCharacteristicsByHandle
This method has been removed.
<br/>
> `BLERemoteService::getCharacteristics` (`NimBLERemoteService::getCharacteristics`)
> `BLERemoteService::getCharacteristics` (`NimBLERemoteService::getCharacteristics`)
This method now takes an optional (bool) parameter to indicate if the characteristics should be retrieved from the server (true) or
the currently known database returned (false : default).
This method now takes an optional (bool) parameter to indicate if the characteristics should be retrieved from the server (true) or the currently known database returned, default = false.
Also now returns a pointer to `std::vector` instead of `std::map`.
<br/>
<a name="remote-characteristics"></a>
### Remote Characteristics
`BLERemoteCharacteristic` (`NimBLERemoteCharacteristic`) There have been a few changes to the methods in this class:
`BLERemoteCharacteristic` (`NimBLERemoteCharacteristic`)
There have been a few changes to the methods in this class:
> `BLERemoteCharacteristic::writeValue` (`NimBLERemoteCharacteristic::writeValue`)
> `BLERemoteCharacteristic::registerForNotify` (`NimBLERemoteCharacteristic::registerForNotify`)
> `BLERemoteCharacteristic::writeValue` (`NimBLERemoteCharacteristic::writeValue`)
Now return true or false to indicate success or failure so you can choose to disconnect or try again.
Now returns true or false to indicate success or failure so you can choose to disconnect or try again.
<br/>
> `BLERemoteCharacteristic::registerForNotify` (`NimBLERemoteCharacteristic::registerForNotify`)
> `BLERemoteCharacteristic::registerForNotify`
Has been removed.
Is now **deprecated**.
> `NimBLERemoteCharacteristic::subscribe`
> `NimBLERemoteCharacteristic::unsubscribe`
@ -307,95 +310,108 @@ Are the new methods added to replace it.
> `BLERemoteCharacteristic::readUInt8` (`NimBLERemoteCharacteristic::readUInt8`)
> `BLERemoteCharacteristic::readUInt16` (`NimBLERemoteCharacteristic::readUInt16`)
> `BLERemoteCharacteristic::readUInt32` (`NimBLERemoteCharacteristic::readUInt32`)
> `BLERemoteCharacteristic::readFloat` (`NimBLERemoteCharacteristic::readFloat`)
> `BLERemoteCharacteristic::readFloat` (`NimBLERemoteCharacteristic::readFloat`)
Are **deprecated** a template: NimBLERemoteCharacteristic::readValue<type\>(time_t\*, bool) has been added to replace them.
Are **removed** a template: `NimBLERemoteCharacteristic::readValue<type\>(time_t\*, bool)` has been added to replace them.
<br/>
> `BLERemoteCharacteristic::readRawData`
> `BLERemoteCharacteristic::readRawData`
**Has been removed from the API**
Originally it stored an unnecessary copy of the data and was returning a `uint8_t` pointer to volatile internal data.
The user application should use `NimBLERemoteCharacteristic::readValue` or `NimBLERemoteCharacteristic::getValue`.
To obatain a copy of the data, then cast the returned std::string to the type required such as:
**Has been removed from the API**
Originally it stored an unnecessary copy of the data and was returning a `uint8_t` pointer to volatile internal data.
The user application should use `NimBLERemoteCharacteristic::readValue` or `NimBLERemoteCharacteristic::getValue`.
To obtain a copy of the data as a `NimBLEAttValue` instance and use the `NimBLEAttValue::data` member function to obtain the pointer.
```
std::string value = pChr->readValue();
uint8_t *data = (uint8_t*)value.data();
NimBLEAttValue value = pChr->readValue();
const uint8_t *data = value.data();
```
Alternatively use the `readValue` template:
```
my_struct_t myStruct = pChr->readValue<my_struct_t>();
```
<br/>
> `BLERemoteCharacteristic::getDescriptors` (`NimBLERemoteCharacteristic::getDescriptors`)
This method now takes an optional (bool) parameter to indicate if the descriptors should be retrieved from the server (true) or
the currently known database returned (false : default).
> `BLERemoteCharacteristic::getDescriptors` (`NimBLERemoteCharacteristic::getDescriptors`)
This method now takes an optional (bool) parameter to indicate if the descriptors should be retrieved from the server (true) or the currently known database returned, default = false.
Also now returns a pointer to `std::vector` instead of `std::map`.
<br/>
<a name="client-security"></a>
### Client callbacks
> `BLEClientCallbacks::onDisconnect` (`NimBLEClientCallbacks::onDisconnect`)
This now takes a second parameter `int reason` which provides the reason code for disconnection.
<br/>
### Client Security
The client will automatically initiate security when the peripheral responds that it's required.
The client will automatically initiate security when the peripheral responds that it's required.
The default configuration will use "just-works" pairing with no bonding, if you wish to enable bonding see below.
<br/>
<a name="security-api"></a>
## Security API
Security operations have been moved to `BLEDevice` (`NimBLEDevice`).
## BLE Scan
The scan API is mostly unchanged from the original except for `NimBLEScan::start`, which has the following changes:
* The duration parameter is now in milliseconds instead of seconds.
* The callback parameter has been removed.
* A new parameter `bool restart` has been added, when set to true to restart the scan if already in progress and clear the duplicate cache.
Also security callback methods are now incorporated in the `NimBLEServerCallbacks` / `NimBLEClientCallbacks` classes.
However backward compatibility with the original `BLESecurity` (`NimBLESecurity`) class is retained to minimize application code changes.
The blocking overload of `NimBLEScan::start` has been replaced by an overload of `NimBLEScan::getResults` with the same parameters.
<br/>
## Security API
Security operations have been moved to `BLEDevice` (`NimBLEDevice`).
The security callback methods are now incorporated in the `NimBLEServerCallbacks` / `NimBLEClientCallbacks` classes.
The callback methods are:
> `bool onConfirmPIN(uint32_t pin)`
> `bool onConfirmPasskey(NimBLEConnInfo& connInfo, uint32_t pin)`
Receives the pin when using numeric comparison authentication, `return true;` to accept.
Receives the pin when using numeric comparison authentication.
Call `NimBLEDevice::injectConfirmPasskey(connInfo, true);` to accept or `NimBLEDevice::injectConfirmPasskey(connInfo, false);` to reject.
<br/>
> `uint32_t onPassKeyRequest()`
> `void onPassKeyEntry(NimBLEConnInfo& connInfo)`
For server callback; return the passkey expected from the client.
For client callback; return the passkey to send to the server.
Client callback; client should respond with the passkey (pin) by calling `NimBLEDevice::injectPassKey(connInfo, 123456);`
<br/>
> `void onAuthenticationComplete(ble_gap_conn_desc\* desc)`
> `uint32_t onPassKeyDisplay()`
Authentication complete, success or failed information is in `desc`.
Server callback; should return the passkey (pin) expected from the client.
<br/>
> `void onAuthenticationComplete(NimBLEConnInfo& connInfo)`
Authentication complete, success or failed information is available from the `NimBLEConnInfo` methods.
<br/>
Security settings and IO capabilities are now set by the following methods of NimBLEDevice.
> `NimBLEDevice::setSecurityAuth(bool bonding, bool mitm, bool sc)`
> `NimBLEDevice::setSecurityAuth(uint8_t auth_req)`
> `NimBLEDevice::setSecurityAuth(bool bonding, bool mitm, bool sc)`
> `NimBLEDevice::setSecurityAuth(uint8_t auth_req)`
Sets the authorization mode for this device.
<br/>
> `NimBLEDevice::setSecurityIOCap(uint8_t iocap)`
> `NimBLEDevice::setSecurityIOCap(uint8_t iocap)`
Sets the Input/Output capabilities of this device.
<br/>
> `NimBLEDevice::setSecurityInitKey(uint8_t init_key)`
> `NimBLEDevice::setSecurityInitKey(uint8_t init_key)`
If we are the initiator of the security procedure this sets the keys we will distribute.
<br/>
> `NimBLEDevice::setSecurityRespKey(uint8_t resp_key)`
> `NimBLEDevice::setSecurityRespKey(uint8_t resp_key)`
Sets the keys we are willing to accept from the peer during pairing.
<br/>
<a name="arduino-configuration"></a>
## Arduino Configuration
Unlike the original library pre-packaged in the esp32-arduino, this library has all the configuration
options that are normally set in menuconfig available in the *src/nimconfig.h* file.
Unlike the original library pre-packaged in the esp32-arduino, this library has all the configuration options that are normally set in menuconfig available in the *src/nimconfig.h* file.
This allows Arduino users to fully customize the build, such as increasing max connections
or loading the BLE stack into external PSRAM.
This allows Arduino users to fully customize the build, such as increasing max connections or loading the BLE stack into external PSRAM.
For details on the options, they are fully commented in *nimconfig.h*
<br/>

View File

@ -21,9 +21,8 @@ If you're not creating a server or do not want to advertise a name, simply pass
This can be called any time you wish to use BLE functions and does not need to be called from app_main(IDF) or setup(Arduino) but usually is.
<br/>
<a name="creating-a-server"></a>
## Creating a Server
BLE servers perform 2 tasks, they advertise their existance for clients to find them and they provide services which contain information for the connecting client.
BLE servers perform 2 tasks, they advertise their existence for clients to find them and they provide services which contain information for the connecting client.
After initializing the NimBLE stack we create a server by calling `NimBLEDevice::createServer()`, this will create a server instance and return a pointer to it.
@ -38,9 +37,7 @@ For this example we will keep it simple and use a 16 bit value: ABCD.
```
#include "NimBLEDevice.h"
// void setup() in Arduino
void app_main(void)
{
extern "C" void app_main(void) {
NimBLEDevice::init("NimBLE");
NimBLEServer *pServer = NimBLEDevice::createServer();
@ -80,9 +77,7 @@ The function call will simply be `pService->createCharacteristic("1234");`
```
#include "NimBLEDevice.h"
// void setup() in Arduino
void app_main(void)
{
extern "C" void app_main(void) {
NimBLEDevice::init("NimBLE");
NimBLEServer *pServer = NimBLEDevice::createServer();
@ -91,7 +86,7 @@ void app_main(void)
}
```
All that's left to do now is start the sevice, give the characteristic a value and start advertising for clients.
All that's left to do now is start the service, give the characteristic a value and start advertising for clients.
Fist we start the service by calling `NimBLEService::start()`.
@ -100,12 +95,13 @@ There are many different types you can send as parameters for the value but for
`pCharacteristic->setValue("Hello BLE");`
Next we need to advertise for connections.
To do this we create an instance of `NimBLEAdvertising` add our service to it (optional) and start advertisng.
To do this we create an instance of `NimBLEAdvertising` add our service to it (optional) and start advertising.
**The code for this will be:**
```
NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising(); // create advertising instance
pAdvertising->addServiceUUID("ABCD"); // tell advertising the UUID of our service
pAdvertising->addServiceUUID("ABCD"); // advertise the UUID of our service
pAdvertising->setName("NimBLE"); // advertise the device name
pAdvertising->start(); // start advertising
```
That's it, this will be enough to create a BLE server with a service and a characteristic and advertise for client connections.
@ -114,9 +110,7 @@ That's it, this will be enough to create a BLE server with a service and a chara
```
#include "NimBLEDevice.h"
// void setup() in Arduino
void app_main(void)
{
extern "C" void app_main(void) {
NimBLEDevice::init("NimBLE");
NimBLEServer *pServer = NimBLEDevice::createServer();
@ -127,7 +121,8 @@ void app_main(void)
pCharacteristic->setValue("Hello BLE");
NimBLEAdvertising *pAdvertising = NimBLEDevice::getAdvertising();
pAdvertising->addServiceUUID("ABCD");
pAdvertising->addServiceUUID("ABCD"); // advertise the UUID of our service
pAdvertising->setName("NimBLE"); // advertise the device name
pAdvertising->start();
}
```
@ -137,7 +132,6 @@ Now if you scan with your phone using nRFConnect or any other BLE app you should
For more advanced features and options please see the server examples in the examples folder.
<br/>
<a name="creating-a-client"></a>
## Creating a Client
BLE clients perform 2 tasks, they scan for advertising servers and form connections to them to read and write to their characteristics/descriptors.
@ -146,7 +140,7 @@ After initializing the NimBLE stack we create a scan instance by calling `NimBLE
Once we have created the scan we can start looking for advertising servers.
To do this we call `NimBLEScan::start(duration)`, the duration parameter is a uint32_t that specifies the number of seconds to scan for,
To do this we call `NimBLEScan::getResults(duration)`, the duration parameter is a uint32_t that specifies the number of milliseconds to scan for,
passing 0 will scan forever.
In this example we will scan for 10 seconds. This is a blocking function (a non blocking overload is also available).
@ -156,13 +150,11 @@ This call returns an instance of `NimBLEScanResults` when the scan completes whi
```
#include "NimBLEDevice.h"
// void setup() in Arduino
void app_main(void)
{
extern "C" void app_main(void) {
NimBLEDevice::init("");
NimBLEScan *pScan = NimBLEDevice::getScan();
NimBLEScanResults results = pScan->start(10);
NimBLEScanResults results = pScan->getResults(10 * 1000);
}
```
<br/>
@ -170,7 +162,7 @@ void app_main(void)
Now that we have scanned we need to check the results for any advertisers we are interested in connecting to.
To do this we iterate through the results and check if any of the devices found are advertising the service we want `ABCD`.
Each result in `NimBLEScanResults` is a `NimBLEAdvertisedDevice` instance that we can access data from.
Each result in `NimBLEScanResults` is a `const NimBLEAdvertisedDevice*` that we can access data from.
We will check each device found for the `ABCD` service by calling `NimBLEAdvertisedDevice::isAdvertisingService`.
This takes an instance of `NimBLEUUID` as a parameter so we will need to create one.
@ -179,11 +171,11 @@ This takes an instance of `NimBLEUUID` as a parameter so we will need to create
```
NimBLEUUID serviceUuid("ABCD");
for(int i = 0; i < results.getCount(); i++) {
NimBLEAdvertisedDevice device = results.getDevice(i);
for (int i = 0; i < results.getCount(); i++) {
const NimBLEAdvertisedDevice *device = results.getDevice(i);
if (device.isAdvertisingService(serviceUuid)) {
// create a client and connect
if (device->isAdvertisingService(serviceUuid)) {
// create a client and connect
}
}
```
@ -200,21 +192,21 @@ This takes a pointer to the `NimBLEAdvertisedDevice` and returns `true` if succe
```
NimBLEUUID serviceUuid("ABCD");
for(int i = 0; i < results.getCount(); i++) {
NimBLEAdvertisedDevice device = results.getDevice(i);
for (int i = 0; i < results.getCount(); i++) {
const NimBLEAdvertisedDevice *device = results.getDevice(i);
if (device.isAdvertisingService(serviceUuid)) {
if (device->isAdvertisingService(serviceUuid)) {
NimBLEClient *pClient = NimBLEDevice::createClient();
if(pClient->connect(&device)) {
//success
if (pClient->connect(&device)) {
//success
} else {
// failed to connect
// failed to connect
}
}
}
```
As shown, the call to `NimBLEClient::connect` should have it's eturn value tested to make sure it succeeded before proceeding to get data.
As shown, the call to `NimBLEClient::connect` should have it's return value tested to make sure it succeeded before proceeding to get data.
<br/>
Next we need to access the servers data by asking it for the service and the characteristic we are interested in, then read the characteristic value.
@ -222,7 +214,7 @@ Next we need to access the servers data by asking it for the service and the cha
To do this we call `NimBLEClient::getService`, which takes as a parameter the UUID of the service and returns
a pointer an instance to `NimBLERemoteService` or `nullptr` if the service was not found.
Next we will call `NimBLERemoteService::getCharateristic` which takes as a parameter the UUID of the service and returns
Next we will call `NimBLERemoteService::getCharacteristic` which takes as a parameter the UUID of the service and returns
a pointer to an instance of `NimBLERemoteCharacteristic` or `nullptr` if not found.
Finally we will read the characteristic value with `NimBLERemoteCharacteristic::readValue()`.
@ -231,11 +223,15 @@ Finally we will read the characteristic value with `NimBLERemoteCharacteristic::
```
NimBLEUUID serviceUuid("ABCD");
for(int i = 0; i < results.getCount(); i++) {
NimBLEAdvertisedDevice device = results.getDevice(i);
for (int i = 0; i < results.getCount(); i++) {
const NimBLEAdvertisedDevice *device = results.getDevice(i);
if (device.isAdvertisingService(serviceUuid)) {
if (device->isAdvertisingService(serviceUuid)) {
NimBLEClient *pClient = NimBLEDevice::createClient();
if (!pClient) { // Make sure the client was created
break;
}
if (pClient->connect(&device)) {
NimBLERemoteService *pService = pClient->getService(serviceUuid);
@ -249,7 +245,7 @@ for(int i = 0; i < results.getCount(); i++) {
}
}
} else {
// failed to connect
// failed to connect
}
}
}
@ -264,12 +260,16 @@ This is done by calling `NimBLEDevice::deleteClient`.
```
NimBLEUUID serviceUuid("ABCD");
for(int i = 0; i < results.getCount(); i++) {
NimBLEAdvertisedDevice device = results.getDevice(i);
for (int i = 0; i < results.getCount(); i++) {
const NimBLEAdvertisedDevice *device = results.getDevice(i);
if (device.isAdvertisingService(serviceUuid)) {
if (device->isAdvertisingService(serviceUuid)) {
NimBLEClient *pClient = NimBLEDevice::createClient();
if (!pClient) { // Make sure the client was created
break;
}
if (pClient->connect(&device)) {
NimBLERemoteService *pService = pClient->getService(serviceUuid);
@ -282,7 +282,7 @@ for(int i = 0; i < results.getCount(); i++) {
}
}
} else {
// failed to connect
// failed to connect
}
NimBLEDevice::deleteClient(pClient);
@ -296,37 +296,39 @@ Note that there is no need to disconnect as that will be done when deleting the
```
#include "NimBLEDevice.h"
// void setup() in Arduino
void app_main(void)
{
extern "C" void app_main(void) {
NimBLEDevice::init("");
NimBLEScan *pScan = NimBLEDevice::getScan();
NimBLEScanResults results = pScan->start(10);
NimBLEScanResults results = pScan->getResults(10 * 1000);
NimBLEUUID serviceUuid("ABCD");
for(int i = 0; i < results.getCount(); i++) {
NimBLEAdvertisedDevice device = results.getDevice(i);
if (device.isAdvertisingService(serviceUuid)) {
for (int i = 0; i < results.getCount(); i++) {
const NimBLEAdvertisedDevice *device = results.getDevice(i);
if (device->isAdvertisingService(serviceUuid)) {
NimBLEClient *pClient = NimBLEDevice::createClient();
if (!pClient) { // Make sure the client was created
break;
}
if (pClient->connect(&device)) {
NimBLERemoteService *pService = pClient->getService(serviceUuid);
if (pService != nullptr) {
NimBLERemoteCharacteristic *pCharacteristic = pService->getCharacteristic("1234");
if (pCharacteristic != nullptr) {
std::string value = pCharacteristic->readValue();
// print or do whatever you need with the value
}
}
} else {
// failed to connect
// failed to connect
}
NimBLEDevice::deleteClient(pClient);
}
}
@ -336,4 +338,3 @@ void app_main(void)
For more advanced features and options please see the client examples in the examples folder.
<br/>

View File

@ -2,7 +2,7 @@
## Put BLE functions in a task running on the NimBLE stack core
When commands are sent to the stack from a differnt core they can experience delays in execution.
When commands are sent to the stack from a different core they can experience delays in execution.
This library detects this and invokes the esp32 IPC to reroute these commands through the correct core but this also increases overhead.
Therefore it is highly recommended to create tasks for BLE to run on the same core, the macro `CONFIG_BT_NIMBLE_PINNED_TO_CORE` can be used to set the core.
<br/>
@ -13,12 +13,12 @@ When a client instance has been created and has connected to a peer device and i
If you are periodically connecting to the same devices and you have deleted the client instance or the services when connecting again it will cause a retrieval of that information from the peer again.
This results in significant energy drain on the battery of the devices, fragments heap, and reduces connection performance.
Client instances in this library use approximately 20% of the original bluedroid library, deleteing them will provide much less gain than it did before.
Client instances in this library use approximately 20% of the original bluedroid library, deleting them will provide much less gain than it did before.
It is recommended to retain the client instance in cases where the time between connecting to the same device is less than 5 minutes.
<br/>
## Only retrieve the services and characteriscs needed
## Only retrieve the services and characteristics needed
As a client the use of `NimBLEClient::getServices` or `NimBLERemoteService::getCharacteristics` and using `true` for the parameter should be limited to devices that are not known.
Instead `NimBLEClient::getService(NimBLEUUID)` or `NimBLERemoteService::getCharacteristic(NimBLEUUID)` should be used to access certain attributes that are useful to the application.

View File

@ -1,5 +1,4 @@
# Overview
This is a C++ BLE library for the ESP32 that uses the NimBLE host stack instead of bluedroid.
The aim is to maintain, as much as reasonable, the original bluedroid C++ & Arduino BLE API by while adding new features
and making improvements in performance, resource use, and stability.
@ -13,20 +12,8 @@ NimBLE is a completely open source Bluetooth Low Energy stack produced by [Apach
It is more suited to resource constrained devices than bluedroid and has now been ported to the ESP32 by Espressif.
<br/>
# Arduino Installation
**Arduino Library manager:** Go to `sketch` -> `Include Library` -> `Manage Libraries` and search for NimBLE and install.
**Alternatively:** Download as .zip and extract to Arduino/libraries folder, or in Arduino IDE from Sketch menu -> Include library -> Add .Zip library.
`#include "NimBLEDevice.h"` at the beginning of your sketch.
Call `NimBLEDevice::init` in `setup`.
Tested and working with esp32-arduino in Arduino IDE and platform IO.
<br/>
# ESP-IDF Installation
### v4.0+
## v4.0+
Download as .zip and extract or clone into the components folder in your esp-idf project.
Run menuconfig, go to `Component config->Bluetooth` enable Bluetooth and in `Bluetooth host` NimBLE.
@ -35,49 +22,23 @@ Configure settings in `NimBLE Options`.
Call `NimBLEDevice::init` in `app_main`.
<br/>
### v3.2 & v3.3
The NimBLE component does not come with these versions of IDF (now included in 3.3.2 and above).
A backport that works in these versions has been created and is [available here](https://github.com/h2zero/esp-nimble-component).
Download or clone that repo into your project/components folder and run menuconfig.
Configure settings in `main menu -> NimBLE Options`.
`#include "NimBLEDevice.h"` in main.cpp.
Call `NimBLEDevice::init` in `app_main`.
<br/>
# Using
This library is intended to be compatible with the original ESP32 BLE functions and types with minor changes.
If you have not used the original Bluedroid library please refer to the [New user guide](New_user_guide.md).
If you are familiar with the original library, see: [The migration guide](Migration_guide.md) for details.
Also see [Improvements and updates](Improvements_and_updates.md) for information about non-breaking changes.
If you are familiar with the original library, see: [The migration guide](Migration_guide.md) for details.
For more advanced usage see [Usage tips](Usage_tips.md) for more performance and optimization.
<br/>
### Arduino specific
See the Refactored_original_examples in the examples folder for highlights of the differences with the original library.
# Sponsors
Thank you to all the sponsors who support this project!
More advanced examples highlighting many available features are in examples/NimBLE_Server, NimBLE_Client.
Beacon examples provided by [beegee-tokyo](https://github.com/beegee-tokyo) are in examples/BLE_Beacon_Scanner, BLE_EddystoneTLM_Beacon, BLE_EddystoneURL_Beacon.
Change the settings in the nimconfig.h file to customize NimBLE to your project, such as increasing max connections (default is 3).
<br/>
### Arduino command line and platformio
As an alternative to changing the configuration in nimconfig.h, Arduino command line and platformio.ini options are available.
See the command line configuration options available in [Command line config](Command_line_config.md).
<br/>
# Need help? Have a question or suggestion?
Come chat on [gitter](https://gitter.im/NimBLE-Arduino/community?utm_source=share-link&utm_medium=link&utm_campaign=share-link) or open an issue at [NimBLE-Arduino](https://github.com/h2zero/NimBLE-Arduino/issues) or [esp-nimble-cpp](https://github.com/h2zero/esp-nimble-cpp/issues)
If you use this library for a commercial product please consider [sponsoring the development](https://github.com/sponsors/h2zero) to ensure the continued updates and maintenance.
<br/>
# Acknowledgments
* [nkolban](https://github.com/nkolban) and [chegewara](https://github.com/chegewara) for the [original esp32 BLE library](https://github.com/nkolban/esp32-snippets/tree/master/cpp_utils) this project was derived from.
* [beegee-tokyo](https://github.com/beegee-tokyo) for contributing your time to test/debug and contributing the beacon examples.
* [Jeroen88](https://github.com/Jeroen88) for the amazing help debugging and improving the client code.

View File

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_Client
include $(IDF_PATH)/make/project.mk

View File

@ -1,372 +0,0 @@
/** NimBLE_Server Demo:
*
* Demonstrates many of the available features of the NimBLE client library.
*
* Created: on March 24 2020
* Author: H2zero
*
*/
#include <NimBLEDevice.h>
extern "C" {void app_main(void);}
void scanEndedCB(NimBLEScanResults results);
static NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTime = 0; /** 0 = scan forever */
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) {
printf("Connected\n");
/** After connection we should change the parameters if we don't need fast response times.
* These settings are 150ms interval, 0 latency, 450ms timout.
* Timeout should be a multiple of the interval, minimum is 100ms.
* I find a multiple of 3-5 * the interval works best for quick response/reconnect.
* Min interval: 120 * 1.25ms = 150, Max interval: 120 * 1.25ms = 150, 0 latency, 45 * 10ms = 450ms timeout
*/
pClient->updateConnParams(120,120,0,45);
};
void onDisconnect(NimBLEClient* pClient) {
printf("%s Disconnected - Starting scan\n", pClient->getPeerAddress().toString().c_str());
NimBLEDevice::getScan()->start(scanTime, scanEndedCB);
};
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
printf("Client Passkey Request\n");
/** return the passkey to send to the server */
return 123456;
};
bool onConfirmPIN(uint32_t pass_key){
printf("The passkey YES/NO number: %d\n", pass_key);
/** Return false if passkeys don't match. */
return true;
};
/** Pairing process complete, we can check the results in ble_gap_conn_desc */
void onAuthenticationComplete(ble_gap_conn_desc* desc){
if(!desc->sec_state.encrypted) {
printf("Encrypt connection failed - disconnecting\n");
/** Find the client with the connection handle provided in desc */
NimBLEDevice::getClientByID(desc->conn_handle)->disconnect();
return;
}
};
};
/** Define a class to handle the callbacks when advertisments are received */
class AdvertisedDeviceCallbacks: public NimBLEAdvertisedDeviceCallbacks {
void onResult(NimBLEAdvertisedDevice* advertisedDevice) {
printf("Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if(advertisedDevice->isAdvertisingService(NimBLEUUID("DEAD")))
{
printf("Found Our Service\n");
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/** Ready to connect now */
doConnect = true;
}
};
};
/** Notification / Indication receiving handler callback */
void notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){
std::string str = (isNotify == true) ? "Notification" : "Indication";
str += " from ";
str += pRemoteCharacteristic->getRemoteService()->getClient()->getPeerAddress().toString();
str += ": Service = " + pRemoteCharacteristic->getRemoteService()->getUUID().toString();
str += ", Characteristic = " + pRemoteCharacteristic->getUUID().toString();
str += ", Value = " + std::string((char*)pData, length);
printf("%s\n", str.c_str());
}
/** Callback to process the results of the last scan or restart it */
void scanEndedCB(NimBLEScanResults results){
printf("Scan Ended\n");
}
/** Create a single global instance of the callback class to be used by all clients */
static ClientCallbacks clientCB;
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer() {
NimBLEClient* pClient = nullptr;
/** Check if we have a client we should reuse first **/
if(NimBLEDevice::getClientListSize()) {
/** Special case when we already know this device, we send false as the
* second argument in connect() to prevent refreshing the service database.
* This saves considerable time and power.
*/
pClient = NimBLEDevice::getClientByPeerAddress(advDevice->getAddress());
if(pClient){
if(!pClient->connect(advDevice, false)) {
printf("Reconnect failed\n");
return false;
}
printf("Reconnected client\n");
}
/** We don't already have a client that knows this device,
* we will check for a client that is disconnected that we can use.
*/
else {
pClient = NimBLEDevice::getDisconnectedClient();
}
}
/** No client to reuse? Create a new one. */
if(!pClient) {
if(NimBLEDevice::getClientListSize() >= NIMBLE_MAX_CONNECTIONS) {
printf("Max clients reached - no more connections available\n");
return false;
}
pClient = NimBLEDevice::createClient();
printf("New client created\n");
pClient->setClientCallbacks(&clientCB, false);
/** Set initial connection parameters: These settings are 15ms interval, 0 latency, 120ms timout.
* These settings are safe for 3 clients to connect reliably, can go faster if you have less
* connections. Timeout should be a multiple of the interval, minimum is 100ms.
* Min interval: 12 * 1.25ms = 15, Max interval: 12 * 1.25ms = 15, 0 latency, 12 * 10ms = 120ms timeout
*/
pClient->setConnectionParams(6,6,0,15);
/** Set how long we are willing to wait for the connection to complete (seconds), default is 30. */
pClient->setConnectTimeout(5);
if (!pClient->connect(advDevice)) {
/** Created a client but failed to connect, don't need to keep it as it has no data */
NimBLEDevice::deleteClient(pClient);
printf("Failed to connect, deleted client\n");
return false;
}
}
if(!pClient->isConnected()) {
if (!pClient->connect(advDevice)) {
printf("Failed to connect\n");
return false;
}
}
printf("Connected to: %s RSSI: %d\n",
pClient->getPeerAddress().toString().c_str(),
pClient->getRssi());
/** Now we can read/write/subscribe the charateristics of the services we are interested in */
NimBLERemoteService* pSvc = nullptr;
NimBLERemoteCharacteristic* pChr = nullptr;
NimBLERemoteDescriptor* pDsc = nullptr;
pSvc = pClient->getService("DEAD");
if(pSvc) { /** make sure it's not null */
pChr = pSvc->getCharacteristic("BEEF");
}
if(pChr) { /** make sure it's not null */
if(pChr->canRead()) {
printf("%s Value: %s\n",
pChr->getUUID().toString().c_str(),
pChr->readValue().c_str());
}
if(pChr->canWrite()) {
if(pChr->writeValue("Tasty")) {
printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
}
else {
/** Disconnect if write failed */
pClient->disconnect();
return false;
}
if(pChr->canRead()) {
printf("The value of: %s is now: %s\n",
pChr->getUUID().toString().c_str(),
pChr->readValue().c_str());
}
}
/** registerForNotify() has been deprecated and replaced with subscribe() / unsubscribe().
* Subscribe parameter defaults are: notifications=true, notifyCallback=nullptr, response=false.
* Unsubscribe parameter defaults are: response=false.
*/
if(pChr->canNotify()) {
//if(!pChr->registerForNotify(notifyCB)) {
if(!pChr->subscribe(true, notifyCB)) {
/** Disconnect if subscribe failed */
pClient->disconnect();
return false;
}
}
else if(pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
//if(!pChr->registerForNotify(notifyCB, false)) {
if(!pChr->subscribe(false, notifyCB)) {
/** Disconnect if subscribe failed */
pClient->disconnect();
return false;
}
}
}
else{
printf("DEAD service not found.\n");
}
pSvc = pClient->getService("BAAD");
if(pSvc) { /** make sure it's not null */
pChr = pSvc->getCharacteristic("F00D");
}
if(pChr) { /** make sure it's not null */
if(pChr->canRead()) {
printf("%s Value: %s\n",
pChr->getUUID().toString().c_str(),
pChr->readValue().c_str());
}
pDsc = pChr->getDescriptor(NimBLEUUID("C01D"));
if(pDsc) { /** make sure it's not null */
printf("Descriptor: %s Value: %s\n",
pDsc->getUUID().toString().c_str(),
pDsc->readValue().c_str());
}
if(pChr->canWrite()) {
if(pChr->writeValue("No tip!")) {
printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
}
else {
/** Disconnect if write failed */
pClient->disconnect();
return false;
}
if(pChr->canRead()) {
printf("The value of: %s is now: %s\n",
pChr->getUUID().toString().c_str(),
pChr->readValue().c_str());
}
}
/** registerForNotify() has been deprecated and replaced with subscribe() / unsubscribe().
* Subscribe parameter defaults are: notifications=true, notifyCallback=nullptr, response=false.
* Unsubscribe parameter defaults are: response=false.
*/
if(pChr->canNotify()) {
//if(!pChr->registerForNotify(notifyCB)) {
if(!pChr->subscribe(true, notifyCB)) {
/** Disconnect if subscribe failed */
pClient->disconnect();
return false;
}
}
else if(pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
//if(!pChr->registerForNotify(notifyCB, false)) {
if(!pChr->subscribe(false, notifyCB)) {
/** Disconnect if subscribe failed */
pClient->disconnect();
return false;
}
}
}
else{
printf("BAAD service not found.\n");
}
printf("Done with this device!\n");
return true;
}
void connectTask (void * parameter){
/** Loop here until we find a device we want to connect to */
for(;;) {
if(doConnect) {
doConnect = false;
/** Found a device we want to connect to, do it now */
if(connectToServer()) {
printf("Success! we should now be getting notifications, scanning for more!\n");
} else {
printf("Failed to connect, starting scan\n");
}
NimBLEDevice::getScan()->start(scanTime,scanEndedCB);
}
vTaskDelay(10/portTICK_PERIOD_MS);
}
vTaskDelete(NULL);
}
void app_main (void){
printf("Starting NimBLE Client\n");
/** Initialize NimBLE, no device name spcified as we are not advertising */
NimBLEDevice::init("");
/** Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_KEYBOARD_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_KEYBOARD_ONLY); // use passkey
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/** 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, secure connections.
*
* These are the default values, only shown here for demonstration.
*/
//NimBLEDevice::setSecurityAuth(false, false, true);
NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
/** Optional: set the transmit power, default is -3db */
NimBLEDevice::setPower(ESP_PWR_LVL_P9); /** 12db */
/** Optional: set any devices you don't want to get advertisments from */
// NimBLEDevice::addIgnored(NimBLEAddress ("aa:bb:cc:dd:ee:ff"));
/** create new scan */
NimBLEScan* pScan = NimBLEDevice::getScan();
/** create a callback that gets called when advertisers are found */
pScan->setAdvertisedDeviceCallbacks(new AdvertisedDeviceCallbacks());
/** Set scan interval (how often) and window (how long) in milliseconds */
pScan->setInterval(400);
pScan->setWindow(100);
/** Active scan will gather scan response data from advertisers
* but will use more energy from both devices
*/
pScan->setActiveScan(true);
/** Start scanning for advertisers for the scan time specified (in seconds) 0 = forever
* Optional callback for when scanning stops.
*/
pScan->start(scanTime, scanEndedCB);
printf("Scanning for peripherals\n");
xTaskCreate(connectTask, "connectTask", 5000, NULL, 1, NULL);
}

View File

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_Server
include $(IDF_PATH)/make/project.mk

View File

@ -1,226 +0,0 @@
/** NimBLE_Server Demo:
*
* Demonstrates many of the available features of the NimBLE server library.
*
* Created: on March 22 2020
* Author: H2zero
*
*/
#include "NimBLEDevice.h"
#include "NimBLELog.h"
#include <stdio.h>
extern "C" {void app_main(void);}
static NimBLEServer* pServer;
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ServerCallbacks: public NimBLEServerCallbacks {
void onConnect(NimBLEServer* pServer) {
printf("Client connected\n");
NimBLEDevice::startAdvertising();
};
/** Alternative onConnect() method to extract details of the connection.
* See: src/ble_gap.h for the details of the ble_gap_conn_desc struct.
*/
void onConnect(NimBLEServer* pServer, ble_gap_conn_desc* desc) {
printf("Client address: %s\n", NimBLEAddress(desc->peer_ota_addr).toString().c_str());
/** We can use the connection handle here to ask for different connection parameters.
* Args: connection handle, min connection interval, max connection interval
* latency, supervision timeout.
* Units; Min/Max Intervals: 1.25 millisecond increments.
* Latency: number of intervals allowed to skip.
* Timeout: 10 millisecond increments, try for 3x interval time for best results.
*/
pServer->updateConnParams(desc->conn_handle, 24, 48, 0, 18);
};
void onDisconnect(NimBLEServer* pServer) {
printf("Client disconnected - start advertising\n");
NimBLEDevice::startAdvertising();
};
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
printf("Server Passkey Request\n");
/** This should return a random 6 digit number for security
* or make your own static passkey as done here.
*/
return 123456;
};
bool onConfirmPIN(uint32_t pass_key){
printf("The passkey YES/NO number: %d\n", pass_key);
/** Return false if passkeys don't match. */
return true;
};
void onAuthenticationComplete(ble_gap_conn_desc* desc){
/** Check that encryption was successful, if not we disconnect the client */
if(!desc->sec_state.encrypted) {
/** NOTE: createServer returns the current server reference unless one is not already created */
NimBLEDevice::createServer()->disconnect(desc->conn_handle);
printf("Encrypt connection failed - disconnecting client\n");
return;
}
printf("Starting BLE work!");
};
};
/** Handler class for characteristic actions */
class CharacteristicCallbacks: public NimBLECharacteristicCallbacks {
void onRead(NimBLECharacteristic* pCharacteristic){
printf("%s : onRead(), value: %s\n",
pCharacteristic->getUUID().toString().c_str(),
pCharacteristic->getValue().c_str());
};
void onWrite(NimBLECharacteristic* pCharacteristic) {
printf("%s : onWrite(), value: %s\n",
pCharacteristic->getUUID().toString().c_str(),
pCharacteristic->getValue().c_str());
};
/** Called before notification or indication is sent,
* the value can be changed here before sending if desired.
*/
void onNotify(NimBLECharacteristic* pCharacteristic) {
printf("Sending notification to clients\n");
};
/** The status returned in status is defined in NimBLECharacteristic.h.
* The value returned in code is the NimBLE host return code.
*/
void onStatus(NimBLECharacteristic* pCharacteristic, Status status, int code) {
printf("Notification/Indication status code: %d , return code: %d, %s\n",
status,
code,
NimBLEUtils::returnCodeToString(code));
};
};
/** Handler class for descriptor actions */
class DescriptorCallbacks : public NimBLEDescriptorCallbacks {
void onWrite(NimBLEDescriptor* pDescriptor) {
std::string dscVal((char*)pDescriptor->getValue(), pDescriptor->getLength());
printf("Descriptor witten value: %s\n", dscVal.c_str());
};
void onRead(NimBLEDescriptor* pDescriptor) {
printf("%s Descriptor read\n", pDescriptor->getUUID().toString().c_str());
};;
};
/** Define callback instances globally to use for multiple Charateristics \ Descriptors */
static DescriptorCallbacks dscCallbacks;
static CharacteristicCallbacks chrCallbacks;
void notifyTask(void * parameter){
for(;;) {
if(pServer->getConnectedCount()) {
NimBLEService* pSvc = pServer->getServiceByUUID("BAAD");
if(pSvc) {
NimBLECharacteristic* pChr = pSvc->getCharacteristic("F00D");
if(pChr) {
pChr->notify(true);
}
}
}
vTaskDelay(2000/portTICK_PERIOD_MS);
}
vTaskDelete(NULL);
}
void app_main(void) {
printf("Starting NimBLE Server\n");
/** sets device name */
NimBLEDevice::init("NimBLE");
/** Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_DISPLAY_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_ONLY); // use passkey
//NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/** 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, secure connections.
*
* These are the default values, only shown here for demonstration.
*/
//NimBLEDevice::setSecurityAuth(false, false, true);
NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
pServer = NimBLEDevice::createServer();
pServer->setCallbacks(new ServerCallbacks());
NimBLEService* pDeadService = pServer->createService("DEAD");
NimBLECharacteristic* pBeefCharacteristic = pDeadService->createCharacteristic(
"BEEF",
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE |
/** Require a secure connection for read and write access */
NIMBLE_PROPERTY::READ_ENC | // only allow reading if paired / encrypted
NIMBLE_PROPERTY::WRITE_ENC // only allow writing if paired / encrypted
);
pBeefCharacteristic->setValue("Burger");
pBeefCharacteristic->setCallbacks(&chrCallbacks);
/** 2902 and 2904 descriptors are a special case, when createDescriptor is called with
* either of those uuid's it will create the associated class with the correct properties
* and sizes. However we must cast the returned reference to the correct type as the method
* only returns a pointer to the base NimBLEDescriptor class.
*/
NimBLE2904* pBeef2904 = (NimBLE2904*)pBeefCharacteristic->createDescriptor("2904");
pBeef2904->setFormat(NimBLE2904::FORMAT_UTF8);
pBeef2904->setCallbacks(&dscCallbacks);
NimBLEService* pBaadService = pServer->createService("BAAD");
NimBLECharacteristic* pFoodCharacteristic = pBaadService->createCharacteristic(
"F00D",
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE |
NIMBLE_PROPERTY::NOTIFY
);
pFoodCharacteristic->setValue("Fries");
pFoodCharacteristic->setCallbacks(&chrCallbacks);
/** Custom descriptor: Arguments are UUID, Properties, max length in bytes of the value */
NimBLEDescriptor* pC01Ddsc = pFoodCharacteristic->createDescriptor(
"C01D",
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE|
NIMBLE_PROPERTY::WRITE_ENC, // only allow writing if paired / encrypted
20
);
pC01Ddsc->setValue("Send it back!");
pC01Ddsc->setCallbacks(&dscCallbacks);
/** Start the services when finished creating all Characteristics and Descriptors */
pDeadService->start();
pBaadService->start();
NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/** Add the services to the advertisment data **/
pAdvertising->addServiceUUID(pDeadService->getUUID());
pAdvertising->addServiceUUID(pBaadService->getUUID());
/** If your device is battery powered you may consider setting scan response
* to false as it will extend battery life at the expense of less data sent.
*/
pAdvertising->setScanResponse(true);
pAdvertising->start();
printf("Advertising Started\n");
xTaskCreate(notifyTask, "notifyTask", 5000, NULL, 1, NULL);
}

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(BLE_scan)
project(NimBLE_extended_client)

View File

@ -1,4 +1,4 @@
set(COMPONENT_SRCS "main.cpp")
set(COMPONENT_ADD_INCLUDEDIRS ".")
register_component()
register_component()

View File

@ -0,0 +1,144 @@
/**
* NimBLE Extended Client Demo:
*
* Demonstrates the Bluetooth 5.x client capabilities.
*
* Created: on April 2 2022
* Author: H2zero
*/
#include <NimBLEDevice.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
static const NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTimeMs = 10 * 1000; // In milliseconds, 0 = scan forever
/** Define the PHY's to use when connecting to peer devices, can be 1, 2, or all 3 (default).*/
static uint8_t connectPhys = BLE_GAP_LE_PHY_CODED_MASK | BLE_GAP_LE_PHY_1M_MASK /*| BLE_GAP_LE_PHY_2M_MASK */;
/** Define a class to handle the callbacks for client connection events */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) override { printf("Connected\n"); };
void onDisconnect(NimBLEClient* pClient, int reason) override {
printf("%s Disconnected, reason = %d - Starting scan\n", pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTimeMs);
}
} clientCallbacks;
/** Define a class to handle the callbacks when advertisements are received */
class scanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {
printf("Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if (advertisedDevice->isAdvertisingService(NimBLEUUID("ABCD"))) {
printf("Found Our Service\n");
doConnect = true;
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
}
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(const NimBLEScanResults& results, int rc) override { printf("Scan Ended\n"); }
} scanCallbacks;
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer() {
NimBLEClient* pClient = nullptr;
pClient = NimBLEDevice::createClient();
pClient->setClientCallbacks(&clientCallbacks, false);
/**
* Set the PHY's to use for this connection. This is a bitmask that represents the PHY's:
* * 0x01 BLE_GAP_LE_PHY_1M_MASK
* * 0x02 BLE_GAP_LE_PHY_2M_MASK
* * 0x04 BLE_GAP_LE_PHY_CODED_MASK
* Combine these with OR ("|"), eg BLE_GAP_LE_PHY_1M_MASK | BLE_GAP_LE_PHY_2M_MASK | BLE_GAP_LE_PHY_CODED_MASK;
*/
pClient->setConnectPhy(connectPhys);
/** Set how long we are willing to wait for the connection to complete (milliseconds), default is 30000. */
pClient->setConnectTimeout(10 * 1000);
if (!pClient->connect(advDevice)) {
/** Created a client but failed to connect, don't need to keep it as it has no data */
NimBLEDevice::deleteClient(pClient);
printf("Failed to connect, deleted client\n");
return false;
}
printf("Connected to: %s RSSI: %d\n", pClient->getPeerAddress().toString().c_str(), pClient->getRssi());
/** Now we can read/write/subscribe the characteristics of the services we are interested in */
NimBLERemoteService* pSvc = nullptr;
NimBLERemoteCharacteristic* pChr = nullptr;
pSvc = pClient->getService(SERVICE_UUID);
if (pSvc) {
pChr = pSvc->getCharacteristic(CHARACTERISTIC_UUID);
if (pChr) {
if (pChr->canRead()) {
std::string value = pChr->readValue();
printf("Characteristic value: %s\n", value.c_str());
}
}
} else {
printf("ABCD service not found.\n");
}
NimBLEDevice::deleteClient(pClient);
printf("Done with this device!\n");
return true;
}
extern "C" void app_main(void) {
printf("Starting NimBLE Client\n");
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("NimBLE Extended Client");
/** Create aNimBLE Scan instance and set the callbacks for scan events */
NimBLEScan* pScan = NimBLEDevice::getScan();
pScan->setScanCallbacks(&scanCallbacks);
/** Set scan interval (how often) and window (how long) in milliseconds */
pScan->setInterval(97);
pScan->setWindow(67);
/**
* Active scan will gather scan response data from advertisers
* but will use more energy from both devices
*/
pScan->setActiveScan(true);
/**
* Start scanning for advertisers for the scan time specified (in milliseconds) 0 = forever
* Optional callback for when scanning stops.
*/
pScan->start(scanTimeMs);
printf("Scanning for peripherals\n");
/** Loop here until we find a device we want to connect to */
for (;;) {
if (doConnect) {
if (connectToServer()) {
printf("Success!, scanning for more!\n");
} else {
printf("Failed to connect, starting scan\n");
}
doConnect = false;
NimBLEDevice::getScan()->start(scanTimeMs);
}
vTaskDelay(pdMS_TO_TICKS(10));
}
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_EXT_ADV=y

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(BLE_uart)
project(NimBLE_extended_scan)

View File

@ -0,0 +1,4 @@
set(COMPONENT_SRCS "main.cpp")
set(COMPONENT_ADD_INCLUDEDIRS ".")
register_component()

View File

@ -0,0 +1,69 @@
/**
* NimBLE Extended Scanner Demo:
*
* Demonstrates the Bluetooth 5.x scanning capabilities of the NimBLE library.
*
* Created: on November 28, 2024
* Author: H2zero
*/
#include <NimBLEDevice.h>
static uint32_t scanTimeMs = 10 * 1000; // In milliseconds, 0 = scan forever
static NimBLEScan::Phy scanPhy = NimBLEScan::Phy::SCAN_ALL;
/** Define a class to handle the callbacks when advertisements are received */
class ScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) {
printf("Advertised Device found: %s\n PHY1: %d\n PHY2: %d\n",
advertisedDevice->toString().c_str(),
advertisedDevice->getPrimaryPhy(),
advertisedDevice->getSecondaryPhy());
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(const NimBLEScanResults& scanResults, int reason) {
printf("Scan Ended, reason: %d; found %d devices\n", reason, scanResults.getCount());
/** Try Different PHY's */
switch (scanPhy) {
case NimBLEScan::Phy::SCAN_ALL:
printf("Scanning only 1M PHY\n");
scanPhy = NimBLEScan::Phy::SCAN_1M;
break;
case NimBLEScan::Phy::SCAN_1M:
printf("Scanning only CODED PHY\n");
scanPhy = NimBLEScan::Phy::SCAN_CODED;
break;
case NimBLEScan::Phy::SCAN_CODED:
printf("Scanning all PHY's\n");
scanPhy = NimBLEScan::Phy::SCAN_ALL;
break;
}
NimBLEScan* pScan = NimBLEDevice::getScan();
pScan->setPhy(scanPhy);
pScan->start(scanTimeMs);
}
} scanCallbacks;
extern "C" void app_main(void) {
printf("Starting Extended Scanner\n");
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("NimBLE Extended Scanner");
NimBLEScan* pScan = NimBLEDevice::getScan();
/** Set the callbacks that the scanner will call on events. */
pScan->setScanCallbacks(&scanCallbacks);
/** Use active scanning to obtain scan response data from advertisers */
pScan->setActiveScan(true);
/** Set the initial PHY's to scan on, default is SCAN_ALL */
pScan->setPhy(scanPhy);
/** Start scanning for scanTimeMs */
pScan->start(scanTimeMs);
printf("Scanning for peripherals\n");
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_EXT_ADV=y

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(BLE_client)
project(NimBLE_extended_server)

View File

@ -0,0 +1,4 @@
set(COMPONENT_SRCS "main.cpp")
set(COMPONENT_ADD_INCLUDEDIRS ".")
register_component()

View File

@ -0,0 +1,138 @@
/**
* NimBLE Extended Server Demo:
*
* Demonstrates the Bluetooth 5.x extended advertising capabilities.
*
* This demo will advertise a long data string on the CODED and 1M Phy's and
* starts a server allowing connection over either PHY's. It will advertise for
* 5 seconds then sleep for 20 seconds, if a client connects it will sleep once
* it has disconnected then repeats.
*
* Created: on April 2 2022
* Author: H2zero
*/
#include <NimBLEDevice.h>
#include <esp_sleep.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
/** Time in milliseconds to advertise */
static uint32_t advTime = 5000;
/** Time to sleep between advertisements */
static uint32_t sleepSeconds = 20;
/** Primary PHY used for advertising, can be one of BLE_HCI_LE_PHY_1M or BLE_HCI_LE_PHY_CODED */
static uint8_t primaryPhy = BLE_HCI_LE_PHY_CODED;
/**
* Secondary PHY used for advertising and connecting,
* can be one of BLE_HCI_LE_PHY_1M, BLE_HCI_LE_PHY_2M or BLE_HCI_LE_PHY_CODED
*/
static uint8_t secondaryPhy = BLE_HCI_LE_PHY_1M;
/** Handler class for server events */
class ServerCallbacks : public NimBLEServerCallbacks {
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) override {
printf("Client connected:: %s\n", connInfo.getAddress().toString().c_str());
}
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
printf("Client disconnected - sleeping for %" PRIu32 " seconds\n", sleepSeconds);
esp_deep_sleep_start();
}
} serverCallbacks;
/** Callback class to handle advertising events */
class AdvertisingCallbacks : public NimBLEExtAdvertisingCallbacks {
void onStopped(NimBLEExtAdvertising* pAdv, int reason, uint8_t instId) override {
/* Check the reason advertising stopped, don't sleep if client is connecting */
printf("Advertising instance %u stopped\n", instId);
switch (reason) {
case 0:
printf("Client connecting\n");
return;
case BLE_HS_ETIMEOUT:
printf("Time expired - sleeping for %" PRIu32 " seconds\n", sleepSeconds);
break;
default:
break;
}
esp_deep_sleep_start();
}
} advertisingCallbacks;
extern "C" void app_main(void) {
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("Extended advertiser");
/** Create the server and add the services/characteristics/descriptors */
NimBLEServer* pServer = NimBLEDevice::createServer();
pServer->setCallbacks(&serverCallbacks);
NimBLEService* pService = pServer->createService(SERVICE_UUID);
NimBLECharacteristic* pCharacteristic =
pService->createCharacteristic(CHARACTERISTIC_UUID,
NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::NOTIFY);
pCharacteristic->setValue("Hello World");
/** Start the service */
pService->start();
/**
* Create an extended advertisement with the instance ID 0 and set the PHY's.
* Multiple instances can be added as long as the instance ID is incremented.
*/
NimBLEExtAdvertisement extAdv(primaryPhy, secondaryPhy);
/** Set the advertisement as connectable */
extAdv.setConnectable(true);
/** As per Bluetooth specification, extended advertising cannot be both scannable and connectable */
extAdv.setScannable(false); // The default is false, set here for demonstration.
/** Extended advertising allows for 251 bytes (minus header bytes ~20) in a single advertisement or up to 1650 if chained */
extAdv.setServiceData(NimBLEUUID(SERVICE_UUID),
std::string("Extended Advertising Demo.\r\n"
"Extended advertising allows for "
"251 bytes of data in a single advertisement,\r\n"
"or up to 1650 bytes with chaining.\r\n"
"This example message is 226 bytes long "
"and is using CODED_PHY for long range."));
extAdv.setName("Extended advertiser");
/** When extended advertising is enabled `NimBLEDevice::getAdvertising` returns a pointer to `NimBLEExtAdvertising */
NimBLEExtAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/** Set the callbacks for advertising events */
pAdvertising->setCallbacks(&advertisingCallbacks);
/**
* NimBLEExtAdvertising::setInstanceData takes the instance ID and
* a reference to a `NimBLEExtAdvertisement` object. This sets the data
* that will be advertised for this instance ID, returns true if successful.
*
* Note: It is safe to create the advertisement as a local variable if setInstanceData
* is called before exiting the code block as the data will be copied.
*/
if (pAdvertising->setInstanceData(0, extAdv)) {
/**
* NimBLEExtAdvertising::start takes the advertisement instance ID to start
* and a duration in milliseconds or a max number of advertisements to send (or both).
*/
if (pAdvertising->start(0, advTime)) {
printf("Started advertising\n");
} else {
printf("Failed to start advertising\n");
}
} else {
printf("Failed to register advertisement data\n");
}
esp_sleep_enable_timer_wakeup(sleepSeconds * 1000000);
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_EXT_ADV=y

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(BLE_notify)
project(NimBLE_multi_advertiser)

View File

@ -0,0 +1,4 @@
set(COMPONENT_SRCS "main.cpp")
set(COMPONENT_ADD_INCLUDEDIRS ".")
register_component()

View File

@ -0,0 +1,168 @@
/**
* NimBLE Multi Advertiser Demo:
*
* Demonstrates the Bluetooth 5.x extended advertising capabilities.
*
* This demo will advertise 2 advertisements, and extended scannable instance
* and a connectable legacy instance. They will advertise for 5 seconds then
* sleep for 20 seconds. The extended scannable instance will use the scan
* request callback to update it's data when a scan response is requested.
*
* Created: on April 9 2022
* Author: H2zero
*/
#include <NimBLEDevice.h>
#include <esp_sleep.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
/** Time in milliseconds to advertise */
static uint32_t advTime = 5000;
/** Time to sleep between advertisements */
static uint32_t sleepTime = 20;
/** Primary PHY used for advertising, can be one of BLE_HCI_LE_PHY_1M or BLE_HCI_LE_PHY_CODED */
static uint8_t primaryPhy = BLE_HCI_LE_PHY_CODED;
/**
* Secondary PHY used for advertising and connecting,
* can be one of BLE_HCI_LE_PHY_1M, BLE_HCI_LE_PHY_2M or BLE_HCI_LE_PHY_CODED
*/
static uint8_t secondaryPhy = BLE_HCI_LE_PHY_1M;
/** Handler class for server events */
class ServerCallbacks : public NimBLEServerCallbacks {
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) override {
printf("Client connected: %s\n", connInfo.getAddress().toString().c_str());
}
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
printf("Client disconnected\n");
// if still advertising we won't sleep yet.
if (!pServer->getAdvertising()->isAdvertising()) {
printf("Sleeping for %" PRIu32 " seconds\n", sleepTime);
esp_deep_sleep_start();
}
}
} serverCallbacks;
/** Callback class to handle advertising events */
class AdvCallbacks : public NimBLEExtAdvertisingCallbacks {
void onStopped(NimBLEExtAdvertising* pAdv, int reason, uint8_t instId) override {
/* Check the reason advertising stopped, don't sleep if client is connecting */
printf("Advertising instance %u stopped\n", instId);
switch (reason) {
case 0:
printf(" client connecting\n");
return;
case BLE_HS_ETIMEOUT:
printf("Time expired - sleeping for %" PRIu32 " seconds\n", sleepTime);
break;
default:
break;
}
esp_deep_sleep_start();
}
bool m_updatedSR = false;
void onScanRequest(NimBLEExtAdvertising* pAdv, uint8_t instId, NimBLEAddress addr) override {
printf("Scan request for instance %u\n", instId);
// if the data has already been updated we don't need to change it again.
if (!m_updatedSR) {
printf("Updating scan data\n");
NimBLEExtAdvertisement sr;
sr.setServiceData(NimBLEUUID(SERVICE_UUID), std::string("Hello from scan response!"));
pAdv->setScanResponseData(instId, sr);
m_updatedSR = true;
}
}
} advCallbacks;
extern "C" void app_main(void) {
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("Multi advertiser");
/** Create a server for our legacy advertiser */
NimBLEServer* pServer = NimBLEDevice::createServer();
pServer->setCallbacks(&serverCallbacks);
NimBLEService* pService = pServer->createService(SERVICE_UUID);
NimBLECharacteristic* pCharacteristic =
pService->createCharacteristic(CHARACTERISTIC_UUID,
NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::NOTIFY);
pCharacteristic->setValue("Hello World");
/** Start the service */
pService->start();
/** Create our multi advertising instances */
/** extended scannable instance advertising on coded and 1m PHY's. */
NimBLEExtAdvertisement extScannable(primaryPhy, secondaryPhy);
/** Legacy advertising as a connectable device. */
NimBLEExtAdvertisement legacyConnectable;
/** Optional scan response data. */
NimBLEExtAdvertisement legacyScanResponse;
/** As per Bluetooth specification, extended advertising cannot be both scannable and connectable */
extScannable.setScannable(true);
extScannable.setConnectable(false);
/** Set the initial data */
extScannable.setServiceData(NimBLEUUID(SERVICE_UUID), std::string("Scan me!"));
/** Enable the scan response callback, we will use this to update the data. */
extScannable.enableScanRequestCallback(true);
/** Optional custom address for this advertisment. */
legacyConnectable.setAddress(NimBLEAddress("DE:AD:BE:EF:BA:AD"));
/** Set the advertising data. */
legacyConnectable.setName("Legacy");
legacyConnectable.setCompleteServices16({NimBLEUUID(SERVICE_UUID)});
/** Set the legacy and connectable flags. */
legacyConnectable.setLegacyAdvertising(true);
legacyConnectable.setConnectable(true);
/** Put some data in the scan response if desired. */
legacyScanResponse.setServiceData(NimBLEUUID(SERVICE_UUID), "Legacy SR");
/** Get the advertising ready */
NimBLEExtAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/** Set the callbacks to handle advertising events */
pAdvertising->setCallbacks(&advCallbacks);
/**
* Set instance data.
* Up to 5 instances can be used if configured in menuconfig, instance 0 is always available.
*
* We will set the extended scannable data on instance 0 and the legacy data on instance 1.
* Note that the legacy scan response data needs to be set to the same instance (1).
*/
if (pAdvertising->setInstanceData(0, extScannable) && pAdvertising->setInstanceData(1, legacyConnectable) &&
pAdvertising->setScanResponseData(1, legacyScanResponse)) {
/**
* NimBLEExtAdvertising::start takes the advertisement instance ID to start
* and a duration in milliseconds or a max number of advertisements to send (or both).
*/
if (pAdvertising->start(0, advTime) && pAdvertising->start(1, advTime)) {
printf("Started advertising\n");
} else {
printf("Failed to start advertising\n");
}
} else {
printf("Failed to register advertisement data\n");
}
esp_sleep_enable_timer_wakeup(sleepTime * 1000000);
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_EXT_ADV=y

View File

@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(Continuous_scan)

View File

@ -0,0 +1,46 @@
/**
* Continuous Scan Example
*
* This example demonstrates how to continuously scan for BLE devices.
* When devices are found the onDiscovered and onResults callbacks will be called with the device data.
* The scan will not store the results, only the callbacks will be used
* When the scan timeout is reached the onScanEnd callback will be called and the scan will be restarted.
* This will clear the duplicate cache in the controller and allow the same devices to be reported again.
*
* Created: on March 24 2020
* Author: H2zero
*/
#include <NimBLEDevice.h>
static constexpr uint32_t scanTime = 30 * 1000; // 30 seconds scan time.
class scanCallbacks : public NimBLEScanCallbacks {
/** Initial discovery, advertisement data only. */
void onDiscovered(const NimBLEAdvertisedDevice* advertisedDevice) override {
printf("Discovered Device: %s\n", advertisedDevice->toString().c_str());
}
/**
* If active scanning the result here will have the scan response data.
* If not active scanning then this will be the same as onDiscovered.
*/
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {
printf("Device result: %s\n", advertisedDevice->toString().c_str());
}
void onScanEnd(const NimBLEScanResults& results, int reason) override {
printf("Scan ended reason = %d; restarting scan\n", reason);
NimBLEDevice::getScan()->start(scanTime, false, true);
}
} scanCallbacks;
extern "C" void app_main() {
NimBLEDevice::init(""); // Initialize the device, you can specify a device name if you want.
NimBLEScan* pBLEScan = NimBLEDevice::getScan(); // Create the scan object.
pBLEScan->setScanCallbacks(&scanCallbacks, false); // Set the callback for when devices are discovered, no duplicates.
pBLEScan->setActiveScan(true); // Set active scanning, this will get more data from the advertiser.
pBLEScan->setMaxResults(0); // Do not store the scan results, use callback only.
pBLEScan->start(scanTime, false, true); // duration, not a continuation of last scan, restart to get all devices again.
printf("Scanning...\n");
}

View File

@ -0,0 +1,12 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y

5
examples/L2CAP/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.vscode
build
sdkconfig
sdkconfig.old
dependencies.lock

View File

@ -0,0 +1,7 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32 esp32s3 esp32c3 esp32c6)
project(L2CAP_client)

View File

@ -1,3 +1,3 @@
PROJECT_NAME := BLE_scan
PROJECT_NAME := L2CAP_client
include $(IDF_PATH)/make/project.mk

View File

@ -0,0 +1,3 @@
dependencies:
local/esp-nimble-cpp:
path: ../../../../../esp-nimble-cpp/

View File

@ -0,0 +1,165 @@
#include <NimBLEDevice.h>
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
// The remote service we wish to connect to.
static BLEUUID serviceUUID("dcbc7255-1e9e-49a0-a360-b0430b6c6905");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("371a55c8-f251-4ad2-90b3-c7c195b049be");
#define L2CAP_CHANNEL 150
#define L2CAP_MTU 5000
const BLEAdvertisedDevice* theDevice = NULL;
BLEClient* theClient = NULL;
BLEL2CAPChannel* theChannel = NULL;
size_t bytesSent = 0;
size_t bytesReceived = 0;
class L2CAPChannelCallbacks: public BLEL2CAPChannelCallbacks {
public:
void onConnect(NimBLEL2CAPChannel* channel) {
printf("L2CAP connection established\n");
}
void onMTUChange(NimBLEL2CAPChannel* channel, uint16_t mtu) {
printf("L2CAP MTU changed to %d\n", mtu);
}
void onRead(NimBLEL2CAPChannel* channel, std::vector<uint8_t>& data) {
printf("L2CAP read %d bytes\n", data.size());
}
void onDisconnect(NimBLEL2CAPChannel* channel) {
printf("L2CAP disconnected\n");
}
};
class MyClientCallbacks: public BLEClientCallbacks {
void onConnect(BLEClient* pClient) {
printf("GAP connected\n");
pClient->setDataLen(251);
theChannel = BLEL2CAPChannel::connect(pClient, L2CAP_CHANNEL, L2CAP_MTU, new L2CAPChannelCallbacks());
}
void onDisconnect(BLEClient* pClient, int reason) {
printf("GAP disconnected (reason: %d)\n", reason);
theDevice = NULL;
theChannel = NULL;
vTaskDelay(1000 / portTICK_PERIOD_MS);
BLEDevice::getScan()->start(5 * 1000, true);
}
};
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(const BLEAdvertisedDevice* advertisedDevice) {
if (theDevice) { return; }
printf("BLE Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if (!advertisedDevice->haveServiceUUID()) { return; }
if (!advertisedDevice->isAdvertisingService(serviceUUID)) { return; }
printf("Found the device we're interested in!\n");
BLEDevice::getScan()->stop();
// Hand over the device to the other task
theDevice = advertisedDevice;
}
};
void connectTask(void *pvParameters) {
uint8_t sequenceNumber = 0;
while (true) {
if (!theDevice) {
vTaskDelay(1000 / portTICK_PERIOD_MS);
continue;
}
if (!theClient) {
theClient = BLEDevice::createClient();
theClient->setConnectionParams(6, 6, 0, 42);
auto callbacks = new MyClientCallbacks();
theClient->setClientCallbacks(callbacks);
auto success = theClient->connect(theDevice);
if (!success) {
printf("Error: Could not connect to device\n");
break;
}
vTaskDelay(2000 / portTICK_PERIOD_MS);
continue;
}
if (!theChannel) {
printf("l2cap channel not initialized\n");
vTaskDelay(2000 / portTICK_PERIOD_MS);
continue;
}
if (!theChannel->isConnected()) {
printf("l2cap channel not connected\n");
vTaskDelay(2000 / portTICK_PERIOD_MS);
continue;
}
while (theChannel->isConnected()) {
/*
static auto initialDelay = true;
if (initialDelay) {
printf("Waiting gracefully 3 seconds before sending data\n");
vTaskDelay(3000 / portTICK_PERIOD_MS);
initialDelay = false;
};
*/
std::vector<uint8_t> data(5000, sequenceNumber++);
if (theChannel->write(data)) {
bytesSent += data.size();
} else {
printf("failed to send!\n");
abort();
}
}
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
extern "C"
void app_main(void) {
printf("Starting L2CAP client example\n");
xTaskCreate(connectTask, "connectTask", 5000, NULL, 1, NULL);
BLEDevice::init("L2CAP-Client");
BLEDevice::setMTU(BLE_ATT_MTU_MAX);
auto scan = BLEDevice::getScan();
auto callbacks = new MyAdvertisedDeviceCallbacks();
scan->setScanCallbacks(callbacks);
scan->setInterval(1349);
scan->setWindow(449);
scan->setActiveScan(true);
scan->start(25 * 1000, false);
int numberOfSeconds = 0;
while (bytesSent == 0) {
vTaskDelay(10 / portTICK_PERIOD_MS);
}
while (true) {
vTaskDelay(1000 / portTICK_PERIOD_MS);
int bytesSentPerSeconds = bytesSent / ++numberOfSeconds;
printf("Bandwidth: %d b/sec = %d KB/sec\n", bytesSentPerSeconds, bytesSentPerSeconds / 1024);
}
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM=1

View File

@ -0,0 +1,7 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32 esp32s3 esp32c3 esp32c6)
project(L2CAP_server)

View File

@ -1,3 +1,3 @@
PROJECT_NAME := BLE_server
PROJECT_NAME := L2CAP_server
include $(IDF_PATH)/make/project.mk

View File

@ -0,0 +1,3 @@
dependencies:
local/esp-nimble-cpp:
path: ../../../../../esp-nimble-cpp/

View File

@ -0,0 +1,90 @@
#include <NimBLEDevice.h>
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "dcbc7255-1e9e-49a0-a360-b0430b6c6905"
#define CHARACTERISTIC_UUID "371a55c8-f251-4ad2-90b3-c7c195b049be"
#define L2CAP_CHANNEL 150
#define L2CAP_MTU 5000
class GATTCallbacks: public BLEServerCallbacks {
public:
void onConnect(BLEServer* pServer, BLEConnInfo& info) {
/// Booster #1
pServer->setDataLen(info.getConnHandle(), 251);
/// Booster #2 (especially for Apple devices)
BLEDevice::getServer()->updateConnParams(info.getConnHandle(), 12, 12, 0, 200);
}
};
class L2CAPChannelCallbacks: public BLEL2CAPChannelCallbacks {
public:
bool connected = false;
size_t numberOfReceivedBytes;
uint8_t nextSequenceNumber;
public:
void onConnect(NimBLEL2CAPChannel* channel) {
printf("L2CAP connection established\n");
connected = true;
numberOfReceivedBytes = nextSequenceNumber = 0;
}
void onRead(NimBLEL2CAPChannel* channel, std::vector<uint8_t>& data) {
numberOfReceivedBytes += data.size();
size_t sequenceNumber = data[0];
printf("L2CAP read %d bytes w/ sequence number %d", data.size(), sequenceNumber);
if (sequenceNumber != nextSequenceNumber) {
printf("(wrong sequence number %d, expected %d)\n", sequenceNumber, nextSequenceNumber);
} else {
printf("\n");
nextSequenceNumber++;
}
}
void onDisconnect(NimBLEL2CAPChannel* channel) {
printf("L2CAP disconnected\n");
connected = false;
}
};
extern "C"
void app_main(void) {
printf("Starting L2CAP server example [%lu free] [%lu min]\n", esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
BLEDevice::init("L2CAP-Server");
BLEDevice::setMTU(BLE_ATT_MTU_MAX);
auto cocServer = BLEDevice::createL2CAPServer();
auto l2capChannelCallbacks = new L2CAPChannelCallbacks();
auto channel = cocServer->createService(L2CAP_CHANNEL, L2CAP_MTU, l2capChannelCallbacks);
auto server = BLEDevice::createServer();
server->setCallbacks(new GATTCallbacks());
auto service = server->createService(SERVICE_UUID);
auto characteristic = service->createCharacteristic(CHARACTERISTIC_UUID, NIMBLE_PROPERTY::READ);
characteristic->setValue(L2CAP_CHANNEL);
service->start();
auto advertising = BLEDevice::getAdvertising();
advertising->addServiceUUID(SERVICE_UUID);
advertising->enableScanResponse(true);
BLEDevice::startAdvertising();
printf("Server waiting for connection requests [%lu free] [%lu min]\n", esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
// Wait until transfer actually starts...
while (!l2capChannelCallbacks->numberOfReceivedBytes) {
vTaskDelay(10 / portTICK_PERIOD_MS);
}
printf("\n\n\n");
int numberOfSeconds = 0;
while (true) {
vTaskDelay(1000 / portTICK_PERIOD_MS);
if (!l2capChannelCallbacks->connected) { continue; }
int bps = l2capChannelCallbacks->numberOfReceivedBytes / ++numberOfSeconds;
printf("Bandwidth: %d b/sec = %d KB/sec [%lu free] [%lu min]\n", bps, bps / 1024, esp_get_free_heap_size(), esp_get_minimum_free_heap_size());
}
}

View File

@ -0,0 +1,13 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM=1

View File

@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(NimBLE_Async_Client)

View File

@ -0,0 +1,83 @@
/**
* NimBLE_Async_client Demo:
*
* Demonstrates asynchronous client operations.
*
* Created: on November 4, 2024
* Author: H2zero
*/
#include <NimBLEDevice.h>
static constexpr uint32_t scanTimeMs = 5 * 1000;
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) override {
printf("Connected to: %s\n", pClient->getPeerAddress().toString().c_str());
}
void onDisconnect(NimBLEClient* pClient, int reason) override {
printf("%s Disconnected, reason = %d - Starting scan\n", pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTimeMs);
}
} clientCallbacks;
class ScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {
printf("Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if (advertisedDevice->haveName() && advertisedDevice->getName() == "NimBLE-Server") {
printf("Found Our Device\n");
/** Async connections can be made directly in the scan callbacks */
auto pClient = NimBLEDevice::getDisconnectedClient();
if (!pClient) {
pClient = NimBLEDevice::createClient(advertisedDevice->getAddress());
if (!pClient) {
printf("Failed to create client\n");
return;
}
}
pClient->setClientCallbacks(&clientCallbacks, false);
if (!pClient->connect(true, true, false)) { // delete attributes, async connect, no MTU exchange
NimBLEDevice::deleteClient(pClient);
printf("Failed to connect\n");
return;
}
}
}
void onScanEnd(const NimBLEScanResults& results, int reason) override {
printf("Scan Ended\n");
NimBLEDevice::getScan()->start(scanTimeMs);
}
} scanCallbacks;
extern "C" void app_main(void) {
printf("Starting NimBLE Async Client\n");
NimBLEDevice::init("Async-Client");
NimBLEDevice::setPower(3); /** +3db */
NimBLEScan* pScan = NimBLEDevice::getScan();
pScan->setScanCallbacks(&scanCallbacks);
pScan->setInterval(45);
pScan->setWindow(15);
pScan->setActiveScan(true);
pScan->start(scanTimeMs);
for (;;) {
vTaskDelay(pdMS_TO_TICKS(1000));
auto pClients = NimBLEDevice::getConnectedClients();
if (!pClients.size()) {
continue;
}
for (auto& pClient : pClients) {
printf("%s\n", pClient->toString().c_str());
NimBLEDevice::deleteClient(pClient);
}
NimBLEDevice::getScan()->start(scanTimeMs);
}
}

View File

@ -0,0 +1,12 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(NimBLE_Client)

View File

@ -0,0 +1,304 @@
/** NimBLE_Client Demo:
*
* Demonstrates many of the available features of the NimBLE client library.
*
* Created: on March 24 2020
* Author: H2zero
*/
#include <NimBLEDevice.h>
static const NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTimeMs = 5000; /** scan time in milliseconds, 0 = scan forever */
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) override { printf("Connected\n"); }
void onDisconnect(NimBLEClient* pClient, int reason) override {
printf("%s Disconnected, reason = %d - Starting scan\n", pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTimeMs, false, true);
}
/********************* Security handled here *********************/
void onPassKeyEntry(NimBLEConnInfo& connInfo) override {
printf("Server Passkey Entry\n");
/**
* This should prompt the user to enter the passkey displayed
* on the peer device.
*/
NimBLEDevice::injectPassKey(connInfo, 123456);
}
void onConfirmPasskey(NimBLEConnInfo& connInfo, uint32_t pass_key) override {
printf("The passkey YES/NO number: %" PRIu32 "\n", pass_key);
/** Inject false if passkeys don't match. */
NimBLEDevice::injectConfirmPasskey(connInfo, true);
}
/** Pairing process complete, we can check the results in connInfo */
void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
if (!connInfo.isEncrypted()) {
printf("Encrypt connection failed - disconnecting\n");
/** Find the client with the connection handle provided in connInfo */
NimBLEDevice::getClientByHandle(connInfo.getConnHandle())->disconnect();
return;
}
}
} clientCallbacks;
/** Define a class to handle the callbacks when scan events are received */
class ScanCallbacks : public NimBLEScanCallbacks {
void onResult(const NimBLEAdvertisedDevice* advertisedDevice) override {
printf("Advertised Device found: %s\n", advertisedDevice->toString().c_str());
if (advertisedDevice->isAdvertisingService(NimBLEUUID("DEAD"))) {
printf("Found Our Service\n");
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/** Ready to connect now */
doConnect = true;
}
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(const NimBLEScanResults& results, int reason) override {
printf("Scan Ended, reason: %d, device count: %d; Restarting scan\n", reason, results.getCount());
NimBLEDevice::getScan()->start(scanTimeMs, false, true);
}
} scanCallbacks;
/** Notification / Indication receiving handler callback */
void notifyCB(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {
std::string str = (isNotify == true) ? "Notification" : "Indication";
str += " from ";
str += pRemoteCharacteristic->getClient()->getPeerAddress().toString();
str += ": Service = " + pRemoteCharacteristic->getRemoteService()->getUUID().toString();
str += ", Characteristic = " + pRemoteCharacteristic->getUUID().toString();
str += ", Value = " + std::string((char*)pData, length);
printf("%s\n", str.c_str());
}
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer() {
NimBLEClient* pClient = nullptr;
/** Check if we have a client we should reuse first **/
if (NimBLEDevice::getCreatedClientCount()) {
/**
* Special case when we already know this device, we send false as the
* second argument in connect() to prevent refreshing the service database.
* This saves considerable time and power.
*/
pClient = NimBLEDevice::getClientByPeerAddress(advDevice->getAddress());
if (pClient) {
if (!pClient->connect(advDevice, false)) {
printf("Reconnect failed\n");
return false;
}
printf("Reconnected client\n");
} else {
/**
* We don't already have a client that knows this device,
* check for a client that is disconnected that we can use.
*/
pClient = NimBLEDevice::getDisconnectedClient();
}
}
/** No client to reuse? Create a new one. */
if (!pClient) {
if (NimBLEDevice::getCreatedClientCount() >= NIMBLE_MAX_CONNECTIONS) {
printf("Max clients reached - no more connections available\n");
return false;
}
pClient = NimBLEDevice::createClient();
printf("New client created\n");
pClient->setClientCallbacks(&clientCallbacks, false);
/**
* Set initial connection parameters:
* These settings are safe for 3 clients to connect reliably, can go faster if you have less
* connections. Timeout should be a multiple of the interval, minimum is 100ms.
* Min interval: 12 * 1.25ms = 15, Max interval: 12 * 1.25ms = 15, 0 latency, 150 * 10ms = 1500ms timeout
*/
pClient->setConnectionParams(12, 12, 0, 150);
/** Set how long we are willing to wait for the connection to complete (milliseconds), default is 30000. */
pClient->setConnectTimeout(5 * 1000);
if (!pClient->connect(advDevice)) {
/** Created a client but failed to connect, don't need to keep it as it has no data */
NimBLEDevice::deleteClient(pClient);
printf("Failed to connect, deleted client\n");
return false;
}
}
if (!pClient->isConnected()) {
if (!pClient->connect(advDevice)) {
printf("Failed to connect\n");
return false;
}
}
printf("Connected to: %s RSSI: %d\n", pClient->getPeerAddress().toString().c_str(), pClient->getRssi());
/** Now we can read/write/subscribe the characteristics of the services we are interested in */
NimBLERemoteService* pSvc = nullptr;
NimBLERemoteCharacteristic* pChr = nullptr;
NimBLERemoteDescriptor* pDsc = nullptr;
pSvc = pClient->getService("DEAD");
if (pSvc) {
pChr = pSvc->getCharacteristic("BEEF");
}
if (pChr) {
if (pChr->canRead()) {
printf("%s Value: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
if (pChr->canWrite()) {
if (pChr->writeValue("Tasty")) {
printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
} else {
pClient->disconnect();
return false;
}
if (pChr->canRead()) {
printf("The value of: %s is now: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
}
if (pChr->canNotify()) {
if (!pChr->subscribe(true, notifyCB)) {
pClient->disconnect();
return false;
}
} else if (pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
if (!pChr->subscribe(false, notifyCB)) {
pClient->disconnect();
return false;
}
}
} else {
printf("DEAD service not found.\n");
}
pSvc = pClient->getService("BAAD");
if (pSvc) {
pChr = pSvc->getCharacteristic("F00D");
if (pChr) {
if (pChr->canRead()) {
printf("%s Value: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
pDsc = pChr->getDescriptor(NimBLEUUID("C01D"));
if (pDsc) {
printf("Descriptor: %s Value: %s\n", pDsc->getUUID().toString().c_str(), pDsc->readValue().c_str());
}
if (pChr->canWrite()) {
if (pChr->writeValue("No tip!")) {
printf("Wrote new value to: %s\n", pChr->getUUID().toString().c_str());
} else {
pClient->disconnect();
return false;
}
if (pChr->canRead()) {
printf("The value of: %s is now: %s\n", pChr->getUUID().toString().c_str(), pChr->readValue().c_str());
}
}
if (pChr->canNotify()) {
if (!pChr->subscribe(true, notifyCB)) {
pClient->disconnect();
return false;
}
} else if (pChr->canIndicate()) {
/** Send false as first argument to subscribe to indications instead of notifications */
if (!pChr->subscribe(false, notifyCB)) {
pClient->disconnect();
return false;
}
}
}
} else {
printf("BAAD service not found.\n");
}
printf("Done with this device!\n");
return true;
}
extern "C" void app_main(void) {
printf("Starting NimBLE Client\n");
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("NimBLE-Client");
/**
* Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_KEYBOARD_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_KEYBOARD_ONLY); // use passkey
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/**
* 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, BLE secure connections.
* These are the default values, only shown here for demonstration.
*/
// NimBLEDevice::setSecurityAuth(false, false, true);
NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
/** Optional: set the transmit power */
NimBLEDevice::setPower(3); /** 3dbm */
NimBLEScan* pScan = NimBLEDevice::getScan();
/** Set the callbacks to call when scan events occur, no duplicates */
pScan->setScanCallbacks(&scanCallbacks, false);
/** Set scan interval (how often) and window (how long) in milliseconds */
pScan->setInterval(100);
pScan->setWindow(100);
/**
* Active scan will gather scan response data from advertisers
* but will use more energy from both devices
*/
pScan->setActiveScan(true);
/** Start scanning for advertisers */
pScan->start(scanTimeMs);
printf("Scanning for peripherals\n");
/** Loop here until we find a device we want to connect to */
for (;;) {
vTaskDelay(10 / portTICK_PERIOD_MS);
if (doConnect) {
doConnect = false;
/** Found a device we want to connect to, do it now */
if (connectToServer()) {
printf("Success! we should now be getting notifications, scanning for more!\n");
} else {
printf("Failed to connect, starting scan\n");
}
NimBLEDevice::getScan()->start(scanTimeMs, false, true);
}
}
}

View File

@ -0,0 +1,12 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y

View File

@ -3,5 +3,4 @@
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(NimBLE_Server)

View File

@ -0,0 +1,218 @@
/**
* NimBLE_Server Demo:
*
* Demonstrates many of the available features of the NimBLE server library.
*
* Created: on March 22 2020
* Author: H2zero
*/
#include <NimBLEDevice.h>
static NimBLEServer* pServer;
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class ServerCallbacks : public NimBLEServerCallbacks {
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo) override {
printf("Client address: %s\n", connInfo.getAddress().toString().c_str());
/**
* We can use the connection handle here to ask for different connection parameters.
* Args: connection handle, min connection interval, max connection interval
* latency, supervision timeout.
* Units; Min/Max Intervals: 1.25 millisecond increments.
* Latency: number of intervals allowed to skip.
* Timeout: 10 millisecond increments.
*/
pServer->updateConnParams(connInfo.getConnHandle(), 24, 48, 0, 180);
}
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
printf("Client disconnected - start advertising\n");
NimBLEDevice::startAdvertising();
}
void onMTUChange(uint16_t MTU, NimBLEConnInfo& connInfo) override {
printf("MTU updated: %u for connection ID: %u\n", MTU, connInfo.getConnHandle());
}
/********************* Security handled here *********************/
uint32_t onPassKeyDisplay() override {
printf("Server Passkey Display\n");
/**
* This should return a random 6 digit number for security
* or make your own static passkey as done here.
*/
return 123456;
}
void onConfirmPassKey(NimBLEConnInfo& connInfo, uint32_t pass_key) override {
printf("The passkey YES/NO number: %" PRIu32 "\n", pass_key);
/** Inject false if passkeys don't match. */
NimBLEDevice::injectConfirmPasskey(connInfo, true);
}
void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
/** Check that encryption was successful, if not we disconnect the client */
if (!connInfo.isEncrypted()) {
NimBLEDevice::getServer()->disconnect(connInfo.getConnHandle());
printf("Encrypt connection failed - disconnecting client\n");
return;
}
printf("Secured connection to: %s\n", connInfo.getAddress().toString().c_str());
}
} serverCallbacks;
/** Handler class for characteristic actions */
class CharacteristicCallbacks : public NimBLECharacteristicCallbacks {
void onRead(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override {
printf("%s : onRead(), value: %s\n",
pCharacteristic->getUUID().toString().c_str(),
pCharacteristic->getValue().c_str());
}
void onWrite(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override {
printf("%s : onWrite(), value: %s\n",
pCharacteristic->getUUID().toString().c_str(),
pCharacteristic->getValue().c_str());
}
/**
* The value returned in code is the NimBLE host return code.
*/
void onStatus(NimBLECharacteristic* pCharacteristic, int code) override {
printf("Notification/Indication return code: %d, %s\n", code, NimBLEUtils::returnCodeToString(code));
}
/** Peer subscribed to notifications/indications */
void onSubscribe(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, uint16_t subValue) override {
std::string str = "Client ID: ";
str += connInfo.getConnHandle();
str += " Address: ";
str += connInfo.getAddress().toString();
if (subValue == 0) {
str += " Unsubscribed to ";
} else if (subValue == 1) {
str += " Subscribed to notifications for ";
} else if (subValue == 2) {
str += " Subscribed to indications for ";
} else if (subValue == 3) {
str += " Subscribed to notifications and indications for ";
}
str += std::string(pCharacteristic->getUUID());
printf("%s\n", str.c_str());
}
} chrCallbacks;
/** Handler class for descriptor actions */
class DescriptorCallbacks : public NimBLEDescriptorCallbacks {
void onWrite(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
std::string dscVal = pDescriptor->getValue();
printf("Descriptor written value: %s\n", dscVal.c_str());
}
void onRead(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
printf("%s Descriptor read\n", pDescriptor->getUUID().toString().c_str());
}
} dscCallbacks;
extern "C" void app_main(void) {
printf("Starting NimBLE Server\n");
/** Initialize NimBLE and set the device name */
NimBLEDevice::init("NimBLE");
/**
* Set the IO capabilities of the device, each option will trigger a different pairing method.
* BLE_HS_IO_DISPLAY_ONLY - Passkey pairing
* BLE_HS_IO_DISPLAY_YESNO - Numeric comparison pairing
* BLE_HS_IO_NO_INPUT_OUTPUT - DEFAULT setting - just works pairing
*/
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_ONLY); // use passkey
// NimBLEDevice::setSecurityIOCap(BLE_HS_IO_DISPLAY_YESNO); //use numeric comparison
/**
* 2 different ways to set security - both calls achieve the same result.
* no bonding, no man in the middle protection, BLE secure connections.
*
* These are the default values, only shown here for demonstration.
*/
// NimBLEDevice::setSecurityAuth(false, false, true);
NimBLEDevice::setSecurityAuth(/*BLE_SM_PAIR_AUTHREQ_BOND | BLE_SM_PAIR_AUTHREQ_MITM |*/ BLE_SM_PAIR_AUTHREQ_SC);
pServer = NimBLEDevice::createServer();
pServer->setCallbacks(&serverCallbacks);
NimBLEService* pDeadService = pServer->createService("DEAD");
NimBLECharacteristic* pBeefCharacteristic =
pDeadService->createCharacteristic("BEEF",
NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE |
/** Require a secure connection for read and write access */
NIMBLE_PROPERTY::READ_ENC | // only allow reading if paired / encrypted
NIMBLE_PROPERTY::WRITE_ENC // only allow writing if paired / encrypted
);
pBeefCharacteristic->setValue("Burger");
pBeefCharacteristic->setCallbacks(&chrCallbacks);
/**
* 2902 and 2904 descriptors are a special case, when createDescriptor is called with
* either of those uuid's it will create the associated class with the correct properties
* and sizes. However we must cast the returned reference to the correct type as the method
* only returns a pointer to the base NimBLEDescriptor class.
*/
NimBLE2904* pBeef2904 = pBeefCharacteristic->create2904();
pBeef2904->setFormat(NimBLE2904::FORMAT_UTF8);
pBeef2904->setCallbacks(&dscCallbacks);
NimBLEService* pBaadService = pServer->createService("BAAD");
NimBLECharacteristic* pFoodCharacteristic =
pBaadService->createCharacteristic("F00D", NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::NOTIFY);
pFoodCharacteristic->setValue("Fries");
pFoodCharacteristic->setCallbacks(&chrCallbacks);
/** Custom descriptor: Arguments are UUID, Properties, max length of the value in bytes */
NimBLEDescriptor* pC01Ddsc =
pFoodCharacteristic->createDescriptor("C01D",
NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_ENC,
20);
pC01Ddsc->setValue("Send it back!");
pC01Ddsc->setCallbacks(&dscCallbacks);
/** Start the services when finished creating all Characteristics and Descriptors */
pDeadService->start();
pBaadService->start();
/** Create an advertising instance and add the services to the advertised data */
NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
pAdvertising->setName("NimBLE-Server");
pAdvertising->addServiceUUID(pDeadService->getUUID());
pAdvertising->addServiceUUID(pBaadService->getUUID());
/**
* If your device is battery powered you may consider setting scan response
* to false as it will extend battery life at the expense of less data sent.
*/
pAdvertising->enableScanResponse(true);
pAdvertising->start();
printf("Advertising Started\n");
/** Loop here and send notifications to connected peers */
for (;;) {
if (pServer->getConnectedCount()) {
NimBLEService* pSvc = pServer->getServiceByUUID("BAAD");
if (pSvc) {
NimBLECharacteristic* pChr = pSvc->getCharacteristic("F00D");
if (pChr) {
pChr->notify();
}
}
}
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}

View File

@ -0,0 +1,12 @@
# Override some defaults so BT stack is enabled
# in this example
#
# BT config
#
CONFIG_BT_ENABLED=y
CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y
CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n
CONFIG_BTDM_CTRL_MODE_BTDM=n
CONFIG_BT_BLUEDROID_ENABLED=n
CONFIG_BT_NIMBLE_ENABLED=y

View File

@ -1,3 +0,0 @@
PROJECT_NAME := BLE_client
include $(IDF_PATH)/make/project.mk

View File

@ -1,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

@ -1,200 +0,0 @@
/**
* A BLE client example that is rich in capabilities.
* There is a lot new capabilities implemented.
* author unknown
* updated by chegewara
* updated for NimBLE by H2zero
*/
/** NimBLE differences highlighted in comment blocks **/
/*******original********
#include "BLEDevice.h"
***********************/
#include "NimBLEDevice.h"
extern "C"{void app_main(void);}
// The remote service we wish to connect to.
static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");
static bool doConnect = false;
static bool connected = false;
static bool doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
printf("Notify callback for characteristic %s of data length %d data: %s\n",
pBLERemoteCharacteristic->getUUID().toString().c_str(),
length,
(char*)pData);
}
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
}
void onDisconnect(BLEClient* pclient) {
connected = false;
printf("onDisconnect");
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
printf("Client PassKeyRequest\n");
return 123456;
}
bool onConfirmPIN(uint32_t pass_key){
printf("The passkey YES/NO number: %d\n", pass_key);
return true;
}
void onAuthenticationComplete(ble_gap_conn_desc desc){
printf("Starting BLE work!\n");
}
/*******************************************************************/
};
bool connectToServer() {
printf("Forming a connection to %s\n", myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
printf(" - Created client\n");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
printf(" - Connected to server\n");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
printf("Failed to find our service UUID: %s\n", serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
printf(" - Found our service\n");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);
if (pRemoteCharacteristic == nullptr) {
printf("Failed to find our characteristic UUID: %s\n", charUUID.toString().c_str());
pClient->disconnect();
return false;
}
printf(" - Found our characteristic\n");
// Read the value of the characteristic.
if(pRemoteCharacteristic->canRead()) {
std::string value = pRemoteCharacteristic->readValue();
printf("The characteristic value was: %s\n", value.c_str());
}
/** registerForNotify() has been deprecated and replaced with subscribe() / unsubscribe().
* Subscribe parameter defaults are: notifications=true, notifyCallback=nullptr, response=false.
* Unsubscribe parameter defaults are: response=false.
*/
if(pRemoteCharacteristic->canNotify()) {
//pRemoteCharacteristic->registerForNotify(notifyCallback);
pRemoteCharacteristic->subscribe(true, notifyCallback);
}
connected = true;
return true;
}
/**
* Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
/**
* Called for each advertising BLE server.
*/
/*** Only a reference to the advertised device is passed now
void onResult(BLEAdvertisedDevice advertisedDevice) { **/
void onResult(BLEAdvertisedDevice* advertisedDevice) {
printf("BLE Advertised Device found: %s\n", advertisedDevice->toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
/********************************************************************************
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
********************************************************************************/
if (advertisedDevice->haveServiceUUID() && advertisedDevice->isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
/*******************************************************************
myDevice = new BLEAdvertisedDevice(advertisedDevice);
*******************************************************************/
myDevice = advertisedDevice; /** Just save the reference now, no need to copy the object */
doConnect = true;
doScan = true;
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
// This is the Arduino main loop function.
void connectTask (void * parameter){
for(;;) {
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer()) {
printf("We are now connected to the BLE Server.\n");
} else {
printf("We have failed to connect to the server; there is nothin more we will do.\n");
}
doConnect = false;
}
// If we are connected to a peer BLE Server, update the characteristic each time we are reached
// with the current time since boot.
if (connected) {
char buf[256];
snprintf(buf, 256, "Time since boot: %lu", (unsigned long)(esp_timer_get_time() / 1000000ULL));
printf("Setting new characteristic value to %s\n", buf);
// Set the characteristic's value to be the array of bytes that is actually a string.
/*** Note: write value now returns true if successful, false otherwise - try again or disconnect ***/
pRemoteCharacteristic->writeValue((uint8_t*)buf, strlen(buf), false);
}else if(doScan){
BLEDevice::getScan()->start(0); // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
}
vTaskDelay(1000/portTICK_PERIOD_MS); // Delay a second between loops.
}
vTaskDelete(NULL);
} // End of loop
void app_main(void) {
printf("Starting BLE Client application...\n");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
xTaskCreate(connectTask, "connectTask", 5000, NULL, 1, NULL);
pBLEScan->start(5, false);
} // End of setup.

View File

@ -1,3 +0,0 @@
PROJECT_NAME := BLE_notify
include $(IDF_PATH)/make/project.mk

View File

@ -1,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

@ -1,155 +0,0 @@
/*
Video: https://www.youtube.com/watch?v=oCMOYS71NIU
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
Ported to Arduino ESP32 by Evandro Copercini
updated by chegewara
Refactored back to IDF by H2zero
Create a BLE server that, once we receive a connection, will send periodic notifications.
The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8
The design of creating the BLE server is:
1. Create a BLE Server
2. Create a BLE Service
3. Create a BLE Characteristic on the Service
4. Create a BLE Descriptor on the characteristic
5. Start the service.
6. Start advertising.
A connect hander associated with the server starts a background task that performs notification
every couple of seconds.
*/
/** NimBLE differences highlighted in comment blocks **/
/*******original********
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
***********************/
#include <NimBLEDevice.h>
extern "C" {void app_main(void);}
BLEServer* pServer = NULL;
BLECharacteristic* pCharacteristic = NULL;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint32_t value = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
printf("Server PassKeyRequest\n");
return 123456;
}
bool onConfirmPIN(uint32_t pass_key){
printf("The passkey YES/NO number: %d\n", pass_key);
return true;
}
void onAuthenticationComplete(ble_gap_conn_desc desc){
printf("Starting BLE work!\n");
}
/*******************************************************************/
};
void connectedTask (void * parameter){
for(;;) {
// notify changed value
if (deviceConnected) {
pCharacteristic->setValue((uint8_t*)&value, 4);
pCharacteristic->notify();
value++;
vTaskDelay(100/portTICK_PERIOD_MS); // bluetooth stack will go into congestion, if too many packets are sent
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
vTaskDelay(500/portTICK_PERIOD_MS); // give the bluetooth stack the chance to get things ready
pServer->startAdvertising(); // restart advertising
printf("start advertising\n");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
vTaskDelay(10/portTICK_PERIOD_MS); // Delay between loops to reset watchdog timer
}
vTaskDelete(NULL);
}
void app_main(void) {
// Create the BLE Device
BLEDevice::init("ESP32");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
/******* Enum Type NIMBLE_PROPERTY now *******
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE |
BLECharacteristic::PROPERTY_NOTIFY |
BLECharacteristic::PROPERTY_INDICATE
);
**********************************************/
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE |
NIMBLE_PROPERTY::NOTIFY |
NIMBLE_PROPERTY::INDICATE
);
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
// Create a BLE Descriptor
/***************************************************
NOTE: DO NOT create a 2902 descriptor.
it will be created automatically if notifications
or indications are enabled on a characteristic.
pCharacteristic->addDescriptor(new BLE2902());
****************************************************/
// Start the service
pService->start();
// Start advertising
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(false);
/** This method had been removed **
pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter
**/
xTaskCreate(connectedTask, "connectedTask", 5000, NULL, 1, NULL);
BLEDevice::startAdvertising();
printf("Waiting a client connection to notify...\n");
}

View File

@ -1,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

@ -1,52 +0,0 @@
/*
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp
Ported to Arduino ESP32 by Evandro Copercini
Refactored back to IDF by H2zero
*/
/** NimBLE differences highlighted in comment blocks **/
/*******original********
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
***********************/
#include <NimBLEDevice.h>
extern "C"{void app_main(void);}
int scanTime = 5; //In seconds
BLEScan* pBLEScan;
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice* advertisedDevice) {
printf("Advertised Device: %s \n", advertisedDevice->toString().c_str());
}
};
void scanTask (void * parameter){
for(;;) {
// put your main code here, to run repeatedly:
BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
printf("Devices found: %d\n", foundDevices.getCount());
printf("Scan done!\n");
pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory
vTaskDelay(2000/portTICK_PERIOD_MS); // Delay a second between loops.
}
vTaskDelete(NULL);
}
void app_main(void) {
printf("Scanning...\n");
BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
pBLEScan->setInterval(100);
pBLEScan->setWindow(99); // less or equal setInterval value
xTaskCreate(scanTask, "scanTask", 5000, NULL, 1, NULL);
}

View File

@ -1,7 +0,0 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(SUPPORTED_TARGETS esp32)
project(BLE_server)

View File

@ -1,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

@ -1,57 +0,0 @@
/*
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp
Ported to Arduino ESP32 by Evandro Copercini
updates by chegewara
Refactored back to IDF by H2zero
*/
/** NimBLE differences highlighted in comment blocks **/
/*******original********
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
***********************/
#include <NimBLEDevice.h>
extern "C"{void app_main(void);}
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
void app_main(void) {
printf("Starting BLE work!\n");
BLEDevice::init("Long name works now");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
/***** Enum Type NIMBLE_PROPERTY now *****
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
*****************************************/
NIMBLE_PROPERTY::READ |
NIMBLE_PROPERTY::WRITE
);
pCharacteristic->setValue("Hello World says Neil");
pService->start();
// BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility
BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
/** These methods have been removed **
pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue
pAdvertising->setMinPreferred(0x12);
*/
BLEDevice::startAdvertising();
printf("Characteristic defined! Now you can read it in your phone!\n");
}

View File

@ -1,3 +0,0 @@
PROJECT_NAME := BLE_uart
include $(IDF_PATH)/make/project.mk

View File

@ -1,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

@ -1,167 +0,0 @@
/*
Video: https://www.youtube.com/watch?v=oCMOYS71NIU
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
Ported to Arduino ESP32 by Evandro Copercini
Refactored back to IDF by H2zero
Create a BLE server that, once we receive a connection, will send periodic notifications.
The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E
Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE"
Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with "NOTIFY"
The design of creating the BLE server is:
1. Create a BLE Server
2. Create a BLE Service
3. Create a BLE Characteristic on the Service
4. Create a BLE Descriptor on the characteristic
5. Start the service.
6. Start advertising.
In this example rxValue is the data received (only accessible inside that function).
And txValue is the data to be sent, in this example just a byte incremented every second.
*/
/** NimBLE differences highlighted in comment blocks **/
/*******original********
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
***********************/
#include <NimBLEDevice.h>
extern "C"{void app_main(void);}
BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint8_t txValue = 0;
// See the following for generating UUIDs:
// https://www.uuidgenerator.net/
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
/** None of these are required as they will be handled by the library with defaults. **
** Remove as you see fit for your needs */
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyRequest(){
printf("Server PassKeyRequest\n");
return 123456;
}
bool onConfirmPIN(uint32_t pass_key){
printf("The passkey YES/NO number: %d\n", pass_key);
return true;
}
void onAuthenticationComplete(ble_gap_conn_desc desc){
printf("Starting BLE work!\n");
}
/*******************************************************************/
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string rxValue = pCharacteristic->getValue();
if (rxValue.length() > 0) {
printf("*********\n");
printf("Received Value: ");
for (int i = 0; i < rxValue.length(); i++)
printf("%d", rxValue[i]);
printf("\n*********\n");
}
}
};
void connectedTask (void * parameter){
for(;;) {
if (deviceConnected) {
pTxCharacteristic->setValue(&txValue, 1);
pTxCharacteristic->notify();
txValue++;
}
// disconnecting
if (!deviceConnected && oldDeviceConnected) {
pServer->startAdvertising(); // restart advertising
printf("start advertising\n");
oldDeviceConnected = deviceConnected;
}
// connecting
if (deviceConnected && !oldDeviceConnected) {
// do stuff here on connecting
oldDeviceConnected = deviceConnected;
}
vTaskDelay(10/portTICK_PERIOD_MS); // Delay between loops to reset watchdog timer
}
vTaskDelete(NULL);
}
void app_main(void) {
// Create the BLE Device
BLEDevice::init("UART Service");
// Create the BLE Server
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());
// Create the BLE Service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Create a BLE Characteristic
pTxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_TX,
/******* Enum Type NIMBLE_PROPERTY now *******
BLECharacteristic::PROPERTY_NOTIFY
);
**********************************************/
NIMBLE_PROPERTY::NOTIFY
);
/***************************************************
NOTE: DO NOT create a 2902 descriptor
it will be created automatically if notifications
or indications are enabled on a characteristic.
pCharacteristic->addDescriptor(new BLE2902());
****************************************************/
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID_RX,
/******* Enum Type NIMBLE_PROPERTY now *******
BLECharacteristic::PROPERTY_WRITE
);
*********************************************/
NIMBLE_PROPERTY::WRITE
);
pRxCharacteristic->setCallbacks(new MyCallbacks());
// Start the service
pService->start();
xTaskCreate(connectedTask, "connectedTask", 5000, NULL, 1, NULL);
// Start advertising
pServer->getAdvertising()->start();
printf("Waiting a client connection to notify...\n");
}

25
idf_component.yml Normal file
View File

@ -0,0 +1,25 @@
## IDF Component Manager Manifest File
version: "2.3.1"
license: "Apache-2.0"
description: "C++ wrapper for the NimBLE BLE stack"
url: "https://github.com/h2zero/esp-nimble-cpp"
repository: "https://github.com/h2zero/esp-nimble-cpp"
maintainers:
- Ryan Powell <ryan@nable-embedded.io>
documentation: "https://h2zero.github.io/esp-nimble-cpp/"
tags:
- BLE
- NimBLE
dependencies:
espressif/esp_hosted:
version: "*"
rules:
- if: "target in [esp32p4]"
espressif/esp_wifi_remote:
version: ">=0.5.3"
rules:
- if: "target in [esp32p4]"
idf:
version: ">=5.3.0"
rules:
- if: "target in [esp32p4]"

23
library.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "esp-nimble-cpp",
"version": "2.3.1",
"description": "C++ wrapper for the NimBLE BLE stack",
"keywords": [
"BLE",
"espidf",
"espressif",
"esp32",
"nimble"
],
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/h2zero/esp-nimble-cpp"
},
"authors": {
"name": "Ryan Powell",
"email": "ryan@nable-embedded.io",
"url": "https://github.com/h2zero/esp-nimble-cpp",
"maintainer": true
}
}

View File

@ -1,316 +0,0 @@
/*
* FreeRTOS.cpp
*
* Created on: Feb 24, 2017
* Author: kolban
*/
#include "sdkconfig.h"
#include "FreeRTOS.h"
#include "NimBLELog.h"
#include <freertos/FreeRTOS.h> // Include the base FreeRTOS definitions
#include <freertos/task.h> // Include the task definitions
#include <freertos/semphr.h> // Include the semaphore definitions
#include <string>
static const char* LOG_TAG = "FreeRTOS";
/**
* Sleep for the specified number of milliseconds.
* @param[in] ms The period in milliseconds for which to sleep.
*/
void FreeRTOS::sleep(uint32_t ms) {
::vTaskDelay(ms / portTICK_PERIOD_MS);
} // sleep
/**
* Start a new task.
* @param[in] task The function pointer to the function to be run in the task.
* @param[in] taskName A string identifier for the task.
* @param[in] param An optional parameter to be passed to the started task.
* @param[in] stackSize An optional paremeter supplying the size of the stack in which to run the task.
*/
void FreeRTOS::startTask(void task(void*), std::string taskName, void* param, uint32_t stackSize) {
::xTaskCreate(task, taskName.data(), stackSize, param, 5, NULL);
} // startTask
/**
* Delete the task.
* @param[in] pTask An optional handle to the task to be deleted. If not supplied the calling task will be deleted.
*/
void FreeRTOS::deleteTask(TaskHandle_t pTask) {
::vTaskDelete(pTask);
} // deleteTask
/**
* Get the time in milliseconds since the %FreeRTOS scheduler started.
* @return The time in milliseconds since the %FreeRTOS scheduler started.
*/
uint32_t FreeRTOS::getTimeSinceStart() {
return (uint32_t) (xTaskGetTickCount() * portTICK_PERIOD_MS);
} // getTimeSinceStart
/**
* @brief Wait for a semaphore to be released by trying to take it and
* then releasing it again.
* @param [in] owner A debug tag.
* @return The value associated with the semaphore.
*/
uint32_t FreeRTOS::Semaphore::wait(std::string owner) {
NIMBLE_LOGD(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);
}
NIMBLE_LOGD(LOG_TAG, "<< wait: Semaphore released: %s", toString().c_str());
return m_value;
} // wait
/**
* @brief Wait for a semaphore to be released in a given period of time by trying to take it and
* then releasing it again. The value associated with the semaphore can be taken by value() call after return
* @param [in] owner A debug tag.
* @param [in] timeoutMs timeout to wait in ms.
* @return True if we took the semaphore within timeframe.
*/
bool FreeRTOS::Semaphore::timedWait(std::string owner, uint32_t timeoutMs) {
NIMBLE_LOGD(LOG_TAG, ">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str());
if (m_usePthreads && timeoutMs != portMAX_DELAY) {
assert(false); // We apparently don't have a timed wait for pthreads.
}
auto ret = pdTRUE;
if (m_usePthreads) {
pthread_mutex_lock(&m_pthread_mutex);
} else {
ret = xSemaphoreTake(m_semaphore, timeoutMs);
}
if (m_usePthreads) {
pthread_mutex_unlock(&m_pthread_mutex);
} else {
xSemaphoreGive(m_semaphore);
}
NIMBLE_LOGD(LOG_TAG, "<< wait: Semaphore %s released: %d", toString().c_str(), ret);
return ret;
} // wait
/**
* @brief Construct a semaphore, the semaphore is given when created.
* @param [in] name A name string to provide debugging support.
*/
FreeRTOS::Semaphore::Semaphore(std::string name) {
m_usePthreads = false; // Are we using pThreads or FreeRTOS?
if (m_usePthreads) {
pthread_mutex_init(&m_pthread_mutex, nullptr);
} else {
//m_semaphore = xSemaphoreCreateMutex();
m_semaphore = xSemaphoreCreateBinary();
xSemaphoreGive(m_semaphore);
}
m_name = name;
m_owner = std::string("<N/A>");
m_value = 0;
}
FreeRTOS::Semaphore::~Semaphore() {
if (m_usePthreads) {
pthread_mutex_destroy(&m_pthread_mutex);
} else {
vSemaphoreDelete(m_semaphore);
}
}
/**
* @brief Give the semaphore.
*/
void FreeRTOS::Semaphore::give() {
NIMBLE_LOGD(LOG_TAG, "Semaphore giving: %s", toString().c_str());
m_owner = std::string("<N/A>");
if (m_usePthreads) {
pthread_mutex_unlock(&m_pthread_mutex);
} else {
xSemaphoreGive(m_semaphore);
}
// #ifdef ARDUINO_ARCH_ESP32
// FreeRTOS::sleep(10);
// #endif
} // Semaphore::give
/**
* @brief Give a semaphore.
* The Semaphore is given with an associated value.
* @param [in] value The value to associate with the semaphore.
*/
void FreeRTOS::Semaphore::give(uint32_t value) {
m_value = value;
give();
} // give
/**
* @brief Give a semaphore from an ISR.
*/
void FreeRTOS::Semaphore::giveFromISR() {
BaseType_t higherPriorityTaskWoken;
if (m_usePthreads) {
assert(false);
} else {
xSemaphoreGiveFromISR(m_semaphore, &higherPriorityTaskWoken);
}
} // giveFromISR
/**
* @brief Take a semaphore.
* Take a semaphore and wait indefinitely.
* @param [in] owner The new owner (for debugging)
* @return True if we took the semaphore.
*/
bool FreeRTOS::Semaphore::take(std::string owner) {
NIMBLE_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);
} else {
rc = ::xSemaphoreTake(m_semaphore, portMAX_DELAY) == pdTRUE;
}
m_owner = owner;
if (rc) {
NIMBLE_LOGD(LOG_TAG, "Semaphore taken: %s", toString().c_str());
} else {
NIMBLE_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str());
}
return rc;
} // Semaphore::take
/**
* @brief Take a semaphore.
* Take a semaphore but return if we haven't obtained it in the given period of milliseconds.
* @param [in] timeoutMs Timeout in milliseconds.
* @param [in] owner The new owner (for debugging)
* @return True if we took the semaphore.
*/
bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) {
NIMBLE_LOGD(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.
} else {
rc = ::xSemaphoreTake(m_semaphore, timeoutMs / portTICK_PERIOD_MS) == pdTRUE;
}
m_owner = owner;
if (rc) {
NIMBLE_LOGD(LOG_TAG, "Semaphore taken: %s", toString().c_str());
} else {
NIMBLE_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str());
}
return rc;
} // Semaphore::take
/**
* @brief Create a string representation of the semaphore.
* @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;
} // toString
/**
* @brief Set the name of the semaphore.
* @param [in] name The name of the semaphore.
*/
void FreeRTOS::Semaphore::setName(std::string name) {
m_name = name;
} // setName
/**
* @brief Create a ring buffer.
* @param [in] length The amount of storage to allocate for the ring buffer.
* @param [in] type The type of buffer. One of RINGBUF_TYPE_NOSPLIT, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF.
*/
#ifdef ESP_IDF_VERSION //Quick hack to detect if using IDF version that replaced ringbuf_type_t
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
Ringbuffer::Ringbuffer(size_t length, RingbufferType_t type) {
#else
Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) {
#endif
#else
Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) {
#endif
m_handle = ::xRingbufferCreate(length, type);
} // Ringbuffer
Ringbuffer::~Ringbuffer() {
::vRingbufferDelete(m_handle);
} // ~Ringbuffer
/**
* @brief Receive data from the buffer.
* @param [out] size On return, the size of data returned.
* @param [in] wait How long to wait.
* @return A pointer to the storage retrieved.
*/
void* Ringbuffer::receive(size_t* size, TickType_t wait) {
return ::xRingbufferReceive(m_handle, size, wait);
} // receive
/**
* @brief Return an item.
* @param [in] item The item to be returned/released.
*/
void Ringbuffer::returnItem(void* item) {
::vRingbufferReturnItem(m_handle, item);
} // returnItem
/**
* @brief Send data to the buffer.
* @param [in] data The data to place into the buffer.
* @param [in] length The length of data to place into the buffer.
* @param [in] wait How long to wait before giving up. The default is to wait indefinitely.
* @return
*/
bool Ringbuffer::send(void* data, size_t length, TickType_t wait) {
return ::xRingbufferSend(m_handle, data, length, wait) == pdTRUE;
} // send

View File

@ -1,89 +0,0 @@
/*
* FreeRTOS.h
*
* Created on: Feb 24, 2017
* Author: kolban
*/
#ifndef MAIN_FREERTOS_H_
#define MAIN_FREERTOS_H_
#include <freertos/FreeRTOS.h> // Include the base FreeRTOS definitions.
#include <freertos/task.h> // Include the task definitions.
#include <freertos/semphr.h> // Include the semaphore definitions.
#include <freertos/ringbuf.h> // Include the ringbuffer definitions.
#include <stdint.h>
#include <string>
#include <pthread.h>
/**
* @brief Interface to %FreeRTOS functions.
*/
class FreeRTOS {
public:
static void sleep(uint32_t ms);
static void startTask(void task(void*), std::string taskName, void* param = nullptr, uint32_t stackSize = 2048);
static void deleteTask(TaskHandle_t pTask = nullptr);
static uint32_t getTimeSinceStart();
/**
* @brief A binary semaphore class that operates like a mutex, it is already given when constructed.
*/
class Semaphore {
public:
Semaphore(std::string owner = "<Unknown>");
~Semaphore();
void give();
void give(uint32_t value);
void giveFromISR();
void setName(std::string name);
bool take(std::string owner = "<Unknown>");
bool take(uint32_t timeoutMs, std::string owner = "<Unknown>");
std::string toString();
bool timedWait(std::string owner = "<Unknown>", uint32_t timeoutMs = portMAX_DELAY);
uint32_t wait(std::string owner = "<Unknown>");
/**
* @brief Get the value of the semaphore.
* @return The value stored if the semaphore was given with give(value);
*/
uint32_t value(){ return m_value; };
private:
SemaphoreHandle_t m_semaphore;
pthread_mutex_t m_pthread_mutex;
std::string m_name;
std::string m_owner;
uint32_t m_value;
bool m_usePthreads;
};
};
/**
* @brief A wrapper class for a freeRTOS ringbuffer.
*/
class Ringbuffer {
public:
#ifdef ESP_IDF_VERSION //Quick hack to detect if using IDF version that replaced ringbuf_type_t
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0)
Ringbuffer(size_t length, RingbufferType_t type = RINGBUF_TYPE_NOSPLIT);
#else
Ringbuffer(size_t length, ringbuf_type_t type = RINGBUF_TYPE_NOSPLIT);
#endif
#else
Ringbuffer(size_t length, ringbuf_type_t type = RINGBUF_TYPE_NOSPLIT);
#endif
~Ringbuffer();
void* receive(size_t* size, TickType_t wait = portMAX_DELAY);
void returnItem(void* item);
bool send(void* data, size_t length, TickType_t wait = portMAX_DELAY);
private:
RingbufHandle_t m_handle;
};
#endif /* MAIN_FREERTOS_H_ */

View File

@ -25,9 +25,9 @@
#define HID_VERSION_1_11 (0x0111)
/* HID Class */
#define HID_CLASS (3)
#define HID_SUBCLASS_NONE (0)
#define HID_PROTOCOL_NONE (0)
#define BLE_HID_CLASS (3)
#define BLE_HID_SUBCLASS_NONE (0)
#define BLE_HID_PROTOCOL_NONE (0)
/* Descriptors */
#define HID_DESCRIPTOR (33)
@ -45,13 +45,8 @@
/* of data as per HID Class standard */
/* Main items */
#ifdef ARDUINO_ARCH_ESP32
#define HIDINPUT(size) (0x80 | size)
#define HIDOUTPUT(size) (0x90 | size)
#else
#define INPUT(size) (0x80 | size)
#define OUTPUT(size) (0x90 | size)
#endif
#define HIDINPUT(size) (0x80 | size)
#define HIDOUTPUT(size) (0x90 | size)
#define FEATURE(size) (0xb0 | size)
#define COLLECTION(size) (0xa0 | size)
#define END_COLLECTION(size) (0xc0 | size)

View File

@ -1,90 +1,72 @@
/*
* NimBLE2904.cpp
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on March 13, 2020
* Author H2zero
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Originally:
* http://www.apache.org/licenses/LICENSE-2.0
*
* BLE2904.cpp
*
* Created on: Dec 23, 2017
* Author: kolban
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* See also:
* https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include "nimconfig.h"
#if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#include "NimBLE2904.h"
#if CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL
NimBLE2904::NimBLE2904(NimBLECharacteristic* pCharacterisitic)
: NimBLEDescriptor(NimBLEUUID((uint16_t) 0x2904),
BLE_GATT_CHR_F_READ,
sizeof(BLE2904_Data),
pCharacterisitic)
{
m_data.m_format = 0;
m_data.m_exponent = 0;
m_data.m_namespace = 1; // 1 = Bluetooth SIG Assigned Numbers
m_data.m_unit = 0;
m_data.m_description = 0;
setValue((uint8_t*) &m_data, sizeof(m_data));
} // BLE2904
NimBLE2904::NimBLE2904(NimBLECharacteristic* pChr)
: NimBLEDescriptor(NimBLEUUID((uint16_t)0x2904), BLE_GATT_CHR_F_READ, sizeof(NimBLE2904Data), pChr) {
setValue(m_data);
} // NimBLE2904
/**
* @brief Set the description.
* @param [in] description The description value to set.
*/
void NimBLE2904::setDescription(uint16_t description) {
m_data.m_description = description;
setValue((uint8_t*) &m_data, sizeof(m_data));
}
setValue(m_data);
} // setDescription
/**
* @brief Set the exponent.
* @param [in] exponent The exponent value to set.
*/
void NimBLE2904::setExponent(int8_t exponent) {
m_data.m_exponent = exponent;
setValue((uint8_t*) &m_data, sizeof(m_data));
setValue(m_data);
} // setExponent
/**
* @brief Set the format.
* @param [in] format The format value to set.
*/
void NimBLE2904::setFormat(uint8_t format) {
m_data.m_format = format;
setValue((uint8_t*) &m_data, sizeof(m_data));
setValue(m_data);
} // setFormat
/**
* @brief Set the namespace.
* @param [in] namespace_value The namespace value toset.
*/
void NimBLE2904::setNamespace(uint8_t namespace_value) {
m_data.m_namespace = namespace_value;
setValue((uint8_t*) &m_data, sizeof(m_data));
setValue(m_data);
} // setNamespace
/**
* @brief Set the units for this value. It should be one of the encoded values defined here:
* https://www.bluetooth.com/specifications/assigned-numbers/units
* @brief Set the units for this value.
* @param [in] unit The type of units of this characteristic as defined by assigned numbers.
* @details See https://www.bluetooth.com/specifications/assigned-numbers/units
*/
void NimBLE2904::setUnit(uint16_t unit) {
m_data.m_unit = unit;
setValue((uint8_t*) &m_data, sizeof(m_data));
setValue(m_data);
} // setUnit
#endif // #if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#endif
#endif // CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL

View File

@ -1,48 +1,44 @@
/*
* NimBLE2904.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on March 13, 2020
* Author H2zero
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Originally:
* http://www.apache.org/licenses/LICENSE-2.0
*
* BLE2904.h
*
* Created on: Dec 23, 2017
* Author: kolban
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MAIN_NIMBLE2904_H_
#define MAIN_NIMBLE2904_H_
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#ifndef NIMBLE_CPP_2904_H_
#define NIMBLE_CPP_2904_H_
#include "nimconfig.h"
#if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#if CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL
#include "NimBLEDescriptor.h"
struct BLE2904_Data {
uint8_t m_format;
int8_t m_exponent;
uint16_t m_unit; // See https://www.bluetooth.com/specifications/assigned-numbers/units
uint8_t m_namespace;
uint16_t m_description;
# include "NimBLEDescriptor.h"
struct NimBLE2904Data {
uint8_t m_format{0};
int8_t m_exponent{0};
uint16_t m_unit{0x2700}; // Unitless; See https://www.bluetooth.com/specifications/assigned-numbers/units
uint8_t m_namespace{1}; // 1 = Bluetooth SIG Assigned Numbers
uint16_t m_description{0}; // unknown description
} __attribute__((packed));
/**
* @brief Descriptor for Characteristic Presentation Format.
*
* This is a convenience descriptor for the Characteristic Presentation Format which has a UUID of 0x2904.
*
* See also:
* https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml
*/
class NimBLE2904: public NimBLEDescriptor {
public:
NimBLE2904(NimBLECharacteristic* pCharacterisitic = nullptr);
class NimBLE2904 : public NimBLEDescriptor {
public:
NimBLE2904(NimBLECharacteristic* pChr = nullptr);
static const uint8_t FORMAT_BOOLEAN = 1;
static const uint8_t FORMAT_UINT2 = 2;
static const uint8_t FORMAT_UINT4 = 3;
@ -70,18 +66,18 @@ public:
static const uint8_t FORMAT_UTF8 = 25;
static const uint8_t FORMAT_UTF16 = 26;
static const uint8_t FORMAT_OPAQUE = 27;
static const uint8_t FORMAT_MEDASN1 = 28;
void setDescription(uint16_t);
void setDescription(uint16_t description);
void setExponent(int8_t exponent);
void setFormat(uint8_t format);
void setNamespace(uint8_t namespace_value);
void setUnit(uint16_t unit);
private:
private:
friend class NimBLECharacteristic;
BLE2904_Data m_data;
}; // BLE2904
NimBLE2904Data m_data{};
}; // NimBLE2904
#endif // #if defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#endif /* CONFIG_BT_ENABLED */
#endif /* MAIN_NIMBLE2904_H_ */
#endif // CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL
#endif // NIMBLE_CPP_2904_H_

View File

@ -1,152 +1,185 @@
/*
* NimBLEAddress.cpp
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on Jan 24 2020
* Author H2zero
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Originally:
* http://www.apache.org/licenses/LICENSE-2.0
*
* BLEAddress.cpp
*
* Created on: Jul 2, 2017
* Author: kolban
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include <algorithm>
#include "NimBLEAddress.h"
#include "NimBLEUtils.h"
#include "NimBLELog.h"
#if CONFIG_BT_ENABLED
# include "NimBLELog.h"
# include <algorithm>
# ifdef CONFIG_NIMBLE_CPP_ADDR_FMT_EXCLUDE_DELIMITER
# define NIMBLE_CPP_ADDR_DELIMITER ""
# else
# define NIMBLE_CPP_ADDR_DELIMITER ":"
# endif
# ifdef CONFIG_NIMBLE_CPP_ADDR_FMT_UPPERCASE
# define NIMBLE_CPP_ADDR_FMT "%02X%s%02X%s%02X%s%02X%s%02X%s%02X"
# else
# define NIMBLE_CPP_ADDR_FMT "%02x%s%02x%s%02x%s%02x%s%02x%s%02x"
# endif
static const char* LOG_TAG = "NimBLEAddress";
/*************************************************
* NOTE: NimBLE address bytes are in INVERSE ORDER!
* We will accomodate that fact in these methods.
*************************************************/
* We will accommodate that fact in these methods.
*************************************************/
/**
* @brief Create an address from the native NimBLE representation.
* @param [in] address The native NimBLE address.
*/
NimBLEAddress::NimBLEAddress(ble_addr_t address) {
memcpy(m_address, address.val, 6);
m_addrType = address.type;
} // NimBLEAddress
NimBLEAddress::NimBLEAddress(ble_addr_t address) : ble_addr_t{address} {}
/**
* @brief Create a blank address, i.e. 00:00:00:00:00:00, type 0.
*/
NimBLEAddress::NimBLEAddress() {
NimBLEAddress("");
} // NimBLEAddress
/**
* @brief Create an address from a hex string
* @brief Create an address from a hex string.
*
* A hex string is of the format:
* ```
* 00:00:00:00:00:00
* ```
* which is 17 characters in length.
*
* @param [in] stringAddress The hex string representation of the address.
* @param [in] type The type of the address.
* @param [in] addr The hex string representation of the address.
* @param [in] type The type of the address, should be one of:
* * BLE_ADDR_PUBLIC (0)
* * BLE_ADDR_RANDOM (1)
*/
NimBLEAddress::NimBLEAddress(const std::string &stringAddress, uint8_t type) {
m_addrType = type;
NimBLEAddress::NimBLEAddress(const std::string& addr, uint8_t type) {
this->type = type;
if (stringAddress.length() == 0) {
memset(m_address, 0, 6);
if (addr.length() == BLE_DEV_ADDR_LEN) {
std::reverse_copy(addr.data(), addr.data() + BLE_DEV_ADDR_LEN, this->val);
return;
}
if (stringAddress.length() == 6) {
std::reverse_copy(stringAddress.data(), stringAddress.data() + 6, m_address);
if (addr.length() == 17) {
std::string mac{addr};
mac.erase(std::remove(mac.begin(), mac.end(), ':'), mac.end());
uint64_t address = std::stoull(mac, nullptr, 16);
memcpy(this->val, &address, sizeof(this->val));
return;
}
if (stringAddress.length() != 17) {
memset(m_address, 0, sizeof m_address); // "00:00:00:00:00:00" represents an invalid address
NIMBLE_LOGD(LOG_TAG, "Invalid address '%s'", stringAddress.c_str());
return;
}
int data[6];
if(sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[5], &data[4], &data[3], &data[2], &data[1], &data[0]) != 6) {
memset(m_address, 0, sizeof m_address); // "00:00:00:00:00:00" represents an invalid address
NIMBLE_LOGD(LOG_TAG, "Invalid address '%s'", stringAddress.c_str());
}
for(size_t index = 0; index < sizeof m_address; index++) {
m_address[index] = data[index];
}
*this = NimBLEAddress{};
NIMBLE_LOGE(LOG_TAG, "Invalid address '%s'", addr.c_str());
} // NimBLEAddress
/**
* @brief Constructor for compatibility with bluedroid esp library using native ESP representation.
* @param [in] address A uint8_t[6] or esp_bd_addr_t containing the address.
* @param [in] type The type of the address.
* @param [in] type The type of the address should be one of:
* * BLE_ADDR_PUBLIC (0)
* * BLE_ADDR_RANDOM (1)
*/
NimBLEAddress::NimBLEAddress(uint8_t address[6], uint8_t type) {
std::reverse_copy(address, address + sizeof m_address, m_address);
m_addrType = type;
NimBLEAddress::NimBLEAddress(const uint8_t address[BLE_DEV_ADDR_LEN], uint8_t type) {
std::reverse_copy(address, address + BLE_DEV_ADDR_LEN, this->val);
this->type = type;
} // NimBLEAddress
/**
* @brief Constructor for address using a hex value.\n
* Use the same byte order, so use 0xa4c1385def16 for "a4:c1:38:5d:ef:16"
* @param [in] address uint64_t containing the address.
* @param [in] type The type of the address.
* @param [in] type The type of the address should be one of:
* * BLE_ADDR_PUBLIC (0)
* * BLE_ADDR_RANDOM (1)
*/
NimBLEAddress::NimBLEAddress(const uint64_t &address, uint8_t type) {
memcpy(m_address, &address, sizeof m_address);
m_addrType = type;
NimBLEAddress::NimBLEAddress(const uint64_t& address, uint8_t type) {
memcpy(this->val, &address, sizeof(this->val));
this->type = type;
} // NimBLEAddress
/**
* @brief Determine if this address equals another.
* @param [in] otherAddress The other address to compare against.
* @return True if the addresses are equal.
*/
bool NimBLEAddress::equals(const NimBLEAddress &otherAddress) const {
bool NimBLEAddress::equals(const NimBLEAddress& otherAddress) const {
return *this == otherAddress;
} // equals
/**
* @brief Get the native representation of the address.
* @return a pointer to the uint8_t[6] array of the address.
* @brief Get the NimBLE base struct of the address.
* @return A read only reference to the NimBLE base struct of the address.
*/
const uint8_t *NimBLEAddress::getNative() const {
return m_address;
} // getNative
const ble_addr_t* NimBLEAddress::getBase() const {
return reinterpret_cast<const ble_addr_t*>(this);
} // getBase
/**
* @brief Get the address type.
* @return The address type.
*/
uint8_t NimBLEAddress::getType() const {
return m_addrType;
return this->type;
} // getType
/**
* @brief Get the address value.
* @return A read only reference to the address value.
*/
const uint8_t* NimBLEAddress::getVal() const {
return this->val;
} // getVal
/**
* @brief Determine if this address is a Resolvable Private Address.
* @return True if the address is a RPA.
*/
bool NimBLEAddress::isRpa() const {
return BLE_ADDR_IS_RPA(this);
} // isRpa
/**
* @brief Determine if this address is a Non-Resolvable Private Address.
* @return True if the address is a NRPA.
*/
bool NimBLEAddress::isNrpa() const {
return BLE_ADDR_IS_NRPA(this);
} // isNrpa
/**
* @brief Determine if this address is a Static Address.
* @return True if the address is a Static Address.
*/
bool NimBLEAddress::isStatic() const {
return BLE_ADDR_IS_STATIC(this);
} // isStatic
/**
* @brief Determine if this address is a Public Address.
* @return True if the address is a Public Address.
*/
bool NimBLEAddress::isPublic() const {
return this->type == BLE_ADDR_PUBLIC;
} // isPublic
/**
* @brief Determine if this address is a NULL Address.
* @return True if the address is a NULL Address.
*/
bool NimBLEAddress::isNull() const {
return *this == NimBLEAddress{};
} // isNull
/**
* @brief Convert a BLE address to a string.
*
* A string representation of an address is in the format:
*
* ```
* xx:xx:xx:xx:xx:xx
* ```
*
* @return The string representation of the address.
* @deprecated Use std::string() operator instead.
*/
@ -154,43 +187,62 @@ std::string NimBLEAddress::toString() const {
return std::string(*this);
} // toString
/**
* @brief Reverse the byte order of the address.
* @return A reference to this address.
*/
const NimBLEAddress& NimBLEAddress::reverseByteOrder() {
std::reverse(this->val, this->val + BLE_DEV_ADDR_LEN);
return *this;
} // reverseByteOrder
/**
* @brief Convienience operator to check if this address is equal to another.
* @brief Convenience operator to check if this address is equal to another.
*/
bool NimBLEAddress::operator ==(const NimBLEAddress & rhs) const {
return memcmp(rhs.m_address, m_address, sizeof m_address) == 0;
bool NimBLEAddress::operator==(const NimBLEAddress& rhs) const {
if (this->type != rhs.type) {
return false;
}
return memcmp(rhs.val, this->val, sizeof(this->val)) == 0;
} // operator ==
/**
* @brief Convienience operator to check if this address is not equal to another.
* @brief Convenience operator to check if this address is not equal to another.
*/
bool NimBLEAddress::operator !=(const NimBLEAddress & rhs) const {
bool NimBLEAddress::operator!=(const NimBLEAddress& rhs) const {
return !this->operator==(rhs);
} // operator !=
/**
* @brief Convienience operator to convert this address to string representation.
* @details This allows passing NimBLEAddress to functions
* that accept std::string and/or or it's methods as a parameter.
* @brief Convenience operator to convert this address to string representation.
* @details This allows passing NimBLEAddress to functions that accept std::string and/or it's methods as a parameter.
*/
NimBLEAddress::operator std::string() const {
char buffer[18];
snprintf(buffer, sizeof(buffer), "%02x:%02x:%02x:%02x:%02x:%02x",
m_address[5], m_address[4], m_address[3],
m_address[2], m_address[1], m_address[0]);
return std::string(buffer);
snprintf(buffer,
sizeof(buffer),
NIMBLE_CPP_ADDR_FMT,
this->val[5],
NIMBLE_CPP_ADDR_DELIMITER,
this->val[4],
NIMBLE_CPP_ADDR_DELIMITER,
this->val[3],
NIMBLE_CPP_ADDR_DELIMITER,
this->val[2],
NIMBLE_CPP_ADDR_DELIMITER,
this->val[1],
NIMBLE_CPP_ADDR_DELIMITER,
this->val[0]);
return std::string{buffer};
} // operator std::string
/**
* @brief Convienience operator to convert the native address representation to uint_64.
* @brief Convenience operator to convert the native address representation to uint_64.
*/
NimBLEAddress::operator uint64_t() const {
uint64_t address = 0;
memcpy(&address, m_address, sizeof m_address);
memcpy(&address, this->val, sizeof(this->val));
return address;
} // operator uint64_t

View File

@ -1,57 +1,71 @@
/*
* NimBLEAddress.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on Jan 24 2020
* Author H2zero
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Originally:
* http://www.apache.org/licenses/LICENSE-2.0
*
* BLEAddress.h
*
* Created on: Jul 2, 2017
* Author: kolban
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMPONENTS_NIMBLEADDRESS_H_
#define COMPONENTS_NIMBLEADDRESS_H_
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#ifndef NIMBLE_CPP_ADDRESS_H_
#define NIMBLE_CPP_ADDRESS_H_
#include "nimconfig.h"
#if CONFIG_BT_ENABLED
# if defined(CONFIG_NIMBLE_CPP_IDF)
# include "nimble/ble.h"
# else
# include "nimble/nimble/include/nimble/ble.h"
# endif
#include "nimble/ble.h"
/**** FIX COMPILATION ****/
#undef min
#undef max
# undef min
# undef max
/**************************/
#include <string>
#include <algorithm>
# include <string>
/**
* @brief A %BLE device address.
* @brief A BLE device address.
*
* Every %BLE device has a unique address which can be used to identify it and form connections.
* Every BLE device has a unique address which can be used to identify it and form connections.
*/
class NimBLEAddress {
public:
NimBLEAddress();
NimBLEAddress(ble_addr_t address);
NimBLEAddress(uint8_t address[6], uint8_t type = BLE_ADDR_PUBLIC);
NimBLEAddress(const std::string &stringAddress, uint8_t type = BLE_ADDR_PUBLIC);
NimBLEAddress(const uint64_t &address, uint8_t type = BLE_ADDR_PUBLIC);
bool equals(const NimBLEAddress &otherAddress) const;
const uint8_t* getNative() const;
std::string toString() const;
uint8_t getType() const;
class NimBLEAddress : private ble_addr_t {
public:
/**
* @brief Create a blank address, i.e. 00:00:00:00:00:00, type 0.
*/
NimBLEAddress() = default;
NimBLEAddress(const ble_addr_t address);
NimBLEAddress(const uint8_t address[BLE_DEV_ADDR_LEN], uint8_t type);
NimBLEAddress(const std::string& stringAddress, uint8_t type);
NimBLEAddress(const uint64_t& address, uint8_t type);
bool operator ==(const NimBLEAddress & rhs) const;
bool operator !=(const NimBLEAddress & rhs) const;
operator std::string() const;
operator uint64_t() const;
private:
uint8_t m_address[6];
uint8_t m_addrType;
bool isRpa() const;
bool isNrpa() const;
bool isStatic() const;
bool isPublic() const;
bool isNull() const;
bool equals(const NimBLEAddress& otherAddress) const;
const ble_addr_t* getBase() const;
std::string toString() const;
uint8_t getType() const;
const uint8_t* getVal() const;
const NimBLEAddress& reverseByteOrder();
bool operator==(const NimBLEAddress& rhs) const;
bool operator!=(const NimBLEAddress& rhs) const;
operator std::string() const;
operator uint64_t() const;
};
#endif /* CONFIG_BT_ENABLED */
#endif /* COMPONENTS_NIMBLEADDRESS_H_ */
#endif // CONFIG_BT_ENABLED
#endif // NIMBLE_CPP_ADDRESS_H_

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,39 @@
/*
* NimBLEAdvertisedDevice.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on Jan 24 2020
* Author H2zero
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* Originally:
* http://www.apache.org/licenses/LICENSE-2.0
*
* BLEAdvertisedDevice.h
*
* Created on: Jul 3, 2017
* Author: kolban
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMPONENTS_NIMBLEADVERTISEDDEVICE_H_
#define COMPONENTS_NIMBLEADVERTISEDDEVICE_H_
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#ifndef NIMBLE_CPP_ADVERTISED_DEVICE_H_
#define NIMBLE_CPP_ADVERTISED_DEVICE_H_
#include "nimconfig.h"
#if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
#if CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_OBSERVER
#include "NimBLEAddress.h"
#include "NimBLEScan.h"
#include "NimBLEUUID.h"
# include "NimBLEAddress.h"
# include "NimBLEScan.h"
# include "NimBLEUUID.h"
#include "host/ble_hs_adv.h"
#include <map>
#include <vector>
# if defined(CONFIG_NIMBLE_CPP_IDF)
# include "host/ble_hs_adv.h"
# include "host/ble_gap.h"
# else
# include "nimble/nimble/host/include/host/ble_hs_adv.h"
# include "nimble/nimble/host/include/host/ble_gap.h"
# endif
# include <vector>
class NimBLEScan;
/**
@ -38,17 +43,61 @@ class NimBLEScan;
* class provides a model of a detected device.
*/
class NimBLEAdvertisedDevice {
public:
NimBLEAdvertisedDevice();
public:
NimBLEAdvertisedDevice() = default;
NimBLEAddress getAddress();
uint8_t getAdvType();
uint16_t getAppearance();
uint16_t getAdvInterval();
uint16_t getMinInterval();
uint16_t getMaxInterval();
std::string getManufacturerData();
std::string getURI();
uint8_t getAdvType() const;
uint8_t getAdvFlags() const;
uint16_t getAppearance() const;
uint16_t getAdvInterval() const;
uint16_t getMinInterval() const;
uint16_t getMaxInterval() const;
uint8_t getManufacturerDataCount() const;
const NimBLEAddress& getAddress() const;
std::string getManufacturerData(uint8_t index = 0) const;
std::string getURI() const;
std::string getPayloadByType(uint16_t type, uint8_t index = 0) const;
std::string getName() const;
int8_t getRSSI() const;
NimBLEScan* getScan() const;
uint8_t getServiceDataCount() const;
std::string getServiceData(uint8_t index = 0) const;
std::string getServiceData(const NimBLEUUID& uuid) const;
NimBLEUUID getServiceDataUUID(uint8_t index = 0) const;
NimBLEUUID getServiceUUID(uint8_t index = 0) const;
uint8_t getServiceUUIDCount() const;
NimBLEAddress getTargetAddress(uint8_t index = 0) const;
uint8_t getTargetAddressCount() const;
int8_t getTXPower() const;
uint8_t getAdvLength() const;
uint8_t getAddressType() const;
bool isAdvertisingService(const NimBLEUUID& uuid) const;
bool haveAppearance() const;
bool haveManufacturerData() const;
bool haveName() const;
bool haveServiceData() const;
bool haveServiceUUID() const;
bool haveTXPower() const;
bool haveConnParams() const;
bool haveAdvInterval() const;
bool haveTargetAddress() const;
bool haveURI() const;
bool haveType(uint16_t type) const;
std::string toString() const;
bool isConnectable() const;
bool isScannable() const;
bool isLegacyAdvertisement() const;
# if CONFIG_BT_NIMBLE_EXT_ADV
uint8_t getSetId() const;
uint8_t getPrimaryPhy() const;
uint8_t getSecondaryPhy() const;
uint16_t getPeriodicInterval() const;
# endif
operator NimBLEAddress() const;
const std::vector<uint8_t>& getPayload() const;
const std::vector<uint8_t>::const_iterator begin() const;
const std::vector<uint8_t>::const_iterator end() const;
/**
* @brief A template to convert the service data to <type\>.
@ -58,21 +107,14 @@ public:
* less than <tt>sizeof(<type\>)</tt>.
* @details <b>Use:</b> <tt>getManufacturerData<type>(skipSizeCheck);</tt>
*/
template<typename T>
T getManufacturerData(bool skipSizeCheck = false) {
template <typename T>
T getManufacturerData(bool skipSizeCheck = false) const {
std::string data = getManufacturerData();
if(!skipSizeCheck && data.size() < sizeof(T)) return T();
const char *pData = data.data();
return *((T *)pData);
if (!skipSizeCheck && data.size() < sizeof(T)) return T();
const char* pData = data.data();
return *((T*)pData);
}
std::string getName();
int getRSSI();
NimBLEScan* getScan();
size_t getServiceDataCount();
std::string getServiceData(uint8_t index = 0);
std::string getServiceData(const NimBLEUUID &uuid);
/**
* @brief A template to convert the service data to <tt><type\></tt>.
* @tparam T The type to convert the data to.
@ -82,12 +124,12 @@ public:
* less than <tt>sizeof(<type\>)</tt>.
* @details <b>Use:</b> <tt>getServiceData<type>(skipSizeCheck);</tt>
*/
template<typename T>
T getServiceData(uint8_t index = 0, bool skipSizeCheck = false) {
template <typename T>
T getServiceData(uint8_t index = 0, bool skipSizeCheck = false) const {
std::string data = getServiceData(index);
if(!skipSizeCheck && data.size() < sizeof(T)) return T();
const char *pData = data.data();
return *((T *)pData);
if (!skipSizeCheck && data.size() < sizeof(T)) return T();
const char* pData = data.data();
return *((T*)pData);
}
/**
@ -99,78 +141,38 @@ public:
* less than <tt>sizeof(<type\>)</tt>.
* @details <b>Use:</b> <tt>getServiceData<type>(skipSizeCheck);</tt>
*/
template<typename T>
T getServiceData(const NimBLEUUID &uuid, bool skipSizeCheck = false) {
template <typename T>
T getServiceData(const NimBLEUUID& uuid, bool skipSizeCheck = false) const {
std::string data = getServiceData(uuid);
if(!skipSizeCheck && data.size() < sizeof(T)) return T();
const char *pData = data.data();
return *((T *)pData);
if (!skipSizeCheck && data.size() < sizeof(T)) return T();
const char* pData = data.data();
return *((T*)pData);
}
NimBLEUUID getServiceDataUUID(uint8_t index = 0);
NimBLEUUID getServiceUUID(uint8_t index = 0);
size_t getServiceUUIDCount();
NimBLEAddress getTargetAddress(uint8_t index = 0);
size_t getTargetAddressCount();
int8_t getTXPower();
uint8_t* getPayload();
uint8_t getAdvLength();
size_t getPayloadLength();
uint8_t getAddressType();
time_t getTimestamp();
bool isAdvertisingService(const NimBLEUUID &uuid);
bool haveAppearance();
bool haveManufacturerData();
bool haveName();
bool haveRSSI();
bool haveServiceData();
bool haveServiceUUID();
bool haveTXPower();
bool haveConnParams();
bool haveAdvInterval();
bool haveTargetAddress();
bool haveURI();
std::string toString();
private:
private:
friend class NimBLEScan;
void setAddress(NimBLEAddress address);
void setAdvType(uint8_t advType);
void setPayload(const uint8_t *payload, uint8_t length, bool append);
void setRSSI(int rssi);
uint8_t findAdvField(uint8_t type, uint8_t index = 0, uint8_t *data_loc = nullptr);
uint8_t findServiceData(uint8_t index, uint8_t* bytes);
NimBLEAdvertisedDevice(const ble_gap_event* event, uint8_t eventType);
void update(const ble_gap_event* event, uint8_t eventType);
uint8_t findAdvField(uint8_t type, uint8_t index = 0, size_t* data_loc = nullptr) const;
size_t findServiceData(uint8_t index, uint8_t* bytes) const;
NimBLEAddress m_address = NimBLEAddress("");
uint8_t m_advType;
int m_rssi;
time_t m_timestamp;
bool m_callbackSent;
uint8_t m_advLength;
NimBLEAddress m_address{};
uint8_t m_advType{};
int8_t m_rssi{};
uint8_t m_callbackSent{};
uint8_t m_advLength{};
std::vector<uint8_t> m_payload;
# if CONFIG_BT_NIMBLE_EXT_ADV
bool m_isLegacyAdv{};
uint8_t m_sid{};
uint8_t m_primPhy{};
uint8_t m_secPhy{};
uint16_t m_periodicItvl{};
# endif
std::vector<uint8_t> m_payload;
};
/**
* @brief A callback handler for callbacks associated device scanning.
*
* When we are performing a scan as a %BLE client, we may wish to know when a new device that is advertising
* has been found. This class can be sub-classed and registered such that when a scan is performed and
* a new advertised device has been found, we will be called back to be notified.
*/
class NimBLEAdvertisedDeviceCallbacks {
public:
virtual ~NimBLEAdvertisedDeviceCallbacks() {}
/**
* @brief Called when a new scan result is detected.
*
* As we are scanning, we will find new devices. When found, this call back is invoked with a reference to the
* device that was found. During any individual scan, a device will only be detected one time.
*/
virtual void onResult(NimBLEAdvertisedDevice* advertisedDevice) = 0;
};
#endif // #if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL)
#endif /* CONFIG_BT_ENABLED */
#endif /* COMPONENTS_NIMBLEADVERTISEDDEVICE_H_ */
#endif /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_OBSERVER */
#endif /* NIMBLE_CPP_ADVERTISED_DEVICE_H_ */

View File

@ -0,0 +1,586 @@
/*
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NimBLEAdvertisementData.h"
#if (CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_BROADCASTER && !CONFIG_BT_NIMBLE_EXT_ADV) || defined(_DOXYGEN_)
# include "NimBLEDevice.h"
# include "NimBLEUtils.h"
# include "NimBLEUUID.h"
# include "NimBLELog.h"
# if defined(CONFIG_NIMBLE_CPP_IDF)
# include "host/ble_hs_adv.h"
# else
# include "nimble/nimble/host/include/host/ble_hs_adv.h"
# endif
static const char* LOG_TAG = "NimBLEAdvertisementData";
/**
* @brief Add data to the payload to be advertised.
* @param [in] data The data to be added to the payload.
* @param [in] length The size of data to be added to the payload.
*/
bool NimBLEAdvertisementData::addData(const uint8_t* data, size_t length) {
if (m_payload.size() + length > BLE_HS_ADV_MAX_SZ) {
NIMBLE_LOGE(LOG_TAG, "Data length exceeded");
return false;
}
m_payload.insert(m_payload.end(), data, data + length);
return true;
} // addData
/**
* @brief Add data to the payload to be advertised.
* @param [in] data The data to be added to the payload.
*/
bool NimBLEAdvertisementData::addData(const std::vector<uint8_t>& data) {
return addData(&data[0], data.size());
} // addData
/**
* @brief Set the appearance.
* @param [in] appearance The appearance code value.
* @return True if successful.
* @details If the appearance value is 0 then it will be removed from the advertisement if set previously.
*/
bool NimBLEAdvertisementData::setAppearance(uint16_t appearance) {
if (appearance == 0) {
return removeData(BLE_HS_ADV_TYPE_APPEARANCE);
}
uint8_t data[4];
data[0] = 3;
data[1] = BLE_HS_ADV_TYPE_APPEARANCE;
data[2] = appearance;
data[3] = (appearance >> 8) & 0xFF;
return addData(data, 4);
} // setAppearance
/**
* @brief Set the advertisement flags.
* @param [in] flag The flags to be set in the advertisement.
* * BLE_HS_ADV_F_DISC_LTD
* * BLE_HS_ADV_F_DISC_GEN
* * BLE_HS_ADV_F_BREDR_UNSUP - must always use with NimBLE
* A flag value of 0 will remove the flags from the advertisement.
*/
bool NimBLEAdvertisementData::setFlags(uint8_t flag) {
int dataLoc = getDataLocation(BLE_HS_ADV_TYPE_FLAGS);
if (dataLoc != -1) {
if (flag) {
m_payload[dataLoc + 2] = flag | BLE_HS_ADV_F_BREDR_UNSUP;
return true;
} else {
return removeData(BLE_HS_ADV_TYPE_FLAGS);
}
}
uint8_t data[3];
data[0] = 2;
data[1] = BLE_HS_ADV_TYPE_FLAGS;
data[2] = flag | BLE_HS_ADV_F_BREDR_UNSUP;
return addData(data, 3);
} // setFlags
/**
* @brief Adds Tx power level to the advertisement data.
* @return True if successful.
*/
bool NimBLEAdvertisementData::addTxPower() {
uint8_t data[3];
data[0] = BLE_HS_ADV_TX_PWR_LVL_LEN + 1;
data[1] = BLE_HS_ADV_TYPE_TX_PWR_LVL;
# ifndef CONFIG_IDF_TARGET_ESP32P4
data[2] = NimBLEDevice::getPower(NimBLETxPowerType::Advertise);
# else
data[2] = 0;
# endif
return addData(data, 3);
} // addTxPower
/**
* @brief Set the preferred min and max connection intervals to advertise.
* @param [in] minInterval The minimum preferred connection interval.
* @param [in] maxInterval The Maximum preferred connection interval.
* @details Range = 0x0006(7.5ms) to 0x0C80(4000ms), values not within the range will be limited to this range.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setPreferredParams(uint16_t minInterval, uint16_t maxInterval) {
minInterval = std::max<uint16_t>(minInterval, 0x6);
minInterval = std::min<uint16_t>(minInterval, 0xC80);
maxInterval = std::max<uint16_t>(maxInterval, 0x6);
maxInterval = std::min<uint16_t>(maxInterval, 0xC80);
maxInterval = std::max<uint16_t>(maxInterval, minInterval); // Max must be greater than or equal to min.
uint8_t data[6];
data[0] = BLE_HS_ADV_SLAVE_ITVL_RANGE_LEN + 1;
data[1] = BLE_HS_ADV_TYPE_SLAVE_ITVL_RANGE;
data[2] = minInterval;
data[3] = minInterval >> 8;
data[4] = maxInterval;
data[5] = maxInterval >> 8;
return addData(data, 6);
} // setPreferredParams
/**
* @brief Add a service uuid to exposed list of services.
* @param [in] serviceUUID The UUID of the service to expose.
*/
bool NimBLEAdvertisementData::addServiceUUID(const NimBLEUUID& serviceUUID) {
uint8_t bytes = serviceUUID.bitSize() / 8;
int type;
switch (bytes) {
case 2:
type = BLE_HS_ADV_TYPE_COMP_UUIDS16;
break;
case 4:
type = BLE_HS_ADV_TYPE_COMP_UUIDS32;
break;
case 16:
type = BLE_HS_ADV_TYPE_COMP_UUIDS128;
break;
default:
NIMBLE_LOGE(LOG_TAG, "Cannot add UUID, invalid size!");
return false;
}
int dataLoc = getDataLocation(type);
uint8_t length = bytes;
if (dataLoc == -1) {
length += 2;
}
if (length + getPayload().size() > BLE_HS_ADV_MAX_SZ) {
NIMBLE_LOGE(LOG_TAG, "Cannot add UUID, data length exceeded!");
return false;
}
uint8_t data[BLE_HS_ADV_MAX_SZ];
const uint8_t* uuid = serviceUUID.getValue();
if (dataLoc == -1) {
data[0] = 1 + bytes;
data[1] = type;
memcpy(&data[2], uuid, bytes);
return addData(data, length);
}
m_payload.insert(m_payload.begin() + dataLoc + m_payload[dataLoc] + 1, uuid, uuid + bytes);
m_payload[dataLoc] += bytes;
return true;
} // addServiceUUID
/**
* @brief Add a service uuid to exposed list of services.
* @param [in] serviceUUID The string representation of the service to expose.
* @return True if successful.
*/
bool NimBLEAdvertisementData::addServiceUUID(const char* serviceUUID) {
return addServiceUUID(NimBLEUUID(serviceUUID));
} // addServiceUUID
/**
* @brief Remove a service UUID from the advertisement.
* @param [in] serviceUUID The UUID of the service to remove.
* @return True if successful or uuid not found, false if uuid error or data could not be reset.
*/
bool NimBLEAdvertisementData::removeServiceUUID(const NimBLEUUID& serviceUUID) {
uint8_t bytes = serviceUUID.bitSize() / 8;
int type;
switch (bytes) {
case 2:
type = BLE_HS_ADV_TYPE_COMP_UUIDS16;
break;
case 4:
type = BLE_HS_ADV_TYPE_COMP_UUIDS32;
break;
case 16:
type = BLE_HS_ADV_TYPE_COMP_UUIDS128;
break;
default:
NIMBLE_LOGE(LOG_TAG, "Cannot remove UUID, invalid size!");
return false;
}
int dataLoc = getDataLocation(type);
if (dataLoc == -1) {
return true;
}
int uuidLoc = -1;
for (size_t i = dataLoc + 2; i < m_payload.size(); i += bytes) {
if (memcmp(&m_payload[i], serviceUUID.getValue(), bytes) == 0) {
uuidLoc = i;
break;
}
}
if (uuidLoc == -1) {
return true;
}
if (m_payload[dataLoc] - bytes == 1) {
return removeData(type);
}
m_payload.erase(m_payload.begin() + uuidLoc, m_payload.begin() + uuidLoc + bytes);
m_payload[dataLoc] -= bytes;
return true;
} // removeServiceUUID
/**
* @brief Remove a service UUID from the advertisement.
* @param [in] serviceUUID The UUID of the service to remove.
* @return True if successful or uuid not found, false if uuid error or data could not be reset.
*/
bool NimBLEAdvertisementData::removeServiceUUID(const char* serviceUUID) {
return removeServiceUUID(NimBLEUUID(serviceUUID));
} // removeServiceUUID
/**
* @brief Remove all service UUIDs from the advertisement.
*/
bool NimBLEAdvertisementData::removeServices() {
return true;
} // removeServices
/**
* @brief Set manufacturer specific data.
* @param [in] data The manufacturer data to advertise.
* @param [in] length The length of the data.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setManufacturerData(const uint8_t* data, size_t length) {
if (length > BLE_HS_ADV_MAX_FIELD_SZ) {
NIMBLE_LOGE(LOG_TAG, "MFG data too long");
return false;
}
uint8_t mdata[BLE_HS_ADV_MAX_SZ];
mdata[0] = length + 1;
mdata[1] = BLE_HS_ADV_TYPE_MFG_DATA;
memcpy(&mdata[2], data, length);
return addData(mdata, length + 2);
} // setManufacturerData
/**
* @brief Set manufacturer specific data.
* @param [in] data The manufacturer data to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setManufacturerData(const std::string& data) {
return setManufacturerData(reinterpret_cast<const uint8_t*>(data.data()), data.length());
} // setManufacturerData
/**
* @brief Set manufacturer specific data.
* @param [in] data The manufacturer data to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setManufacturerData(const std::vector<uint8_t>& data) {
return setManufacturerData(&data[0], data.size());
} // setManufacturerData
/**
* @brief Set the URI to advertise.
* @param [in] uri The uri to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setURI(const std::string& uri) {
if (uri.length() > BLE_HS_ADV_MAX_FIELD_SZ) {
NIMBLE_LOGE(LOG_TAG, "URI too long");
return false;
}
uint8_t data[BLE_HS_ADV_MAX_SZ];
uint8_t length = 2 + uri.length();
data[0] = length - 1;
data[1] = BLE_HS_ADV_TYPE_URI;
memcpy(&data[2], uri.c_str(), uri.length());
return addData(data, length);
} // setURI
/**
* @brief Set the complete name of this device.
* @param [in] name The name to advertise.
* @param [in] isComplete If true the name is complete, which will set the data type accordingly.
* @details If the name is longer than 29 characters it will be truncated.
* and the data type will be set to incomplete name.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setName(const std::string& name, bool isComplete) {
if (name.length() > BLE_HS_ADV_MAX_FIELD_SZ) {
NIMBLE_LOGE(LOG_TAG, "Name too long - truncating");
isComplete = false;
}
uint8_t data[BLE_HS_ADV_MAX_SZ];
uint8_t length = 2 + std::min<uint8_t>(name.length(), BLE_HS_ADV_MAX_FIELD_SZ);
data[0] = length - 1;
data[1] = isComplete ? BLE_HS_ADV_TYPE_COMP_NAME : BLE_HS_ADV_TYPE_INCOMP_NAME;
memcpy(&data[2], name.c_str(), std::min<uint8_t>(name.length(), BLE_HS_ADV_MAX_FIELD_SZ));
return addData(data, length);
} // setName
/**
* @brief Set the short name.
* @param [in] name The short name of the device.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setShortName(const std::string& name) {
return setName(name, false);
} // setShortName
/**
* @brief Set a single service to advertise as a complete list of services.
* @param [in] uuid The service to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setCompleteServices(const NimBLEUUID& uuid) {
return setServices(true, uuid.bitSize(), {uuid});
} // setCompleteServices
/**
* @brief Set the complete list of 16 bit services to advertise.
* @param [in] uuids A vector of 16 bit UUID's to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setCompleteServices16(const std::vector<NimBLEUUID>& uuids) {
return setServices(true, 16, uuids);
} // setCompleteServices16
/**
* @brief Set the complete list of 32 bit services to advertise.
* @param [in] uuids A vector of 32 bit UUID's to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setCompleteServices32(const std::vector<NimBLEUUID>& uuids) {
return setServices(true, 32, uuids);
} // setCompleteServices32
/**
* @brief Set a single service to advertise as a partial list of services.
* @param [in] uuid The service to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setPartialServices(const NimBLEUUID& uuid) {
return setServices(false, uuid.bitSize(), {uuid});
} // setPartialServices
/**
* @brief Set the partial list of services to advertise.
* @param [in] uuids A vector of 16 bit UUID's to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setPartialServices16(const std::vector<NimBLEUUID>& uuids) {
return setServices(false, 16, uuids);
} // setPartialServices16
/**
* @brief Set the partial list of services to advertise.
* @param [in] uuids A vector of 32 bit UUID's to advertise.
* @return True if successful.
*/
bool NimBLEAdvertisementData::setPartialServices32(const std::vector<NimBLEUUID>& uuids) {
return setServices(false, 32, uuids);
} // setPartialServices32
/**
* @brief Utility function to create the list of service UUID's from a vector.
* @param [in] complete If true the vector is the complete set of services.
* @param [in] size The bit size of the UUID's in the vector. (16, 32, or 128).
* @param [in] uuids The vector of service UUID's to advertise.
* @return True if successful.
* @details The number of services will be truncated if the total length exceeds 31 bytes.
*/
bool NimBLEAdvertisementData::setServices(bool complete, uint8_t size, const std::vector<NimBLEUUID>& uuids) {
uint8_t bytes = size / 8;
uint8_t length = 2; // start with 2 for length + type bytes
uint8_t data[BLE_HS_ADV_MAX_SZ];
for (const auto& uuid : uuids) {
if (uuid.bitSize() != size) {
NIMBLE_LOGE(LOG_TAG, "Service UUID(%d) invalid", size);
continue;
} else {
if (length + bytes >= BLE_HS_ADV_MAX_SZ) {
NIMBLE_LOGW(LOG_TAG, "Too many services - truncating");
complete = false;
break;
}
memcpy(&data[length], uuid.getValue(), bytes);
length += bytes;
}
}
data[0] = length - 1; // don't count the length byte as part of the AD length
switch (size) {
case 16:
data[1] = (complete ? BLE_HS_ADV_TYPE_COMP_UUIDS16 : BLE_HS_ADV_TYPE_INCOMP_UUIDS16);
break;
case 32:
data[1] = (complete ? BLE_HS_ADV_TYPE_COMP_UUIDS32 : BLE_HS_ADV_TYPE_INCOMP_UUIDS32);
break;
case 128:
data[1] = (complete ? BLE_HS_ADV_TYPE_COMP_UUIDS128 : BLE_HS_ADV_TYPE_INCOMP_UUIDS128);
break;
default:
NIMBLE_LOGE(LOG_TAG, "Cannot set services, invalid size!");
return false;
}
return addData(data, length);
} // setServices
/**
* @brief Set the service data advertised for the UUID.
* @param [in] uuid The UUID the service data belongs to.
* @param [in] data The data to advertise.
* @param [in] length The length of the data.
* @note If data length is 0 the service data will not be advertised.
* @return True if successful, false if data length is too long or could not be set.
*/
bool NimBLEAdvertisementData::setServiceData(const NimBLEUUID& uuid, const uint8_t* data, size_t length) {
uint8_t uuidBytes = uuid.bitSize() / 8;
uint8_t sDataLen = 2 + uuidBytes + length;
if (sDataLen > BLE_HS_ADV_MAX_SZ) {
NIMBLE_LOGE(LOG_TAG, "Service Data too long");
return false;
}
uint8_t type;
switch (uuidBytes) {
case 2:
type = BLE_HS_ADV_TYPE_SVC_DATA_UUID16;
break;
case 4:
type = BLE_HS_ADV_TYPE_SVC_DATA_UUID32;
break;
case 16:
type = BLE_HS_ADV_TYPE_SVC_DATA_UUID128;
break;
default:
NIMBLE_LOGE(LOG_TAG, "Cannot set service data, invalid size!");
return false;
}
if (length == 0) {
removeData(type);
return true;
}
uint8_t sData[BLE_HS_ADV_MAX_SZ];
sData[0] = uuidBytes + length + 1;
sData[1] = type;
memcpy(&sData[2], uuid.getValue(), uuidBytes);
memcpy(&sData[2 + uuidBytes], data, length);
return addData(sData, sDataLen);
} // setServiceData
/**
* @brief Set the service data (UUID + data)
* @param [in] uuid The UUID to set with the service data.
* @param [in] data The data to be associated with the service data advertised.
* @return True if the service data was set successfully.
* @note If data length is 0 the service data will not be advertised.
*/
bool NimBLEAdvertisementData::setServiceData(const NimBLEUUID& uuid, const std::string& data) {
return setServiceData(uuid, reinterpret_cast<const uint8_t*>(data.data()), data.length());
} // setServiceData
/**
* @brief Set the service data advertised for the UUID.
* @param [in] uuid The UUID the service data belongs to.
* @param [in] data The data to advertise.
* @return True if the service data was set successfully.
* @note If data length is 0 the service data will not be advertised.
*/
bool NimBLEAdvertisementData::setServiceData(const NimBLEUUID& uuid, const std::vector<uint8_t>& data) {
return setServiceData(uuid, &data[0], data.size());
} // setServiceData
/**
* @brief Get the location of the data in the payload.
* @param [in] type The type of data to search for.
* @return -1 if the data is not found, otherwise the index of the data in the payload.
*/
int NimBLEAdvertisementData::getDataLocation(uint8_t type) const {
size_t index = 0;
while (index < m_payload.size()) {
if (m_payload[index + 1] == type) {
return index;
}
index += m_payload[index] + 1;
}
return -1;
} // getDataLocation
/**
* @brief Remove data from the advertisement data.
* @param [in] type The type of data to remove.
* @return True if successful, false if the data was not found.
*/
bool NimBLEAdvertisementData::removeData(uint8_t type) {
int dataLoc = getDataLocation(type);
if (dataLoc != -1) {
std::vector<uint8_t> swap(m_payload.begin(), m_payload.begin() + dataLoc);
int nextData = dataLoc + m_payload[dataLoc] + 1;
swap.insert(swap.end(), m_payload.begin() + nextData, m_payload.end());
swap.swap(m_payload);
return true;
}
return false;
} // removeData
/**
* @brief Retrieve the payload that is to be advertised.
* @return The payload of the advertisement data.
*/
std::vector<uint8_t> NimBLEAdvertisementData::getPayload() const {
return m_payload;
} // getPayload
/**
* @brief Clear the advertisement data for reuse.
*/
void NimBLEAdvertisementData::clearData() {
std::vector<uint8_t>().swap(m_payload);
} // clearData
/**
* @brief Get the string representation of the advertisement data.
* @return The string representation of the advertisement data.
*/
std::string NimBLEAdvertisementData::toString() const {
std::string hexStr = NimBLEUtils::dataToHexString(&m_payload[0], m_payload.size());
std::string str;
for (size_t i = 0; i < hexStr.length(); i += 2) {
str += hexStr[i];
str += hexStr[i + 1];
if (i + 2 < hexStr.length()) {
str += " ";
}
}
return str;
} // toString
#endif // (CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_BROADCASTER && !CONFIG_BT_NIMBLE_EXT_ADV) || defined(_DOXYGEN_)

Some files were not shown because too many files have changed in this diff Show More