Compare commits

...

87 Commits

Author SHA1 Message Date
8aa824ef32 Release 2.2.0 2025-02-24 17:53:24 -07:00
cc7f97a37d 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-24 17:35:42 -07:00
8723121ff9 [BugFix] Provide default task data when retrieving all descriptors.
* Update the descriptor filter when trying again with different UUID sizes.
2025-02-24 17:35:39 -07:00
90b721ed55 change(2904|AdvData): Add missing parameter name in declarations 2025-02-24 17:35:36 -07:00
d1ef98a4c8 feat(Device): Implement store status handler 2025-02-24 17:35:34 -07:00
70eee888eb feat(AdvDevice): Add convenience operator to NimBLEAddress 2025-02-24 17:35:31 -07:00
80b61ffa3d feat(Log): Add macros for conditional log print and rc handling 2025-02-24 17:35:27 -07:00
ee895d386e Release 2.1.1 2025-01-26 18:22:37 -07:00
5add3442e9 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 18:16:03 -07:00
aea55ccda2 Rename config macros to enable duplicate scan options on s3/c3 2025-01-26 18:16:00 -07:00
83e9919457 Workaround for P4 CI build error. 2025-01-26 18:15:57 -07:00
edeaf3977a Fix characteristic discovery with no descriptors.
Avoid discovery of descriptors if there are no handles remaining.
2025-01-26 18:15:54 -07:00
4e80e1ee38 Release 2.1.0 2025-01-12 18:16:42 -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
140 changed files with 6698 additions and 6354 deletions

View File

@ -1,7 +1,7 @@
name: Build
on:
workflow_dispatch: # Start a workflow
workflow_dispatch:
pull_request:
push:
branches:
@ -17,33 +17,28 @@ jobs:
# 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.1"]
idf_target: ["esp32", "esp32s3", "esp32c2", "esp32c3", "esp32c6", "esp32h2"]
idf_ver: ["release-v4.4", "release-v5.1", "v5.3.2"]
idf_target: ["esp32", "esp32s3", "esp32c2", "esp32c3", "esp32c6", "esp32h2", "esp32p4"]
example:
- Advanced/NimBLE_Client
- Advanced/NimBLE_Server
- basic/BLE_client
- basic/BLE_notify
- basic/BLE_scan
- basic/BLE_server
- basic/BLE_uart
- NimBLE_Client
- NimBLE_Server
- Bluetooth_5/NimBLE_extended_client
- Bluetooth_5/NimBLE_extended_server
- Bluetooth_5/NimBLE_multi_advertiser
- NimBLE_server_get_client_name
exclude:
- idf_target: "esp32"
example: Bluetooth_5/NimBLE_extended_client
- idf_target: "esp32"
example: Bluetooth_5/NimBLE_extended_server
- idf_target: "esp32"
example: Bluetooth_5/NimBLE_multi_advertiser
- idf_ver: release-v4.4
idf_target: "esp32c2"
- 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:
@ -65,6 +60,6 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Doxygen Action
uses: mattnotmitt/doxygen-action@v1.9.5
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'

2
.gitignore vendored
View File

@ -1 +1 @@
docs/doxydocs
docs/doxydocs

View File

@ -1,14 +1,306 @@
# Changelog
All notable changes to this project will be documented in this file.
## [Unreleased]
## [2.2.0] 2025-02-24
## 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
- NimBLESecurity class removed.
- `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
@ -71,7 +363,7 @@ All notable changes to this project will be documented in this file.
## [1.3.0] - 2021-08-02
### Added
- `NimBLECharacteristic::removeDescriptor`: Dynamically remove a descriptor from a characterisic. Takes effect after all connections are closed and sends a service changed indication.
- `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
@ -102,12 +394,12 @@ All notable changes to this project will be documented in this file.
### 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 characterisic with a std::string value now correctly writes values with null characters.
- Retrieving remote descriptors now uses the characterisic end handle correctly.
- 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.
- Complile errors with NimBLE release 1.3.0.
- Compile errors with NimBLE release 1.3.0.
## [1.2.0] - 2021-02-08
@ -120,7 +412,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)`
@ -162,12 +454,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.
@ -176,84 +468,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

@ -44,6 +44,7 @@ idf_component_register(
"src/NimBLE2904.cpp"
"src/NimBLEAddress.cpp"
"src/NimBLEAdvertisedDevice.cpp"
"src/NimBLEAdvertisementData.cpp"
"src/NimBLEAdvertising.cpp"
"src/NimBLEAttValue.cpp"
"src/NimBLEBeacon.cpp"
@ -52,7 +53,6 @@ idf_component_register(
"src/NimBLEDescriptor.cpp"
"src/NimBLEDevice.cpp"
"src/NimBLEEddystoneTLM.cpp"
"src/NimBLEEddystoneURL.cpp"
"src/NimBLEExtAdvertising.cpp"
"src/NimBLEHIDDevice.cpp"
"src/NimBLERemoteCharacteristic.cpp"

View File

@ -1,56 +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/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()

127
Kconfig
View File

@ -26,6 +26,113 @@ config NIMBLE_CPP_LOG_LEVEL
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"
@ -50,6 +157,20 @@ config NIMBLE_CPP_ENABLE_ADVERTISEMENT_TYPE_TEXT
while scanning as text messages in the debug log.
This will use approximately 250 bytes of flash memory.
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"
@ -77,12 +198,12 @@ config NIMBLE_CPP_DEBUG_ASSERT_ENABLED
This will use approximately 1kB of flash memory.
config NIMBLE_CPP_FREERTOS_TASK_BLOCK_BIT
int "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
#
@ -130,4 +251,4 @@ if IDF_TARGET_ESP32P4
endchoice
endif
endmenu
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,6 +53,14 @@ 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.

View File

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

View File

@ -0,0 +1,166 @@
# 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`.
<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.
<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

@ -1,4 +1,4 @@
# Doxyfile 1.9.5
# Doxyfile 1.10.0
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
@ -48,7 +48,7 @@ PROJECT_NAME = esp-nimble-cpp
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER = 1.4.1
PROJECT_NUMBER = 2.2.0
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
@ -63,6 +63,12 @@ PROJECT_BRIEF =
PROJECT_LOGO =
# With the PROJECT_ICON tag one can specify an icon that is included in the tabs
# when the HTML document is shown. Doxygen will copy the logo to the output
# directory.
PROJECT_ICON =
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
@ -86,7 +92,7 @@ CREATE_SUBDIRS = NO
# level increment doubles the number of directories, resulting in 4096
# directories at level 8 which is the default and also the maximum value. The
# sub-directories are organized in 2 levels, the first level always has a fixed
# numer of 16 directories.
# number of 16 directories.
# Minimum value: 0, maximum value: 8, default value: 8.
# This tag requires that the tag CREATE_SUBDIRS is set to YES.
@ -363,6 +369,17 @@ MARKDOWN_SUPPORT = YES
TOC_INCLUDE_HEADINGS = 5
# The MARKDOWN_ID_STYLE tag can be used to specify the algorithm used to
# generate identifiers for the Markdown headings. Note: Every identifier is
# unique.
# Possible values are: DOXYGEN use a fixed 'autotoc_md' string followed by a
# sequence number starting at 0 and GITHUB use the lower case version of title
# with any whitespace replaced by '-' and punctuation characters removed.
# The default value is: DOXYGEN.
# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
MARKDOWN_ID_STYLE = GITHUB
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by putting a % sign in front of the word or
@ -487,6 +504,14 @@ LOOKUP_CACHE_SIZE = 0
NUM_PROC_THREADS = 1
# If the TIMESTAMP tag is set different from NO then each generated page will
# contain the date or date and time when the page was generated. Setting this to
# NO can help when comparing the output of multiple runs.
# Possible values are: YES, NO, DATETIME and DATE.
# The default value is: NO.
TIMESTAMP = NO
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
@ -568,7 +593,8 @@ HIDE_UNDOC_MEMBERS = YES
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO, these classes will be included in the various overviews. This option
# has no effect if EXTRACT_ALL is enabled.
# will also hide undocumented C++ concepts if enabled. This option has no effect
# if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = YES
@ -859,14 +885,29 @@ WARN_IF_INCOMPLETE_DOC = YES
WARN_NO_PARAMDOC = NO
# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, doxygen will warn about
# undocumented enumeration values. If set to NO, doxygen will accept
# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: NO.
WARN_IF_UNDOC_ENUM_VAL = NO
# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS
# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but
# at the end of the doxygen process doxygen will return with a non-zero status.
# Possible values are: NO, YES and FAIL_ON_WARNINGS.
# If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS_PRINT then doxygen behaves
# like FAIL_ON_WARNINGS but in case no WARN_LOGFILE is defined doxygen will not
# write the warning messages in between other messages but write them at the end
# of a run, in case a WARN_LOGFILE is defined the warning messages will be
# besides being in the defined file also be shown at the end of a run, unless
# the WARN_LOGFILE is defined as - i.e. standard output (stdout) in that case
# the behavior will remain as with the setting FAIL_ON_WARNINGS.
# Possible values are: NO, YES, FAIL_ON_WARNINGS and FAIL_ON_WARNINGS_PRINT.
# The default value is: NO.
WARN_AS_ERROR = YES
WARN_AS_ERROR = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
@ -943,12 +984,12 @@ INPUT_FILE_ENCODING =
# Note the list of default checked file patterns might differ from the list of
# default file extension mappings.
#
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml,
# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C
# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd,
# *.vhdl, *.ucf, *.qsf and *.ice.
# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cxxm,
# *.cpp, *.cppm, *.ccm, *.c++, *.c++m, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl,
# *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, *.h++, *.ixx, *.l, *.cs, *.d,
# *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to
# be provided as doxygen C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,
# *.f18, *.f, *.for, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice.
FILE_PATTERNS = *.c \
*.cc \
@ -1034,9 +1075,6 @@ EXCLUDE_PATTERNS =
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# ANamespace::AClass, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS =
@ -1150,7 +1188,8 @@ FORTRAN_COMMENT_AFTER = 72
SOURCE_BROWSER = NO
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# multi-line macros, enums or list initialized variables directly into the
# documentation.
# The default value is: NO.
INLINE_SOURCES = NO
@ -1222,46 +1261,6 @@ USE_HTAGS = NO
VERBATIM_HEADERS = YES
# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
# clang parser (see:
# http://clang.llvm.org/) for more accurate parsing at the cost of reduced
# performance. This can be particularly helpful with template rich C++ code for
# which doxygen's built-in parser lacks the necessary type information.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
# The default value is: NO.
CLANG_ASSISTED_PARSING = NO
# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS
# tag is set to YES then doxygen will add the directory of each input to the
# include path.
# The default value is: YES.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_ADD_INC_PATHS = YES
# If clang assisted parsing is enabled you can provide the compiler with command
# line options that you would normally use when invoking the compiler. Note that
# the include paths will already be set by doxygen for the files and directories
# specified with INPUT and INCLUDE_PATH.
# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
CLANG_OPTIONS =
# If clang assisted parsing is enabled you can provide the clang parser with the
# path to the directory containing a file called compile_commands.json. This
# file is the compilation database (see:
# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the
# options used when the source files were built. This is equivalent to
# specifying the -p option to a clang tool, such as clang-check. These options
# will then be passed to the parser. Any options specified with CLANG_OPTIONS
# will be added as well.
# Note: The availability of this option depends on whether or not doxygen was
# generated with the -Duse_libclang=ON option for CMake.
CLANG_DATABASE_PATH =
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
@ -1273,10 +1272,11 @@ CLANG_DATABASE_PATH =
ALPHABETICAL_INDEX = YES
# In case all classes in a project start with a common prefix, all classes will
# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
# can be used to specify a prefix (or a list of prefixes) that should be ignored
# while generating the index headers.
# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes)
# that should be ignored while generating the index headers. The IGNORE_PREFIX
# tag works for classes, function and member names. The entity will be placed in
# the alphabetical list under the first letter of the entity name that remains
# after removing the prefix.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
@ -1355,7 +1355,12 @@ HTML_STYLESHEET =
# Doxygen will copy the style sheet files to the output directory.
# Note: The order of the extra style sheet files is of importance (e.g. the last
# style sheet in the list overrules the setting of the previous ones in the
# list). For an example see the documentation.
# list).
# Note: Since the styling of scrollbars can currently not be overruled in
# Webkit/Chromium, the styling will be left out of the default doxygen.css if
# one or more extra stylesheets have been specified. So if scrollbar
# customization is desired it has to be added explicitly. For an example see the
# documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET =
@ -1371,17 +1376,13 @@ HTML_EXTRA_STYLESHEET =
HTML_EXTRA_FILES =
# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output
# should be rendered with a dark or light theme. Default setting AUTO_LIGHT
# enables light output unless the user preference is dark output. Other options
# are DARK to always use dark mode, LIGHT to always use light mode, AUTO_DARK to
# default to dark mode unless the user prefers light mode, and TOGGLE to let the
# user toggle between dark and light mode via a button.
# Possible values are: LIGHT Always generate light output., DARK Always generate
# dark output., AUTO_LIGHT Automatically set the mode according to the user
# preference, use light mode if no preference is set (the default)., AUTO_DARK
# Automatically set the mode according to the user preference, use dark mode if
# no preference is set. and TOGGLE Allow to user to switch between light and
# dark mode via a button..
# should be rendered with a dark or light theme.
# Possible values are: LIGHT always generate light mode output, DARK always
# generate dark mode output, AUTO_LIGHT automatically set the mode according to
# the user preference, use light mode if no preference is set (the default),
# AUTO_DARK automatically set the mode according to the user preference, use
# dark mode if no preference is set and TOGGLE allow to user to switch between
# light and dark mode via a button.
# The default value is: AUTO_LIGHT.
# This tag requires that the tag GENERATE_HTML is set to YES.
@ -1417,15 +1418,6 @@ HTML_COLORSTYLE_SAT = 100
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to YES can help to show when doxygen was last run and thus if the
# documentation is up to date.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = NO
# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
# documentation will contain a main index with vertical navigation menus that
# are dynamically created via JavaScript. If disabled, the navigation index will
@ -1445,6 +1437,33 @@ HTML_DYNAMIC_MENUS = YES
HTML_DYNAMIC_SECTIONS = NO
# If the HTML_CODE_FOLDING tag is set to YES then classes and functions can be
# dynamically folded and expanded in the generated HTML source code.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_CODE_FOLDING = YES
# If the HTML_COPY_CLIPBOARD tag is set to YES then doxygen will show an icon in
# the top right corner of code and text fragments that allows the user to copy
# its content to the clipboard. Note this only works if supported by the browser
# and the web page is served via a secure context (see:
# https://www.w3.org/TR/secure-contexts/), i.e. using the https: or file:
# protocol.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COPY_CLIPBOARD = YES
# Doxygen stores a couple of settings persistently in the browser (via e.g.
# cookies). By default these settings apply to all HTML pages generated by
# doxygen across all projects. The HTML_PROJECT_COOKIE tag can be used to store
# the settings under a project specific key, such that the user preferences will
# be stored separately.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_PROJECT_COOKIE =
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
@ -1575,6 +1594,16 @@ BINARY_TOC = NO
TOC_EXPAND = NO
# The SITEMAP_URL tag is used to specify the full URL of the place where the
# generated documentation will be placed on the server by the user during the
# deployment of the documentation. The generated sitemap is called sitemap.xml
# and placed on the directory specified by HTML_OUTPUT. In case no SITEMAP_URL
# is specified no sitemap is generated. For information about the sitemap
# protocol see https://www.sitemaps.org
# This tag requires that the tag GENERATE_HTML is set to YES.
SITEMAP_URL =
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
@ -1811,8 +1840,8 @@ MATHJAX_RELPATH = https://cdn.jsdelivr.net/npm/mathjax@2
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# for MathJax version 2 (see https://docs.mathjax.org/en/v2.7-latest/tex.html
# #tex-and-latex-extensions):
# for MathJax version 2 (see
# https://docs.mathjax.org/en/v2.7-latest/tex.html#tex-and-latex-extensions):
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# For example for MathJax version 3 (see
# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html):
@ -2063,9 +2092,16 @@ PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help.
# The LATEX_BATCHMODE tag signals the behavior of LaTeX in case of an error.
# Possible values are: NO same as ERROR_STOP, YES same as BATCH, BATCH In batch
# mode nothing is printed on the terminal, errors are scrolled as if <return> is
# hit at every error; missing files that TeX tries to input or request from
# keyboard input (\read on a not open input stream) cause the job to abort,
# NON_STOP In nonstop mode the diagnostic message will appear on the terminal,
# but there is no possibility of user interaction just like in batch mode,
# SCROLL In scroll mode, TeX will stop only for missing files to input or if
# keyboard input is necessary and ERROR_STOP In errorstop mode, TeX will stop at
# each error, asking for user intervention.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
@ -2086,14 +2122,6 @@ LATEX_HIDE_INDICES = NO
LATEX_BIB_STYLE = plain
# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_TIMESTAMP = NO
# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
# path from which the emoji images will be read. If a relative path is entered,
# it will be relative to the LATEX_OUTPUT directory. If left blank the
@ -2259,7 +2287,7 @@ DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
# AutoGen Definitions (see https://autogen.sourceforge.net/) file that captures
# the structure of the code including all documentation. Note that this feature
# is still experimental and incomplete at the moment.
# The default value is: NO.
@ -2270,6 +2298,28 @@ GENERATE_AUTOGEN_DEF = NO
# Configuration options related to Sqlite3 output
#---------------------------------------------------------------------------
# If the GENERATE_SQLITE3 tag is set to YES doxygen will generate a Sqlite3
# database with symbols found by doxygen stored in tables.
# The default value is: NO.
GENERATE_SQLITE3 = NO
# The SQLITE3_OUTPUT tag is used to specify where the Sqlite3 database will be
# put. If a relative path is entered the value of OUTPUT_DIRECTORY will be put
# in front of it.
# The default directory is: sqlite3.
# This tag requires that the tag GENERATE_SQLITE3 is set to YES.
SQLITE3_OUTPUT = sqlite3
# The SQLITE3_RECREATE_DB tag is set to YES, the existing doxygen_sqlite3.db
# database file will be recreated with each doxygen run. If set to NO, doxygen
# will warn if a database file is already found and not modify it.
# The default value is: YES.
# This tag requires that the tag GENERATE_SQLITE3 is set to YES.
SQLITE3_RECREATE_DB = YES
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
@ -2418,15 +2468,15 @@ TAGFILES =
GENERATE_TAGFILE =
# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
# the class index. If set to NO, only the inherited external classes will be
# listed.
# If the ALLEXTERNALS tag is set to YES, all external classes and namespaces
# will be listed in the class and namespace index. If set to NO, only the
# inherited external classes will be listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
# in the modules index. If set to NO, only the current project's groups will be
# in the topic index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
@ -2440,16 +2490,9 @@ EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
# Configuration options related to diagram generator tools
#---------------------------------------------------------------------------
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
DIA_PATH =
# If set to YES the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
@ -2458,7 +2501,7 @@ HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# https://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
@ -2511,13 +2554,19 @@ DOT_NODE_ATTR = "shape=box,height=0.2,width=0.4"
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES (or GRAPH) then doxygen will generate a
# graph for each documented class showing the direct and indirect inheritance
# relations. In case HAVE_DOT is set as well dot will be used to draw the graph,
# otherwise the built-in generator will be used. If the CLASS_GRAPH tag is set
# to TEXT the direct and indirect inheritance relations will be shown as texts /
# links.
# Possible values are: NO, YES, TEXT and GRAPH.
# If the CLASS_GRAPH tag is set to YES or GRAPH or BUILTIN then doxygen will
# generate a graph for each documented class showing the direct and indirect
# inheritance relations. In case the CLASS_GRAPH tag is set to YES or GRAPH and
# HAVE_DOT is enabled as well, then dot will be used to draw the graph. In case
# the CLASS_GRAPH tag is set to YES and HAVE_DOT is disabled or if the
# CLASS_GRAPH tag is set to BUILTIN, then the built-in generator will be used.
# If the CLASS_GRAPH tag is set to TEXT the direct and indirect inheritance
# relations will be shown as texts / links. Explicit enabling an inheritance
# graph or choosing a different representation for an inheritance graph of a
# specific class, can be accomplished by means of the command \inheritancegraph.
# Disabling an inheritance graph can be accomplished by means of the command
# \hideinheritancegraph.
# Possible values are: NO, YES, TEXT, GRAPH and BUILTIN.
# The default value is: YES.
CLASS_GRAPH = TEXT
@ -2525,15 +2574,21 @@ CLASS_GRAPH = TEXT
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# class with other documented classes. Explicit enabling a collaboration graph,
# when COLLABORATION_GRAPH is set to NO, can be accomplished by means of the
# command \collaborationgraph. Disabling a collaboration graph can be
# accomplished by means of the command \hidecollaborationgraph.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies. See also the chapter Grouping
# in the manual.
# groups, showing the direct groups dependencies. Explicit enabling a group
# dependency graph, when GROUP_GRAPHS is set to NO, can be accomplished by means
# of the command \groupgraph. Disabling a directory graph can be accomplished by
# means of the command \hidegroupgraph. See also the chapter Grouping in the
# manual.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
@ -2575,8 +2630,8 @@ DOT_UML_DETAILS = NO
# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters
# to display on a single line. If the actual line length exceeds this threshold
# significantly it will wrapped across multiple lines. Some heuristics are apply
# to avoid ugly line breaks.
# significantly it will be wrapped across multiple lines. Some heuristics are
# applied to avoid ugly line breaks.
# Minimum value: 0, maximum value: 1000, default value: 17.
# This tag requires that the tag HAVE_DOT is set to YES.
@ -2593,7 +2648,9 @@ TEMPLATE_RELATIONS = NO
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# files. Explicit enabling an include graph, when INCLUDE_GRAPH is is set to NO,
# can be accomplished by means of the command \includegraph. Disabling an
# include graph can be accomplished by means of the command \hideincludegraph.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
@ -2602,7 +2659,10 @@ INCLUDE_GRAPH = YES
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# files. Explicit enabling an included by graph, when INCLUDED_BY_GRAPH is set
# to NO, can be accomplished by means of the command \includedbygraph. Disabling
# an included by graph can be accomplished by means of the command
# \hideincludedbygraph.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
@ -2642,7 +2702,10 @@ GRAPHICAL_HIERARCHY = YES
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# files in the directories. Explicit enabling a directory graph, when
# DIRECTORY_GRAPH is set to NO, can be accomplished by means of the command
# \directorygraph. Disabling a directory graph can be accomplished by means of
# the command \hidedirectorygraph.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
@ -2658,7 +2721,7 @@ DIR_GRAPH_MAX_DEPTH = 1
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot. For an explanation of the image formats see the section
# output formats in the documentation of the dot tool (Graphviz (see:
# http://www.graphviz.org/)).
# https://www.graphviz.org/)).
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
@ -2695,11 +2758,12 @@ DOT_PATH =
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
# You can include diagrams made with dia in doxygen documentation. Doxygen will
# then run dia to produce the diagram and insert it in the documentation. The
# DIA_PATH tag allows you to specify the directory where the dia binary resides.
# If left empty dia is assumed to be found in the default search path.
MSCFILE_DIRS =
DIA_PATH =
# The DIAFILE_DIRS tag can be used to specify one or more directories that
# contain dia files that are included in the documentation (see the \diafile
@ -2776,3 +2840,19 @@ GENERATE_LEGEND = YES
# The default value is: YES.
DOT_CLEANUP = YES
# You can define message sequence charts within doxygen comments using the \msc
# command. If the MSCGEN_TOOL tag is left empty (the default), then doxygen will
# use a built-in version of mscgen tool to produce the charts. Alternatively,
# the MSCGEN_TOOL tag can also specify the name an external tool. For instance,
# specifying prog as the value, doxygen will call the tool as prog -T
# <outfile_format> -o <outputfile> <inputfile>. The external tool should support
# output file formats "png", "eps", "svg", and "ismap".
MSCGEN_TOOL =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =

View File

@ -1,149 +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 further information on class specifics.
* [Server](#server)
* [Advertising](#advertising)
* [Client](#client)
* [General](#general)
<br/>
<a name="server"></a>
# Server
`NimBLEService::NimBLEService::createCharacteristic` takes a 3rd parameter to specify the maximum data size that can be stored by the characteristic. This allows for limiting the RAM use of the characteristic in cases where small amounts of data are expected.
<br/>
`NimBLECharacteristic::setValue(const T &s)`
`NimBLEDescriptor::setValue(const T &s)`
Now use the `NimbleAttValue` class and templates to accommodate 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);
// Arduino String support
String myString = "Hello";
pCharacteristic->setValue(myString);
```
This will send the struct to the receiving 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 received. 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 milliseconds), 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).
This provides an opportunity to update the advertisement 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 removed.
`NimBLERemoteCharacteristic::subscribe` and `NimBLERemoteCharacteristic::unsubscribe` have been implemented to replace it.
The internally stored characteristic value is now updated when notification/indication is recieved. Making a callback no longer required to get the most recent value unless timing is important. Instead, the application can call `NimBLERemoteCharacteristic::getValue` to get the most recent value any time.
<br/>
The `notify_callback` function is now defined as a `std::function` to take advantage of using `std::bind` to specify 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 received.
> 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) significantly 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.
Characteristics and descriptors now use the `NimBLEAttValue` class to store their data. This is a polymorphic container class capable of converting to/from many different types efficiently. See: [#286](https://github.com/h2zero/NimBLE-Arduino/pull/286)

View File

@ -4,7 +4,7 @@ This guide describes the required changes to existing projects migrating from th
**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/NimBLE-Arduino/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)
@ -20,12 +20,11 @@ For more information on the improvements and additions please refer to the [clas
* [Remote characteristics](#remote-characteristics)
* [Client Callbacks](#client-callbacks)
* [Security](#client-security)
* [Scanning](#scan-api)
* [BLE scan](#ble-scan)
* [General Security](#security-api)
* [Configuration](#arduino-configuration)
<br/>
<a name="general-information"></a>
## General Information
### Header Files
@ -48,10 +47,9 @@ For example `BLEAddress addr(11:22:33:44:55:66, 1)` will create the address obje
As this parameter is optional no changes to existing code are needed, it is mentioned here for information.
`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.
`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.
@ -72,7 +70,7 @@ void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason)`
```
<br/>
`BLEServerCallbacks::onMtuChanged` (`NimBLEServerCallbacks::onMtuChanged`) takes the parameter `NimBLEConnInfo & connInfo` instead of `esp_ble_gatts_cb_param_t`, which has methods to get information about the connected peer.
`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)
@ -81,13 +79,11 @@ 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.
For example `BLEServer::createService(SERVICE_UUID)` will work just as it did before.
<br/>
<a name="characteristics"></a>
### Characteristics
`BLEService::createCharacteristic` (`NimBLEService::createCharacteristic`) is used the same way as originally except the properties parameter has changed.
@ -137,8 +133,8 @@ BLECharacteristic *pCharacteristic = pService->createCharacteristic(
```
<br/>
<a name="characteristic-callbacks"></a>
#### 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.
@ -168,7 +164,6 @@ my_struct_t myStruct = pChr->getValue<my_struct_t>();
```
<br/>
<a name="descriptors"></a>
### Descriptors
Descriptors are now created using the `NimBLECharacteristic::createDescriptor` method.
@ -179,8 +174,7 @@ NimBLE automatically creates the 0x2902 descriptor if a characteristic has a not
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.
**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.
**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:
@ -197,7 +191,7 @@ NimBLEDescriptor* createDescriptor(NimBLEUUID uuid,
NIMBLE_PROPERTY::WRITE,
uint16_t max_len = 100);
```
##### Example
#### Example
```
pDescriptor = pCharacteristic->createDescriptor("ABCD",
NIMBLE_PROPERTY::READ |
@ -208,27 +202,18 @@ pDescriptor = pCharacteristic->createDescriptor("ABCD",
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/>
<a name="descriptor-callbacks"></a>
#### Descriptor callbacks
> `BLEDescriptorCallbacks::onRead` (`NimBLEDescriptorCallbacks::onRead`)
`BLEDescriptorCallbacks::onwrite` (`NimBLEDescriptorCallbacks::onwrite`)
`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
@ -245,7 +230,6 @@ When a peer wants to read or write a characteristic or descriptor with any of th
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:
@ -255,11 +239,9 @@ Calling `NimBLEAdvertising::setAdvertisementData` will entirely replace any data
> BLEAdvertising::start (NimBLEAdvertising::start)
Now takes 2 optional parameters, the first is the duration to advertise for (in milliseconds), 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).
This provides an opportunity to update the advertisement 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`).
@ -268,15 +250,17 @@ Multiple client instances can be created, up to the maximum number of connection
`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.
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.
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`)
@ -290,7 +274,6 @@ Also now returns a pointer to `std::vector` instead of `std::map`.
**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:
@ -301,12 +284,10 @@ This method has been removed.
> `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:
@ -326,12 +307,12 @@ Has been removed.
Are the new methods added to replace it.
<br/>
> `BLERemoteCharacteristic::readUInt8` (`NimBLERemoteCharacteristic::readUInt8`)
> `BLERemoteCharacteristic::readUInt16` (`NimBLERemoteCharacteristic::readUInt16`)
> `BLERemoteCharacteristic::readUInt32` (`NimBLERemoteCharacteristic::readUInt32`)
> `BLERemoteCharacteristic::readUInt8` (`NimBLERemoteCharacteristic::readUInt8`)
> `BLERemoteCharacteristic::readUInt16` (`NimBLERemoteCharacteristic::readUInt16`)
> `BLERemoteCharacteristic::readUInt32` (`NimBLERemoteCharacteristic::readUInt32`)
> `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`
@ -339,10 +320,10 @@ Are **deprecated** a template: `NimBLERemoteCharacteristic::readValue<type\>(tim
**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, then cast the returned std::string to the type required such as:
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:
```
@ -352,12 +333,10 @@ my_struct_t myStruct = pChr->readValue<my_struct_t>();
> `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).
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-callbacks"></a>
### Client callbacks
> `BLEClientCallbacks::onDisconnect` (`NimBLEClientCallbacks::onDisconnect`)
@ -365,18 +344,20 @@ Also now returns a pointer to `std::vector` instead of `std::map`.
This now takes a second parameter `int reason` which provides the reason code for disconnection.
<br/>
<a name="client-security"></a>
### Client Security
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="scan-api"></a>
## BLE Scan
The scan API is mostly unchanged from the original except for `NimBLEScan::start`, in which the duration parameter is now in milliseconds instead of seconds.
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.
The blocking overload of `NimBLEScan::start` has been replaced by an overload of `NimBLEScan::getResults` with the same parameters.
<br/>
<a name="security-api"></a>
## Security API
Security operations have been moved to `BLEDevice` (`NimBLEDevice`).
The security callback methods are now incorporated in the `NimBLEServerCallbacks` / `NimBLEClientCallbacks` classes.
@ -386,7 +367,7 @@ The callback methods are:
> `bool onConfirmPasskey(NimBLEConnInfo& connInfo, uint32_t pin)`
Receives the pin when using numeric comparison authentication.
Call `NimBLEDevice::injectConfirmPIN(connInfo, true);` to accept or `NimBLEDevice::injectConfirmPIN(connInfo, false);` to reject.
Call `NimBLEDevice::injectConfirmPasskey(connInfo, true);` to accept or `NimBLEDevice::injectConfirmPasskey(connInfo, false);` to reject.
<br/>
> `void onPassKeyEntry(NimBLEConnInfo& connInfo)`
@ -426,7 +407,6 @@ If we are the initiator of the security procedure this sets the keys we will dis
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.

View File

@ -21,7 +21,6 @@ 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 existence for clients to find them and they provide services which contain information for the connecting client.
@ -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();
@ -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 milliseconds 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,9 +150,7 @@ 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();
@ -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,16 +192,16 @@ 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
}
}
}
@ -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 * 1000);
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

@ -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.
@ -14,7 +13,7 @@ It is more suited to resource constrained devices than bluedroid and has now bee
<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.
@ -23,34 +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/>
# 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)
# Sponsors
Thank you to all the sponsors who support this project!
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,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,372 +0,0 @@
/** NimBLE_Client 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);}
static NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTime = 0; /** 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) {
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, int reason) {
printf("%s Disconnected, reason = %d - Starting scan\n",
pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTime);
}
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
void onPassKeyEntry(NimBLEConnInfo& connInfo){
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){
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){
if(!connInfo.isEncrypted()) {
printf("Encrypt connection failed - disconnecting\n");
/** Find the client with the connection handle provided in desc */
NimBLEDevice::getClientByHandle(connInfo.getConnHandle())->disconnect();
return;
}
}
};
/** Define a class to handle the callbacks when advertisments are received */
class scanCallbacks: public NimBLEScanCallbacks {
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;
}
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(NimBLEScanResults results) {
printf("Scan Ended\n");
}
};
/** 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());
}
/** 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::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");
}
/** 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::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(&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 (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 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 removed and replaced with subscribe() / unsubscribe().
* Subscribe parameter defaults are: notifications=true, notifyCallback=nullptr, response=true.
* Unsubscribe parameter defaults are: response=true.
*/
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=true.
* Unsubscribe parameter defaults are: response=true.
*/
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);
}
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->setScanCallbacks (new scanCallbacks());
/** 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 milliseconds) 0 = forever
* Optional callback for when scanning stops.
*/
pScan->start(scanTime);
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,4 +0,0 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)

View File

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

View File

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_extended_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,71 +1,62 @@
/** NimBLE Extended Client Demo:
/**
* NimBLE Extended Client Demo:
*
* Demonstrates the Bluetooth 5.x client capabilities.
*
* Created: on April 2 2022
* Author: H2zero
*
*/
#include <NimBLEDevice.h>
*/
extern "C" void app_main(void);
#include <NimBLEDevice.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
static NimBLEAdvertisedDevice* advDevice;
static bool doConnect = false;
static uint32_t scanTime = 10 * 1000; // In milliseconds, 0 = scan forever
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 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 */
/** Define a class to handle the callbacks for client connection events */
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) {
printf("Connected\n");
};
void onConnect(NimBLEClient* pClient) override { printf("Connected\n"); };
void onDisconnect(NimBLEClient* pClient, int reason) {
printf("%s Disconnected, reason = %d - Starting scan\n",
pClient->getPeerAddress().toString().c_str(), reason);
NimBLEDevice::getScan()->start(scanTime);
};
};
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(NimBLEAdvertisedDevice* advertisedDevice) {
/** 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")))
{
if (advertisedDevice->isAdvertisingService(NimBLEUUID("ABCD"))) {
printf("Found Our Service\n");
/* Ready to connect now */
doConnect = true;
/* Save the device reference in a global for the client to use*/
/** Save the device reference in a global for the client to use*/
advDevice = advertisedDevice;
/* stop scan before connecting */
/** stop scan before connecting */
NimBLEDevice::getScan()->stop();
}
}
/** Callback to process the results of the completed scan or restart it */
void onScanEnd(NimBLEScanResults results) {
printf("Scan Ended\n");
}
};
void onScanEnd(const NimBLEScanResults& results, int rc) override { printf("Scan Ended\n"); }
} scanCallbacks;
/* Handles the provisioning of clients and connects / interfaces with the server */
/** Handles the provisioning of clients and connects / interfaces with the server */
bool connectToServer() {
NimBLEClient* pClient = nullptr;
pClient = NimBLEDevice::createClient();
pClient->setClientCallbacks(new ClientCallbacks, false);
pClient->setClientCallbacks(&clientCallbacks, false);
/* Set the PHY's to use for this connection. This is a bitmask that represents the PHY's:
/**
* 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
@ -77,27 +68,22 @@ bool connectToServer() {
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 */
/** 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());
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;
/** 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) {
// Read the value of the characteristic.
if (pChr->canRead()) {
std::string value = pChr->readValue();
printf("Characteristic value: %s\n", value.c_str());
@ -113,11 +99,37 @@ bool connectToServer() {
return true;
}
void connectTask (void * parameter){
/* Loop here until we find a device we want to connect to */
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) {
/* Found a device we want to connect to, do it now */
if (connectToServer()) {
printf("Success!, scanning for more!\n");
} else {
@ -125,39 +137,8 @@ void connectTask (void * parameter){
}
doConnect = false;
NimBLEDevice::getScan()->start(scanTime);
NimBLEDevice::getScan()->start(scanTimeMs);
}
vTaskDelay(pdMS_TO_TICKS(10));
}
vTaskDelete(NULL);
}
void app_main (void) {
printf("Starting NimBLE Client\n");
/* Create a task to handle connecting to peers */
xTaskCreate(connectTask, "connectTask", 5000, NULL, 1, NULL);
/* Initialize NimBLE, no device name specified as we are not advertising */
NimBLEDevice::init("");
NimBLEScan* pScan = NimBLEDevice::getScan();
/* create a callback that gets called when advertisers are found */
pScan->setScanCallbacks(new 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(scanTime);
printf("Scanning for peripherals\n");
}

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_scan)

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

@ -10,3 +10,4 @@ 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 esp32c3 esp32s3)
project(NimBLE_extended_server)

View File

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_extended_server
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,4 +1,5 @@
/** NimBLE Extended Server Demo:
/**
* NimBLE Extended Server Demo:
*
* Demonstrates the Bluetooth 5.x extended advertising capabilities.
*
@ -9,55 +10,52 @@
*
* Created: on April 2 2022
* Author: H2zero
*
*/
*/
#include "NimBLEDevice.h"
#include "esp_sleep.h"
extern "C" void app_main(void);
#include <NimBLEDevice.h>
#include <esp_sleep.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
/* Time in milliseconds to advertise */
/** Time in milliseconds to advertise */
static uint32_t advTime = 5000;
/* Time to sleep between advertisements */
/** 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 */
/** 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
/**
* 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) {
/** 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) {
printf("Client disconnected - sleeping for %" PRIu32" seconds\n", sleepSeconds);
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 inst_id) {
/** 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", inst_id);
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);
printf("Time expired - sleeping for %" PRIu32 " seconds\n", sleepSeconds);
break;
default:
break;
@ -65,66 +63,69 @@ class advertisingCallbacks: public NimBLEExtAdvertisingCallbacks {
esp_deep_sleep_start();
}
};
} advertisingCallbacks;
void app_main (void) {
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(new ServerCallbacks);
/** 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);
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 services */
/** 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.
*/
/**
* 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 */
/** Set the advertisement as connectable */
extAdv.setConnectable(true);
/* As per Bluetooth specification, extended advertising cannot be both scannable and connectable */
/** 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."));
/** 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.setCompleteServices16({NimBLEUUID(SERVICE_UUID)});
extAdv.setName("Extended advertiser");
/* When extended advertising is enabled `NimBLEDevice::getAdvertising` returns a pointer to `NimBLEExtAdvertising */
/** When extended advertising is enabled `NimBLEDevice::getAdvertising` returns a pointer to `NimBLEExtAdvertising */
NimBLEExtAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/* Set the callbacks for advertising events */
pAdvertising->setCallbacks(new advertisingCallbacks);
/** 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.
/**
* 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.
* 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).
/**
* 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");
@ -132,7 +133,7 @@ void app_main (void) {
printf("Failed to start advertising\n");
}
} else {
printf("Failed to register advertisment data\n");
printf("Failed to register advertisement data\n");
}
esp_sleep_enable_timer_wakeup(sleepSeconds * 1000000);

View File

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

View File

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_multi_advertiser
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,4 +1,5 @@
/** NimBLE Multi Advertiser Demo:
/**
* NimBLE Multi Advertiser Demo:
*
* Demonstrates the Bluetooth 5.x extended advertising capabilities.
*
@ -9,59 +10,56 @@
*
* Created: on April 9 2022
* Author: H2zero
*
*/
*/
#include "NimBLEDevice.h"
#include "esp_sleep.h"
extern "C" void app_main(void);
#include <NimBLEDevice.h>
#include <esp_sleep.h>
#define SERVICE_UUID "ABCD"
#define CHARACTERISTIC_UUID "1234"
/* Time in milliseconds to advertise */
/** Time in milliseconds to advertise */
static uint32_t advTime = 5000;
/* Time to sleep between advertisements */
/** 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 */
/** 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
/**
* 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) {
/** 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) {
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);
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 inst_id) {
/** 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", inst_id);
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);
printf("Time expired - sleeping for %" PRIu32 " seconds\n", sleepTime);
break;
default:
break;
@ -72,90 +70,90 @@ class advCallbacks: public NimBLEExtAdvertisingCallbacks {
bool m_updatedSR = false;
void onScanRequest(NimBLEExtAdvertising* pAdv, uint8_t inst_id, NimBLEAddress addr) {
printf("Scan request for instance %u\n", inst_id);
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(inst_id, sr);
pAdv->setScanResponseData(instId, sr);
m_updatedSR = true;
}
}
};
} advCallbacks;
void app_main (void) {
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(new ServerCallbacks);
/** 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);
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 */
/** Start the service */
pService->start();
/* Create our multi advertising instances */
/** Create our multi advertising instances */
// extended scannable instance advertising on coded and 1m PHY's.
/** extended scannable instance advertising on coded and 1m PHY's. */
NimBLEExtAdvertisement extScannable(primaryPhy, secondaryPhy);
// Legacy advertising as a connectable device.
/** Legacy advertising as a connectable device. */
NimBLEExtAdvertisement legacyConnectable;
// Optional scan response data.
/** Optional scan response data. */
NimBLEExtAdvertisement legacyScanResponse;
/* As per Bluetooth specification, extended advertising cannot be both scannable and connectable */
/** As per Bluetooth specification, extended advertising cannot be both scannable and connectable */
extScannable.setScannable(true);
extScannable.setConnectable(false);
/* Set the initial data */
/** 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. */
/** Enable the scan response callback, we will use this to update the data. */
extScannable.enableScanRequestCallback(true);
/* Optional custom address for this advertisment. */
/** Optional custom address for this advertisment. */
legacyConnectable.setAddress(NimBLEAddress("DE:AD:BE:EF:BA:AD"));
/* Set the advertising data. */
/** Set the advertising data. */
legacyConnectable.setName("Legacy");
legacyConnectable.setCompleteServices16({NimBLEUUID(SERVICE_UUID)});
/* Set the legacy and connectable flags. */
/** Set the legacy and connectable flags. */
legacyConnectable.setLegacyAdvertising(true);
legacyConnectable.setConnectable(true);
/* Put some data in the scan response if desired. */
/** Put some data in the scan response if desired. */
legacyScanResponse.setServiceData(NimBLEUUID(SERVICE_UUID), "Legacy SR");
/* Get the advertising ready */
/** Get the advertising ready */
NimBLEExtAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/* Set the callbacks to handle advertising events */
pAdvertising->setCallbacks(new advCallbacks);
/** 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.
/**
* 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).
* 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->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");
@ -163,7 +161,7 @@ void app_main (void) {
printf("Failed to start advertising\n");
}
} else {
printf("Failed to register advertisment data\n");
printf("Failed to register advertisement data\n");
}
esp_sleep_enable_timer_wakeup(sleepTime * 1000000);

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(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

@ -1,3 +0,0 @@
PROJECT_NAME := NimBLE_Async_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

@ -6,7 +6,6 @@
*
* Created: on November 4, 2024
* Author: H2zero
*
*/
#include <NimBLEDevice.h>
@ -14,22 +13,23 @@
static constexpr uint32_t scanTimeMs = 5 * 1000;
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) {
void onConnect(NimBLEClient* pClient) override {
printf("Connected to: %s\n", pClient->getPeerAddress().toString().c_str());
}
void onDisconnect(NimBLEClient* pClient, int reason) {
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);
}
} clientCB;
} clientCallbacks;
class scanCallbacks : public NimBLEScanCallbacks {
void onResult(NimBLEAdvertisedDevice* advertisedDevice) {
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());
@ -39,7 +39,7 @@ class scanCallbacks : public NimBLEScanCallbacks {
}
}
pClient->setClientCallbacks(&clientCB, false);
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");
@ -48,19 +48,19 @@ class scanCallbacks : public NimBLEScanCallbacks {
}
}
void onScanEnd(NimBLEScanResults results) {
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("");
NimBLEDevice::init("Async-Client");
NimBLEDevice::setPower(3); /** +3db */
NimBLEScan* pScan = NimBLEDevice::getScan();
pScan->setScanCallbacks(new scanCallbacks());
pScan->setScanCallbacks(&scanCallbacks);
pScan->setInterval(45);
pScan->setWindow(15);
pScan->setActiveScan(true);

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

@ -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

@ -1,224 +1,186 @@
/** NimBLE_Server Demo:
/**
* 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);}
#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) {
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.
/**
* 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.
* Timeout: 10 millisecond increments.
*/
pServer->updateConnParams(connInfo.getConnHandle(), 24, 48, 0, 18);
};
pServer->updateConnParams(connInfo.getConnHandle(), 24, 48, 0, 180);
}
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) {
void onDisconnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, int reason) override {
printf("Client disconnected - start advertising\n");
NimBLEDevice::startAdvertising();
};
}
void onMTUChange(uint16_t MTU, NimBLEConnInfo& connInfo) {
void onMTUChange(uint16_t MTU, NimBLEConnInfo& connInfo) override {
printf("MTU updated: %u for connection ID: %u\n", MTU, connInfo.getConnHandle());
pServer->updateConnParams(connInfo.getConnHandle(), 24, 48, 0, 60);
};
}
/********************* Security handled here **********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyDisplay(){
/********************* Security handled here *********************/
uint32_t onPassKeyDisplay() override {
printf("Server Passkey Display\n");
/** This should return a random 6 digit number for security
/**
* This should return a random 6 digit number for security
* or make your own static passkey as done here.
*/
return 123456;
};
}
void onConfirmasskeyN(NimBLEConnInfo& connInfo, uint32_t pass_key){
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){
void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
/** Check that encryption was successful, if not we disconnect the client */
if(!connInfo.isEncrypted()) {
if (!connInfo.isEncrypted()) {
NimBLEDevice::getServer()->disconnect(connInfo.getConnHandle());
printf("Encrypt connection failed - disconnecting client\n");
return;
}
printf("Starting BLE work!");
};
};
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) {
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) {
void onWrite(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override {
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 value returned in code is the NimBLE host return code.
*/
void onStatus(NimBLECharacteristic* pCharacteristic, int code) {
printf("Notification/Indication return code: %d, %s\n",
code, NimBLEUtils::returnCodeToString(code));
void onStatus(NimBLECharacteristic* pCharacteristic, int code) override {
printf("Notification/Indication return code: %d, %s\n", code, NimBLEUtils::returnCodeToString(code));
}
void onSubscribe(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, uint16_t subValue) {
std::string str = "Client ID: ";
str += connInfo.getConnHandle();
str += " Address: ";
str += connInfo.getAddress().toString();
if(subValue == 0) {
/** 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 notfications for ";
} else if(subValue == 2) {
} else if (subValue == 1) {
str += " Subscribed to notifications for ";
} else if (subValue == 2) {
str += " Subscribed to indications for ";
} else if(subValue == 3) {
} 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) {
void onWrite(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
std::string dscVal = pDescriptor->getValue();
printf("Descriptor witten value: %s\n", dscVal.c_str());
};
void onRead(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) {
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();
}
}
}
vTaskDelay(2000/portTICK_PERIOD_MS);
printf("Descriptor written value: %s\n", dscVal.c_str());
}
vTaskDelete(NULL);
}
void onRead(NimBLEDescriptor* pDescriptor, NimBLEConnInfo& connInfo) override {
printf("%s Descriptor read\n", pDescriptor->getUUID().toString().c_str());
}
} dscCallbacks;
void app_main(void) {
extern "C" void app_main(void) {
printf("Starting NimBLE Server\n");
/** sets device name */
/** 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.
/**
* 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
// 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.
/**
* 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(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());
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
);
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
/**
* 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");
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
);
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
);
/** 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);
@ -226,17 +188,31 @@ void app_main(void) {
pDeadService->start();
pBaadService->start();
/** Create an advertising instance and add the services to the advertised data */
NimBLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
/** Add the services to the advertisment data **/
pAdvertising->setName("NimBLE-Server");
pAdvertising->addServiceUUID(pDeadService->getUUID());
pAdvertising->addServiceUUID(pBaadService->getUUID());
/** If your device is battery powered you may consider setting scan response
/**
* 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->enableScanResponse(true);
pAdvertising->start();
printf("Advertising Started\n");
xTaskCreate(notifyTask, "notifyTask", 5000, NULL, 1, NULL);
/** 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

@ -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(NimBLE_server_get_client_name)

View File

@ -1,83 +0,0 @@
/** NimBLE_server_get_client_name
*
* Demonstrates 2 ways for the server to read the device name from the connected client.
*
* Created: on June 24 2024
* Author: H2zero
*
*/
#include <NimBLEDevice.h>
// 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"
#define ENC_CHARACTERISTIC_UUID "9551f35b-8d91-42e4-8f7e-1358dfe272dc"
NimBLEServer* pServer;
class ServerCallbacks : public NimBLEServerCallbacks {
// Same as before but now includes the name parameter
void onConnect(NimBLEServer* pServer, NimBLEConnInfo& connInfo, std::string& name) override {
printf("Client address: %s Name: %s\n", connInfo.getAddress().toString().c_str(), name.c_str());
}
// Same as before but now includes the name parameter
void onAuthenticationComplete(NimBLEConnInfo& connInfo, const std::string& name) override {
if (!connInfo.isEncrypted()) {
NimBLEDevice::getServer()->disconnect(connInfo.getConnHandle());
printf("Encrypt connection failed - disconnecting client\n");
return;
}
printf("Encrypted Client address: %s Name: %s\n", connInfo.getAddress().toString().c_str(), name.c_str());
}
};
extern "C" void app_main(void) {
printf("Starting BLE Server!\n");
NimBLEDevice::init("Connect to me!");
NimBLEDevice::setSecurityAuth(true, false, true); // Enable bonding to see full name on phones.
pServer = NimBLEDevice::createServer();
NimBLEService* pService = pServer->createService(SERVICE_UUID);
NimBLECharacteristic* pCharacteristic =
pService->createCharacteristic(CHARACTERISTIC_UUID, NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE);
pCharacteristic->setValue("Hello World says NimBLE!");
NimBLECharacteristic* pEncCharacteristic = pService->createCharacteristic(
ENC_CHARACTERISTIC_UUID,
(NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::READ_ENC | NIMBLE_PROPERTY::WRITE_ENC));
pEncCharacteristic->setValue("Hello World says NimBLE Encrypted");
pService->start();
pServer->setCallbacks(new ServerCallbacks());
pServer->getPeerNameOnConnect(true); // Setting this will enable the onConnect callback that provides the name.
BLEAdvertising* pAdvertising = NimBLEDevice::getAdvertising();
pAdvertising->addServiceUUID(SERVICE_UUID);
pAdvertising->setScanResponse(true);
pAdvertising->start();
printf("Advertising started, connect with your phone.\n");
while (true) {
auto clientCount = pServer->getConnectedCount();
if (clientCount) {
printf("Connected clients:\n");
for (auto i = 0; i < clientCount; ++i) {
NimBLEConnInfo peerInfo = pServer->getPeerInfo(i);
printf("Client address: %s Name: %s\n", peerInfo.getAddress().toString().c_str(),
// This function blocks until the name is retrieved, so cannot be used in callback functions.
pServer->getPeerName(peerInfo).c_str());
}
}
vTaskDelay(pdMS_TO_TICKS(10000));
}
}

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_client)

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,214 +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) {
}
/** onDisconnect now takes a reason parameter to indicate the reason for disconnection
void onDisconnect(BLEClient* pclient) { */
void onDisconnect(BLEClient* pclient, int reason) {
connected = false;
printf("onDisconnect");
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
void onPassKeyEntry(NimBLEConnInfo& connInfo){
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){
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){
if(!connInfo.isEncrypted()) {
printf("Encrypt connection failed - disconnecting\n");
/** Find the client with the connection handle provided in desc */
NimBLEDevice::getClientByHandle(connInfo.getConnHandle())->disconnect();
return;
}
}
/*******************************************************************/
};
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 removed and replaced with subscribe() / unsubscribe().
* Subscribe parameter defaults are: notifications=true, notifyCallback=nullptr, response=true.
* Unsubscribe parameter defaults are: response=true.
*/
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
}
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->setScanCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
xTaskCreate(connectTask, "connectTask", 5000, NULL, 1, NULL);
pBLEScan->start(5 * 1000, false);
} // End of setup.

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_notify)

View File

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

View File

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

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,164 +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, BLEConnInfo& connInfo) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer, BLEConnInfo& connInfo, int reason) {
deviceConnected = false;
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyDisplay(){
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){
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){
/** 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("Starting BLE work!");
};
/*******************************************************************/
};
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
);
// 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,12 +0,0 @@
# 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_scan
include $(IDF_PATH)/make/project.mk

View File

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

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 * 1000; // In milliseconds, 0 = scan forever
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->getResults(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->setScanCallbacks(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,12 +0,0 @@
# 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,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,3 +0,0 @@
PROJECT_NAME := BLE_server
include $(IDF_PATH)/make/project.mk

View File

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

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,12 +0,0 @@
# 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_uart
include $(IDF_PATH)/make/project.mk

View File

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

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,177 +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, BLEConnInfo& connInfo) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer, BLEConnInfo& connInfo, int reason) {
deviceConnected = false;
}
/***************** New - Security handled here ********************
****** Note: these are the same return values as defaults ********/
uint32_t onPassKeyDisplay(){
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){
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){
/** 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("Starting BLE work!");
};
/*******************************************************************/
};
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic, BLEConnInfo& connInfo) {
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");
}

View File

@ -1,12 +0,0 @@
# 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,15 +1,24 @@
## IDF Component Manager Manifest File
version: "2.2.0"
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: "*"
version: "<0.5.4"
rules:
- if: "target in [esp32p4]"
## Required IDF version
idf:
version: ">=5.3.0"
rules:

23
library.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "esp-nimble-cpp",
"version": "2.2.0",
"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,17 +0,0 @@
{
"name": "esp-nimble-cpp",
"version": "1.5.0",
"description": "NimBLE, BLE stack for the Espressif ESP32, ESP32-S and ESP32-C series of SoCs",
"keywords": [
"BLE",
"espidf",
"arduino",
"espressif",
"esp32"
],
"license": "LGPL-2.1-or-later",
"repository": {
"type": "git",
"url": "https://github.com/h2zero/esp-nimble-cpp"
}
}

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)

View File

@ -1,82 +1,74 @@
/*
* 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.
*/
#include "nimconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#include "NimBLE2904.h"
NimBLE2904::NimBLE2904(NimBLECharacteristic* pCharacteristic)
: NimBLEDescriptor(NimBLEUUID((uint16_t) 0x2904),
BLE_GATT_CHR_F_READ,
sizeof(BLE2904_Data),
pCharacteristic)
{
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
# include "NimBLE2904.h"
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 /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL */

View File

@ -1,42 +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_
#ifndef NIMBLE_CPP_2904_H_
#define NIMBLE_CPP_2904_H_
#include "nimconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(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.
*/
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;
@ -64,17 +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 /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL */
#endif /* MAIN_NIMBLE2904_H_ */
#endif // CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL
#endif // NIMBLE_CPP_2904_H_

View File

@ -1,16 +1,20 @@
/*
* 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 "nimconfig.h"
#if defined(CONFIG_BT_ENABLED)
@ -19,6 +23,18 @@
# 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";
/*************************************************
@ -41,7 +57,9 @@ NimBLEAddress::NimBLEAddress(ble_addr_t address) : ble_addr_t{address} {}
* ```
* which is 17 characters in length.
* @param [in] addr The hex string representation of 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 std::string& addr, uint8_t type) {
this->type = type;
@ -55,7 +73,7 @@ NimBLEAddress::NimBLEAddress(const std::string& addr, uint8_t type) {
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);
memcpy(this->val, &address, sizeof(this->val));
return;
}
@ -66,7 +84,9 @@ NimBLEAddress::NimBLEAddress(const std::string& addr, uint8_t type) {
/**
* @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(const uint8_t address[BLE_DEV_ADDR_LEN], uint8_t type) {
std::reverse_copy(address, address + BLE_DEV_ADDR_LEN, this->val);
@ -77,10 +97,12 @@ NimBLEAddress::NimBLEAddress(const uint8_t address[BLE_DEV_ADDR_LEN], uint8_t ty
* @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(this->val, &address, sizeof this->val);
memcpy(this->val, &address, sizeof(this->val));
this->type = type;
} // NimBLEAddress
@ -183,7 +205,7 @@ bool NimBLEAddress::operator==(const NimBLEAddress& rhs) const {
return false;
}
return memcmp(rhs.val, this->val, sizeof this->val) == 0;
return memcmp(rhs.val, this->val, sizeof(this->val)) == 0;
} // operator ==
/**
@ -201,12 +223,12 @@ NimBLEAddress::operator std::string() const {
char buffer[18];
snprintf(buffer,
sizeof(buffer),
"%02x:%02x:%02x:%02x:%02x:%02x",
this->val[5],
this->val[4],
this->val[3],
this->val[2],
this->val[1],
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
@ -216,7 +238,7 @@ NimBLEAddress::operator std::string() const {
*/
NimBLEAddress::operator uint64_t() const {
uint64_t address = 0;
memcpy(&address, this->val, sizeof this->val);
memcpy(&address, this->val, sizeof(this->val));
return address;
} // operator uint64_t

View File

@ -1,15 +1,18 @@
/*
* 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 NIMBLE_CPP_ADDRESS_H_
@ -31,9 +34,9 @@
# 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 : private ble_addr_t {
public:
@ -42,9 +45,9 @@ class NimBLEAddress : private ble_addr_t {
*/
NimBLEAddress() = default;
NimBLEAddress(const ble_addr_t address);
NimBLEAddress(const uint8_t address[BLE_DEV_ADDR_LEN], 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);
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 isRpa() const;
bool isNrpa() const;
@ -59,8 +62,8 @@ class NimBLEAddress : private ble_addr_t {
const NimBLEAddress& reverseByteOrder();
bool operator==(const NimBLEAddress& rhs) const;
bool operator!=(const NimBLEAddress& rhs) const;
operator std::string() const;
operator uint64_t() const;
operator std::string() const;
operator uint64_t() const;
};
#endif /* CONFIG_BT_ENABLED */

View File

@ -1,15 +1,18 @@
/*
* NimBLEAdvertisedDevice.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
*
* BLEAdvertisedDevice.cpp
*
* 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.
*/
#include "nimconfig.h"
@ -757,6 +760,14 @@ bool NimBLEAdvertisedDevice::isConnectable() const {
return (m_advType & BLE_HCI_ADV_CONN_MASK) || (m_advType & BLE_HCI_ADV_DIRECT_MASK);
} // isConnectable
/**
* @brief Check if this device is advertising as scannable.
* @return True if the device is scannable.
*/
bool NimBLEAdvertisedDevice::isScannable() const {
return isLegacyAdvertisement() && (m_advType == BLE_HCI_ADV_TYPE_ADV_IND || m_advType == BLE_HCI_ADV_TYPE_ADV_SCAN_IND);
} // isScannable
/**
* @brief Check if this advertisement is a legacy or extended type
* @return True if legacy (Bluetooth 4.x), false if extended (bluetooth 5.x).
@ -769,6 +780,16 @@ bool NimBLEAdvertisedDevice::isLegacyAdvertisement() const {
# endif
} // isLegacyAdvertisement
/**
* @brief Convenience operator to convert this NimBLEAdvertisedDevice to NimBLEAddress representation.
* @details This allows passing NimBLEAdvertisedDevice to functions
* that accept NimBLEAddress and/or or it's methods as a parameter.
*/
NimBLEAdvertisedDevice::operator NimBLEAddress() const {
NimBLEAddress address(getAddress());
return address;
} // operator NimBLEAddress
/**
* @brief Get the payload advertised by the device.
* @return The advertisement payload.

View File

@ -1,15 +1,18 @@
/*
* 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 NIMBLE_CPP_ADVERTISED_DEVICE_H_
@ -82,6 +85,7 @@ class NimBLEAdvertisedDevice {
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;
@ -89,6 +93,7 @@ class NimBLEAdvertisedDevice {
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;

View File

@ -0,0 +1,588 @@
/*
* 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 "nimconfig.h"
#if (defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER) && !CONFIG_BT_NIMBLE_EXT_ADV) || \
defined(_DOXYGEN_)
# include "NimBLEAdvertisementData.h"
# 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

View File

@ -0,0 +1,79 @@
/*
* 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.
*/
#ifndef NIMBLE_CPP_ADVERTISEMENT_DATA_H_
#define NIMBLE_CPP_ADVERTISEMENT_DATA_H_
#include "nimconfig.h"
#if (defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER) && !CONFIG_BT_NIMBLE_EXT_ADV) || \
defined(_DOXYGEN_)
# include <cstdint>
# include <string>
# include <vector>
class NimBLEUUID;
/**
* @brief Advertisement data set by the programmer to be published by the BLE server.
*/
class NimBLEAdvertisementData {
// Only a subset of the possible BLE architected advertisement fields are currently exposed. Others will
// be exposed on demand/request or as time permits.
//
public:
bool addData(const uint8_t* data, size_t length);
bool addData(const std::vector<uint8_t>& data);
bool setAppearance(uint16_t appearance);
bool setFlags(uint8_t flag);
bool addTxPower();
bool setPreferredParams(uint16_t minInterval, uint16_t maxInterval);
bool addServiceUUID(const NimBLEUUID& serviceUUID);
bool addServiceUUID(const char* serviceUUID);
bool removeServiceUUID(const NimBLEUUID& serviceUUID);
bool removeServiceUUID(const char* serviceUUID);
bool removeServices();
bool setManufacturerData(const uint8_t* data, size_t length);
bool setManufacturerData(const std::string& data);
bool setManufacturerData(const std::vector<uint8_t>& data);
bool setURI(const std::string& uri);
bool setName(const std::string& name, bool isComplete = true);
bool setShortName(const std::string& name);
bool setCompleteServices(const NimBLEUUID& uuid);
bool setCompleteServices16(const std::vector<NimBLEUUID>& uuids);
bool setCompleteServices32(const std::vector<NimBLEUUID>& uuids);
bool setPartialServices(const NimBLEUUID& uuid);
bool setPartialServices16(const std::vector<NimBLEUUID>& uuids);
bool setPartialServices32(const std::vector<NimBLEUUID>& uuids);
bool setServiceData(const NimBLEUUID& uuid, const uint8_t* data, size_t length);
bool setServiceData(const NimBLEUUID& uuid, const std::string& data);
bool setServiceData(const NimBLEUUID& uuid, const std::vector<uint8_t>& data);
bool removeData(uint8_t type);
void clearData();
int getDataLocation(uint8_t type) const;
std::string toString() const;
std::vector<uint8_t> getPayload() const;
private:
friend class NimBLEAdvertising;
bool setServices(bool complete, uint8_t size, const std::vector<NimBLEUUID>& v_uuid);
std::vector<uint8_t> m_payload{};
}; // NimBLEAdvertisementData
#endif // CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_BROADCASTER && !CONFIG_BT_NIMBLE_EXT_ADV
#endif // NIMBLE_CPP_ADVERTISEMENT_DATA_H_

File diff suppressed because it is too large Load Diff

View File

@ -1,150 +1,110 @@
/*
* NimBLEAdvertising.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on March 3, 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
*
* BLEAdvertising.h
*
* Created on: Jun 21, 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_BLEADVERTISING_H_
#define MAIN_BLEADVERTISING_H_
#include "nimconfig.h"
#if (defined(CONFIG_BT_ENABLED) && \
defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER) && \
!CONFIG_BT_NIMBLE_EXT_ADV) || defined(_DOXYGEN_)
#ifndef NIMBLE_CPP_ADVERTISING_H_
#define NIMBLE_CPP_ADVERTISING_H_
#if defined(CONFIG_NIMBLE_CPP_IDF)
#include "host/ble_gap.h"
#else
#include "nimble/nimble/host/include/host/ble_gap.h"
#endif
#include "nimconfig.h"
#if (defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER) && !CONFIG_BT_NIMBLE_EXT_ADV) || \
defined(_DOXYGEN_)
# if defined(CONFIG_NIMBLE_CPP_IDF)
# include "host/ble_gap.h"
# else
# include "nimble/nimble/host/include/host/ble_gap.h"
# endif
/**** FIX COMPILATION ****/
#undef min
#undef max
# undef min
# undef max
/**************************/
#include "NimBLEUUID.h"
#include "NimBLEAddress.h"
# include "NimBLEUUID.h"
# include "NimBLEAddress.h"
# include "NimBLEAdvertisementData.h"
#include <functional>
#include <vector>
/* COMPATIBILITY - DO NOT USE */
#define ESP_BLE_ADV_FLAG_LIMIT_DISC (0x01 << 0)
#define ESP_BLE_ADV_FLAG_GEN_DISC (0x01 << 1)
#define ESP_BLE_ADV_FLAG_BREDR_NOT_SPT (0x01 << 2)
#define ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT (0x01 << 3)
#define ESP_BLE_ADV_FLAG_DMT_HOST_SPT (0x01 << 4)
#define ESP_BLE_ADV_FLAG_NON_LIMIT_DISC (0x00 )
/* ************************* */
# include <functional>
# include <string>
# include <vector>
class NimBLEAdvertising;
typedef std::function<void(NimBLEAdvertising*)> advCompleteCB_t;
/**
* @brief Advertisement data set by the programmer to be published by the %BLE server.
*/
class NimBLEAdvertisementData {
// Only a subset of the possible BLE architected advertisement fields are currently exposed. Others will
// be exposed on demand/request or as time permits.
//
public:
void setAppearance(uint16_t appearance);
void setCompleteServices(const NimBLEUUID &uuid);
void setCompleteServices16(const std::vector<NimBLEUUID> &v_uuid);
void setCompleteServices32(const std::vector<NimBLEUUID> &v_uuid);
void setFlags(uint8_t);
void setManufacturerData(const std::string &data);
void setManufacturerData(const std::vector<uint8_t> &data);
void setURI(const std::string &uri);
void setName(const std::string &name);
void setPartialServices(const NimBLEUUID &uuid);
void setPartialServices16(const std::vector<NimBLEUUID> &v_uuid);
void setPartialServices32(const std::vector<NimBLEUUID> &v_uuid);
void setServiceData(const NimBLEUUID &uuid, const std::string &data);
void setShortName(const std::string &name);
void addData(const std::string &data); // Add data to the payload.
void addData(char * data, size_t length);
void addTxPower();
void setPreferredParams(uint16_t min, uint16_t max);
std::string getPayload(); // Retrieve the current advert payload.
void clearData(); // Clear the advertisement data.
private:
friend class NimBLEAdvertising;
void setServices(const bool complete, const uint8_t size,
const std::vector<NimBLEUUID> &v_uuid);
std::string m_payload; // The payload of the advertisement.
}; // NimBLEAdvertisementData
/**
* @brief Perform and manage %BLE advertising.
* @brief Perform and manage BLE advertising.
*
* A %BLE server will want to perform advertising in order to make itself known to %BLE clients.
* A BLE server will want to perform advertising in order to make itself known to BLE clients.
*/
class NimBLEAdvertising {
public:
public:
NimBLEAdvertising();
void addServiceUUID(const NimBLEUUID &serviceUUID);
void addServiceUUID(const char* serviceUUID);
void removeServiceUUID(const NimBLEUUID &serviceUUID);
bool start(uint32_t duration = 0, advCompleteCB_t advCompleteCB = nullptr, NimBLEAddress* dirAddr = nullptr);
void removeServices();
bool start(uint32_t duration = 0, const NimBLEAddress* dirAddr = nullptr);
void setAdvertisingCompleteCallback(advCompleteCB_t callback);
bool stop();
void setAppearance(uint16_t appearance);
void setName(const std::string &name);
void setManufacturerData(const std::string &data);
void setManufacturerData(const std::vector<uint8_t> &data);
void setURI(const std::string &uri);
void setServiceData(const NimBLEUUID &uuid, const std::string &data);
void setAdvertisementType(uint8_t adv_type);
void setMaxInterval(uint16_t maxinterval);
void setMinInterval(uint16_t mininterval);
void setAdvertisementData(NimBLEAdvertisementData& advertisementData);
void setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly);
void setScanResponseData(NimBLEAdvertisementData& advertisementData);
void setScanResponse(bool);
void setMinPreferred(uint16_t);
void setMaxPreferred(uint16_t);
void addTxPower();
void reset();
void advCompleteCB();
bool setConnectableMode(uint8_t mode);
bool setDiscoverableMode(uint8_t mode);
bool reset();
bool isAdvertising();
void setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly);
void enableScanResponse(bool enable);
void setAdvertisingInterval(uint16_t interval);
void setMaxInterval(uint16_t maxInterval);
void setMinInterval(uint16_t minInterval);
private:
bool setAdvertisementData(const NimBLEAdvertisementData& advertisementData);
bool setScanResponseData(const NimBLEAdvertisementData& advertisementData);
const NimBLEAdvertisementData& getAdvertisementData();
const NimBLEAdvertisementData& getScanData();
void clearData();
bool refreshAdvertisingData();
bool addServiceUUID(const NimBLEUUID& serviceUUID);
bool addServiceUUID(const char* serviceUUID);
bool removeServiceUUID(const NimBLEUUID& serviceUUID);
bool removeServiceUUID(const char* serviceUUID);
bool removeServices();
bool setAppearance(uint16_t appearance);
bool setPreferredParams(uint16_t minInterval, uint16_t maxInterval);
bool addTxPower();
bool setName(const std::string& name);
bool setManufacturerData(const uint8_t* data, size_t length);
bool setManufacturerData(const std::string& data);
bool setManufacturerData(const std::vector<uint8_t>& data);
bool setURI(const std::string& uri);
bool setServiceData(const NimBLEUUID& uuid, const uint8_t* data, size_t length);
bool setServiceData(const NimBLEUUID& uuid, const std::string& data);
bool setServiceData(const NimBLEUUID& uuid, const std::vector<uint8_t>& data);
private:
friend class NimBLEDevice;
friend class NimBLEServer;
void onHostSync();
static int handleGapEvent(struct ble_gap_event *event, void *arg);
void onHostSync();
static int handleGapEvent(ble_gap_event* event, void* arg);
ble_hs_adv_fields m_advData;
ble_hs_adv_fields m_scanData;
NimBLEAdvertisementData m_advData;
NimBLEAdvertisementData m_scanData;
ble_gap_adv_params m_advParams;
std::vector<NimBLEUUID> m_serviceUUIDs;
bool m_customAdvData;
bool m_customScanResponseData;
bool m_scanResp;
bool m_advDataSet;
advCompleteCB_t m_advCompCB{nullptr};
advCompleteCB_t m_advCompCb;
uint8_t m_slaveItvl[4];
uint32_t m_duration;
std::vector<uint8_t> m_svcData16;
std::vector<uint8_t> m_svcData32;
std::vector<uint8_t> m_svcData128;
std::vector<uint8_t> m_name;
std::vector<uint8_t> m_mfgData;
std::vector<uint8_t> m_uri;
bool m_scanResp : 1;
bool m_advDataSet : 1;
};
#endif /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_BROADCASTER && !CONFIG_BT_NIMBLE_EXT_ADV */
#endif /* MAIN_BLEADVERTISING_H_ */
#endif /* NIMBLE_CPP_ADVERTISING_H_ */

View File

@ -1,9 +1,18 @@
/*
* NimBLEAttValue.cpp
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on July 17, 2024
* 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
*
* 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 "nimconfig.h"
@ -16,6 +25,9 @@
# endif
# include "NimBLEAttValue.h"
# include "NimBLELog.h"
static const char* LOG_TAG = "NimBLEAttValue";
// Default constructor implementation.
NimBLEAttValue::NimBLEAttValue(uint16_t init_len, uint16_t max_len)
@ -29,14 +41,17 @@ NimBLEAttValue::NimBLEAttValue(uint16_t init_len, uint16_t max_len)
# endif
{
NIMBLE_CPP_DEBUG_ASSERT(m_attr_value);
if (m_attr_value == nullptr) {
NIMBLE_LOGE(LOG_TAG, "Failed to calloc ctx");
}
}
// Value constructor implementation.
NimBLEAttValue::NimBLEAttValue(const uint8_t *value, uint16_t len, uint16_t max_len)
: NimBLEAttValue(len, max_len) {
memcpy(m_attr_value, value, len);
m_attr_value[len] = '\0';
m_attr_len = len;
NimBLEAttValue::NimBLEAttValue(const uint8_t* value, uint16_t len, uint16_t max_len) : NimBLEAttValue(len, max_len) {
if (m_attr_value != nullptr) {
memcpy(m_attr_value, value, len);
m_attr_len = len;
}
}
// Destructor implementation.
@ -73,6 +88,10 @@ NimBLEAttValue& NimBLEAttValue::operator=(const NimBLEAttValue& source) {
void NimBLEAttValue::deepCopy(const NimBLEAttValue& source) {
uint8_t* res = static_cast<uint8_t*>(realloc(m_attr_value, source.m_capacity + 1));
NIMBLE_CPP_DEBUG_ASSERT(res);
if (res == nullptr) {
NIMBLE_LOGE(LOG_TAG, "Failed to realloc deepCopy");
return;
}
ble_npl_hw_enter_critical();
m_attr_value = res;
@ -98,7 +117,7 @@ NimBLEAttValue& NimBLEAttValue::append(const uint8_t* value, uint16_t len) {
}
if ((m_attr_len + len) > m_attr_max_len) {
NIMBLE_LOGE("NimBLEAttValue", "val > max, len=%u, max=%u", len, m_attr_max_len);
NIMBLE_LOGE(LOG_TAG, "val > max, len=%u, max=%u", len, m_attr_max_len);
return *this;
}
@ -109,6 +128,10 @@ NimBLEAttValue& NimBLEAttValue::append(const uint8_t* value, uint16_t len) {
m_capacity = new_len;
}
NIMBLE_CPP_DEBUG_ASSERT(res);
if (res == nullptr) {
NIMBLE_LOGE(LOG_TAG, "Failed to realloc append");
return *this;
}
# if CONFIG_NIMBLE_CPP_ATT_VALUE_TIMESTAMP_ENABLED
time_t t = time(nullptr);
@ -127,4 +150,13 @@ NimBLEAttValue& NimBLEAttValue::append(const uint8_t* value, uint16_t len) {
return *this;
}
uint8_t NimBLEAttValue::operator[](int pos) const {
NIMBLE_CPP_DEBUG_ASSERT(pos < m_attr_len);
if (pos >= m_attr_len) {
NIMBLE_LOGE(LOG_TAG, "pos >= len, pos=%u, len=%u", pos, m_attr_len);
return 0;
}
return m_attr_value[pos];
}
#endif // CONFIG_BT_ENABLED

View File

@ -1,9 +1,18 @@
/*
* NimBLEAttValue.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on March 18, 2021
* 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
*
* 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.
*/
#ifndef NIMBLE_CPP_ATTVALUE_H
@ -15,7 +24,6 @@
# include <Arduino.h>
# endif
# include "NimBLELog.h"
# include <string>
# include <vector>
# include <ctime>
@ -84,16 +92,15 @@ class NimBLEAttValue {
* @param[in] len The size in bytes of the value to set.
* @param[in] max_len The max size in bytes that the value can be.
*/
NimBLEAttValue(const uint8_t *value, uint16_t len,
uint16_t max_len = BLE_ATT_ATTR_MAX_LEN);
NimBLEAttValue(const uint8_t* value, uint16_t len, uint16_t max_len = BLE_ATT_ATTR_MAX_LEN);
/**
* @brief Construct with an initial value from a const char string.
* @param value A pointer to the initial value to set.
* @param[in] max_len The max size in bytes that the value can be.
*/
NimBLEAttValue(const char *value, uint16_t max_len = BLE_ATT_ATTR_MAX_LEN)
:NimBLEAttValue((uint8_t*)value, (uint16_t)strlen(value), max_len){}
NimBLEAttValue(const char* value, uint16_t max_len = BLE_ATT_ATTR_MAX_LEN)
: NimBLEAttValue((uint8_t*)value, (uint16_t)strlen(value), max_len) {}
/**
* @brief Construct with an initializer list.
@ -221,14 +228,61 @@ class NimBLEAttValue {
/*********************** Template Functions ************************/
# if __cplusplus < 201703L
/**
* @brief Template to set value to the value of <type\>val.
* @param [in] v The <type\>value to set.
* @details Only used for types without a `c_str()` and `length()` or `data()` and `size()` method.
* <type\> size must be evaluatable by `sizeof()`.
*/
template <typename T>
# ifdef _DOXYGEN_
bool
# else
typename std::enable_if<!std::is_pointer<T>::value && !Has_c_str_length<T>::value && !Has_data_size<T>::value, bool>::type
# endif
setValue(const T& v) {
return setValue(reinterpret_cast<const uint8_t*>(&v), sizeof(T));
}
/**
* @brief Template to set value to the value of <type\>val.
* @param [in] s The <type\>value to set.
* @note This function is only availabe if the type T is not a pointer.
* @details Only used if the <type\> has a `c_str()` method.
*/
template <typename T>
typename std::enable_if<!std::is_pointer<T>::value, bool>::type
# ifdef _DOXYGEN_
bool
# else
typename std::enable_if<Has_c_str_length<T>::value && !Has_data_size<T>::value, bool>::type
# endif
setValue(const T& s) {
return setValue(reinterpret_cast<const uint8_t*>(s.c_str()), s.length());
}
/**
* @brief Template to set value to the value of <type\>val.
* @param [in] v The <type\>value to set.
* @details Only used if the <type\> has a `data()` and `size()` method.
*/
template <typename T>
# ifdef _DOXYGEN_
bool
# else
typename std::enable_if<Has_data_size<T>::value, bool>::type
# endif
setValue(const T& v) {
return setValue(reinterpret_cast<const uint8_t*>(v.data()), v.size());
}
# else
/**
* @brief Template to set value to the value of <type\>val.
* @param [in] s The <type\>value to set.
* @note This function is only available if the type T is not a pointer.
*/
template <typename T>
typename std::enable_if<!std::is_pointer<T>::value, bool>::type setValue(const T& s) {
if constexpr (Has_data_size<T>::value) {
return setValue(reinterpret_cast<const uint8_t*>(s.data()), s.size());
} else if constexpr (Has_c_str_length<T>::value) {
@ -237,6 +291,7 @@ class NimBLEAttValue {
return setValue(reinterpret_cast<const uint8_t*>(&s), sizeof(s));
}
}
# endif
/**
* @brief Template to return the value as a <type\>.
@ -267,10 +322,7 @@ class NimBLEAttValue {
/*********************** Operators ************************/
/** @brief Subscript operator */
uint8_t operator[](int pos) const {
NIMBLE_CPP_DEBUG_ASSERT(pos < m_attr_len);
return m_attr_value[pos];
}
uint8_t operator[](int pos) const;
/** @brief Operator; Get the value as a std::vector<uint8_t>. */
operator std::vector<uint8_t>() const { return std::vector<uint8_t>(m_attr_value, m_attr_value + m_attr_len); }

View File

@ -1,8 +1,18 @@
/*
* NimBLEAttribute.h
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on July 28 2024
* 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
*
* 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.
*/
#ifndef NIMBLE_CPP_ATTRIBUTE_H_
@ -43,7 +53,7 @@ class NimBLEAttribute {
~NimBLEAttribute() = default;
const NimBLEUUID m_uuid{};
uint16_t m_handle{0};
uint16_t m_handle{0};
};
#endif // CONFIG_BT_ENABLED && (CONFIG_BT_NIMBLE_ROLE_PERIPHERAL || CONFIG_BT_NIMBLE_ROLE_CENTRAL)

View File

@ -1,60 +1,46 @@
/*
* NimBLEBeacon2.cpp
* Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
* esp-nimble-cpp, NimBLE-Arduino contributors.
*
* Created: on March 15 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
*
* BLEBeacon.cpp
*
* Created on: Jan 4, 2018
* 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 "nimconfig.h"
#if defined(CONFIG_BT_ENABLED)
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
#include <string.h>
#include <algorithm>
#include "NimBLEBeacon.h"
#include "NimBLELog.h"
# include "NimBLEBeacon.h"
# include "NimBLEUUID.h"
# include "NimBLELog.h"
#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8))
# define ENDIAN_CHANGE_U16(x) ((((x) & 0xFF00) >> 8) + (((x) & 0xFF) << 8))
static const char* LOG_TAG = "NimBLEBeacon";
/**
* @brief Construct a default beacon object.
*/
NimBLEBeacon::NimBLEBeacon() {
m_beaconData.manufacturerId = 0x4c00;
m_beaconData.subType = 0x02;
m_beaconData.subTypeLength = 0x15;
m_beaconData.major = 0;
m_beaconData.minor = 0;
m_beaconData.signalPower = 0;
memset(m_beaconData.proximityUUID, 0, sizeof(m_beaconData.proximityUUID));
} // NimBLEBeacon
/**
* @brief Retrieve the data that is being advertised.
* @return The advertised data.
*/
std::string NimBLEBeacon::getData() {
return std::string((char*) &m_beaconData, sizeof(m_beaconData));
const NimBLEBeacon::BeaconData& NimBLEBeacon::getData() {
return m_beaconData;
} // getData
/**
* @brief Get the major value being advertised.
* @return The major value advertised.
*/
uint16_t NimBLEBeacon::getMajor() {
return m_beaconData.major;
}
} // getMajor
/**
* @brief Get the manufacturer ID being advertised.
@ -62,8 +48,7 @@ uint16_t NimBLEBeacon::getMajor() {
*/
uint16_t NimBLEBeacon::getManufacturerId() {
return m_beaconData.manufacturerId;
}
} // getManufacturerId
/**
* @brief Get the minor value being advertised.
@ -71,8 +56,7 @@ uint16_t NimBLEBeacon::getManufacturerId() {
*/
uint16_t NimBLEBeacon::getMinor() {
return m_beaconData.minor;
}
} // getMinor
/**
* @brief Get the proximity UUID being advertised.
@ -80,8 +64,7 @@ uint16_t NimBLEBeacon::getMinor() {
*/
NimBLEUUID NimBLEBeacon::getProximityUUID() {
return NimBLEUUID(m_beaconData.proximityUUID, 16).reverseByteOrder();
}
} // getProximityUUID
/**
* @brief Get the signal power being advertised.
@ -89,22 +72,28 @@ NimBLEUUID NimBLEBeacon::getProximityUUID() {
*/
int8_t NimBLEBeacon::getSignalPower() {
return m_beaconData.signalPower;
}
} // getSignalPower
/**
* @brief Set the raw data for the beacon record.
* @param [in] data The raw beacon data.
* @brief Set the beacon data.
* @param [in] data A pointer to the raw data that the beacon should advertise.
* @param [in] length The length of the data.
*/
void NimBLEBeacon::setData(const std::string &data) {
if (data.length() != sizeof(m_beaconData)) {
NIMBLE_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and expected %d",
data.length(), sizeof(m_beaconData));
void NimBLEBeacon::setData(const uint8_t* data, uint8_t length) {
if (length != sizeof(BeaconData)) {
NIMBLE_LOGE(LOG_TAG, "Data length must be %d bytes, sent: %d", sizeof(BeaconData), length);
return;
}
memcpy(&m_beaconData, data.data(), sizeof(m_beaconData));
memcpy(&m_beaconData, data, length);
} // setData
/**
* @brief Set the beacon data.
* @param [in] data The data that the beacon should advertise.
*/
void NimBLEBeacon::setData(const NimBLEBeacon::BeaconData& data) {
m_beaconData = data;
} // setData
/**
* @brief Set the major value.
@ -114,7 +103,6 @@ void NimBLEBeacon::setMajor(uint16_t major) {
m_beaconData.major = ENDIAN_CHANGE_U16(major);
} // setMajor
/**
* @brief Set the manufacturer ID.
* @param [in] manufacturerId The manufacturer ID value.
@ -123,7 +111,6 @@ void NimBLEBeacon::setManufacturerId(uint16_t manufacturerId) {
m_beaconData.manufacturerId = ENDIAN_CHANGE_U16(manufacturerId);
} // setManufacturerId
/**
* @brief Set the minor value.
* @param [in] minor The minor value.
@ -132,18 +119,17 @@ void NimBLEBeacon::setMinor(uint16_t minor) {
m_beaconData.minor = ENDIAN_CHANGE_U16(minor);
} // setMinor
/**
* @brief Set the proximity UUID.
* @param [in] uuid The proximity UUID.
*/
void NimBLEBeacon::setProximityUUID(const NimBLEUUID &uuid) {
void NimBLEBeacon::setProximityUUID(const NimBLEUUID& uuid) {
NimBLEUUID temp_uuid = uuid;
temp_uuid.to128();
std::reverse_copy(temp_uuid.getValue(), temp_uuid.getValue() + 16, m_beaconData.proximityUUID);
temp_uuid.reverseByteOrder();
memcpy(m_beaconData.proximityUUID, temp_uuid.getValue(), 16);
} // setProximityUUID
/**
* @brief Set the signal power.
* @param [in] signalPower The signal power value.
@ -152,4 +138,4 @@ void NimBLEBeacon::setSignalPower(int8_t signalPower) {
m_beaconData.signalPower = signalPower;
} // setSignalPower
#endif
#endif // CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_BROADCASTER

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