Repository: arduino-libraries/ArduinoBLE
Branch: master
Commit: a769ff82f323
Files: 130
Total size: 606.8 KB
Directory structure:
gitextract_54t7sr_k/
├── .codespellrc
├── .github/
│ ├── dependabot.yml
│ └── workflows/
│ ├── compile-examples.yml
│ ├── report-size-deltas.yml
│ ├── spell-check.yml
│ ├── sync-labels.yml
│ └── unit-tests.yml
├── .gitignore
├── CHANGELOG
├── LICENSE
├── README.md
├── docs/
│ ├── api.md
│ └── readme.md
├── examples/
│ ├── Central/
│ │ ├── LedControl/
│ │ │ └── LedControl.ino
│ │ ├── PeripheralExplorer/
│ │ │ └── PeripheralExplorer.ino
│ │ ├── Scan/
│ │ │ └── Scan.ino
│ │ ├── ScanCallback/
│ │ │ └── ScanCallback.ino
│ │ └── SensorTagButton/
│ │ └── SensorTagButton.ino
│ └── Peripheral/
│ ├── Advertising/
│ │ ├── EnhancedAdvertising/
│ │ │ └── EnhancedAdvertising.ino
│ │ └── RawDataAdvertising/
│ │ └── RawDataAdvertising.ino
│ ├── BatteryMonitor/
│ │ └── BatteryMonitor.ino
│ ├── ButtonLED/
│ │ └── ButtonLED.ino
│ ├── CallbackLED/
│ │ └── CallbackLED.ino
│ ├── EncryptedBatteryMonitor/
│ │ └── EncryptedBatteryMonitor.ino
│ └── LED/
│ └── LED.ino
├── extras/
│ ├── arduino-ble-parser.py
│ └── test/
│ ├── .gitignore
│ ├── CMakeLists.txt
│ ├── include/
│ │ ├── Arduino.h
│ │ ├── test_advertising_data/
│ │ │ └── FakeBLELocalDevice.h
│ │ ├── test_discovered_device/
│ │ │ └── FakeGAP.h
│ │ └── util/
│ │ ├── Common.h
│ │ ├── HCIFakeTransport.h
│ │ ├── Stream.h
│ │ ├── String.h
│ │ ├── TestUtil.h
│ │ └── itoa.h
│ └── src/
│ ├── Arduino.cpp
│ ├── test_advertising_data/
│ │ ├── FakeBLELocalDevice.cpp
│ │ ├── test_advertising_data.cpp
│ │ ├── test_local_name.cpp
│ │ ├── test_manufacturer.cpp
│ │ └── test_service.cpp
│ ├── test_characteristic/
│ │ ├── test_permissions.cpp
│ │ └── test_writeValue.cpp
│ ├── test_discovered_device/
│ │ ├── FakeGAP.cpp
│ │ └── test_discovered_device.cpp
│ ├── test_main.cpp
│ ├── test_uuid/
│ │ └── test_uuid.cpp
│ └── util/
│ ├── Common.cpp
│ ├── HCIFakeTransport.cpp
│ ├── String.cpp
│ ├── TestUtil.cpp
│ └── itoa.c
├── keywords.txt
├── library.properties
└── src/
├── ArduinoBLE.h
├── BLEAdvertisingData.cpp
├── BLEAdvertisingData.h
├── BLECharacteristic.cpp
├── BLECharacteristic.h
├── BLEDescriptor.cpp
├── BLEDescriptor.h
├── BLEDevice.cpp
├── BLEDevice.h
├── BLEProperty.h
├── BLEService.cpp
├── BLEService.h
├── BLEStringCharacteristic.cpp
├── BLEStringCharacteristic.h
├── BLETypedCharacteristic.h
├── BLETypedCharacteristics.cpp
├── BLETypedCharacteristics.h
├── local/
│ ├── BLELocalAttribute.cpp
│ ├── BLELocalAttribute.h
│ ├── BLELocalCharacteristic.cpp
│ ├── BLELocalCharacteristic.h
│ ├── BLELocalDescriptor.cpp
│ ├── BLELocalDescriptor.h
│ ├── BLELocalDevice.cpp
│ ├── BLELocalDevice.h
│ ├── BLELocalService.cpp
│ └── BLELocalService.h
├── remote/
│ ├── BLERemoteAttribute.cpp
│ ├── BLERemoteAttribute.h
│ ├── BLERemoteCharacteristic.cpp
│ ├── BLERemoteCharacteristic.h
│ ├── BLERemoteDescriptor.cpp
│ ├── BLERemoteDescriptor.h
│ ├── BLERemoteDevice.cpp
│ ├── BLERemoteDevice.h
│ ├── BLERemoteService.cpp
│ └── BLERemoteService.h
└── utility/
├── ATT.cpp
├── ATT.h
├── BLELinkedList.h
├── BLEUuid.cpp
├── BLEUuid.h
├── CordioHCICustomDriver.h
├── GAP.cpp
├── GAP.h
├── GATT.cpp
├── GATT.h
├── HCI.cpp
├── HCI.h
├── HCICordioTransport.cpp
├── HCICordioTransport.h
├── HCINinaSpiTransport.cpp
├── HCINinaSpiTransport.h
├── HCISilabsTransport.cpp
├── HCISilabsTransport.h
├── HCITransport.h
├── HCIUartTransport.cpp
├── HCIUartTransport.h
├── HCIVirtualTransport.cpp
├── HCIVirtualTransport.h
├── HCIVirtualTransportAT.cpp
├── HCIVirtualTransportAT.h
├── HCIVirtualTransportRPC.cpp
├── HCIVirtualTransportRPC.h
├── HCIVirtualTransportZephyr.cpp
├── HCIVirtualTransportZephyr.h
├── L2CAPSignaling.cpp
├── L2CAPSignaling.h
├── bitDescriptions.cpp
├── bitDescriptions.h
├── btct.cpp
├── btct.h
├── keyDistribution.cpp
└── keyDistribution.h
================================================
FILE CONTENTS
================================================
================================================
FILE: .codespellrc
================================================
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/spell-check/.codespellrc
# See: https://github.com/codespell-project/codespell#using-a-config-file
[codespell]
# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here:
ignore-words-list = ,
skip = ./.git,./.licenses,__pycache__,node_modules,./go.mod,./go.sum,./package-lock.json,./poetry.lock,./yarn.lock,./extras/test
builtin = clear,informal,en-GB_to_en-US
check-filenames =
check-hidden =
================================================
FILE: .github/dependabot.yml
================================================
# See: https://docs.github.com/en/code-security/supply-chain-security/configuration-options-for-dependency-updates#about-the-dependabotyml-file
version: 2
updates:
# Configure check for outdated GitHub Actions actions in workflows.
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/dependabot/README.md
# See: https://docs.github.com/en/code-security/supply-chain-security/keeping-your-actions-up-to-date-with-dependabot
- package-ecosystem: github-actions
directory: / # Check the repository's workflows under /.github/workflows/
schedule:
interval: daily
labels:
- "topic: infrastructure"
================================================
FILE: .github/workflows/compile-examples.yml
================================================
name: Compile Examples
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/compile-examples.yml"
- "examples/**"
- "src/**"
pull_request:
paths:
- ".github/workflows/compile-examples.yml"
- "examples/**"
- "src/**"
schedule:
# Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms).
- cron: "0 8 * * TUE"
workflow_dispatch:
repository_dispatch:
jobs:
build:
name: ${{ matrix.board.fqbn }}
runs-on: ubuntu-latest
env:
SKETCHES_REPORTS_PATH: sketches-reports
strategy:
fail-fast: false
matrix:
board:
- fqbn: arduino:samd:mkrwifi1010
platforms: |
- name: arduino:samd
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-samd-mkrwifi1010
- fqbn: arduino:samd:nano_33_iot
platforms: |
- name: arduino:samd
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-samd-nano_33_iot
- fqbn: arduino:megaavr:uno2018:mode=on
platforms: |
- name: arduino:megaavr
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-megaavr-uno2018
- fqbn: arduino:mbed_nano:nano33ble
platforms: |
- name: arduino:mbed_nano
libraries: ""
artifact-name-suffix: arduino-mbed_nano-nano33ble
- fqbn: arduino:mbed_nano:nanorp2040connect
platforms: |
- name: arduino:mbed_nano
libraries: |
- name: Arduino_SpiNINA
artifact-name-suffix: arduino-mbed_nano-nanorp2040connect
- fqbn: arduino:mbed_portenta:envie_m7
platforms: |
- name: arduino:mbed_portenta
libraries: ""
artifact-name-suffix: arduino-mbed_portenta-envie_m7
- fqbn: arduino:mbed_nicla:nicla_vision
platforms: |
- name: arduino:mbed_nicla
libraries: ""
artifact-name-suffix: arduino-mbed_nicla-nicla_vision
- fqbn: arduino:mbed_giga:giga
platforms: |
- name: arduino:mbed_giga
libraries: ""
artifact-name-suffix: arduino-mbed_giga-giga
- fqbn: arduino:mbed_opta:opta
platforms: |
- name: arduino:mbed_opta
libraries: ""
artifact-name-suffix: arduino-mbed_opta-opta
- fqbn: arduino:renesas_uno:unor4wifi
platforms: |
- name: arduino:renesas_uno
libraries: ""
artifact-name-suffix: arduino-renesas_uno-unor4wifi
- fqbn: arduino:renesas_portenta:portenta_c33
platforms: |
- name: arduino:renesas_portenta
libraries: ""
artifact-name-suffix: arduino-renesas_portenta-portenta_c33
- fqbn: arduino:esp32:nano_nora
platforms: |
- name: arduino:esp32
libraries: ""
artifact-name-suffix: arduino-esp32-nano_nora
- fqbn: arduino:zephyr_main:giga
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-giga
- fqbn: arduino:zephyr_main:nano33ble
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-nano33ble
- fqbn: arduino:zephyr_main:portentah7
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-portentah7
- fqbn: arduino:zephyr_main:niclasense
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-niclasense
- fqbn: arduino:zephyr_main:portentac33
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-portentac33
- fqbn: arduino:zephyr_main:opta
platforms: |
- name: arduino:zephyr_main
libraries: ""
artifact-name-suffix: arduino-zephyr_main-opta
- fqbn: arduino:zephyr:unoq
platforms: |
- name: arduino:zephyr
libraries: |
- name: MsgPack
artifact-name-suffix: arduino-zephyr-unoq
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Compile examples
uses: arduino/compile-sketches@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fqbn: ${{ matrix.board.fqbn }}
platforms: ${{ matrix.board.platforms }}
libraries: |
# Install the library from the local path.
- source-path: ./
${{ matrix.board.libraries }}
sketch-paths: |
- examples
enable-deltas-report: true
sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }}
- name: Save sketches report as workflow artifact
uses: actions/upload-artifact@v7
with:
if-no-files-found: error
path: ${{ env.SKETCHES_REPORTS_PATH }}
name: sketches-report-${{ matrix.board.artifact-name-suffix }}
build-for-esp32:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
fqbn:
- esp32:esp32:esp32
- esp32:esp32:esp32s3
- esp32:esp32:esp32c3
- esp32:esp32:esp32c6
- esp32:esp32:esp32h2
# Not supported out of the box by ESP32 Arduino core
#- esp32:esp32:esp32c2
steps:
- uses: actions/checkout@v6
- uses: arduino/compile-sketches@v1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
fqbn: ${{ matrix.fqbn }}
libraries: |
${{ matrix.libraries }}
platforms: |
- name: esp32:esp32
source-url: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
sketch-paths: |
- examples/Central/Scan
- examples/Central/PeripheralExplorer
- examples/Central/ScanCallback
- examples/Central/SensorTagButton
- examples/Peripheral/Advertising/EnhancedAdvertising
- examples/Peripheral/Advertising/RawDataAdvertising
cli-compile-flags: |
- --warnings="none"
================================================
FILE: .github/workflows/report-size-deltas.yml
================================================
name: Report Size Deltas
# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/report-size-deltas.yml"
schedule:
# Run at the minimum interval allowed by GitHub Actions.
# Note: GitHub Actions periodically has outages which result in workflow failures.
# In this event, the workflows will start passing again once the service recovers.
- cron: "*/5 * * * *"
workflow_dispatch:
repository_dispatch:
jobs:
report:
runs-on: ubuntu-latest
steps:
- name: Comment size deltas reports to PRs
uses: arduino/report-size-deltas@v1
with:
# Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow
sketches-reports-source: ^sketches-report-.+
================================================
FILE: .github/workflows/spell-check.yml
================================================
# Source: https://github.com/per1234/.github/blob/main/workflow-templates/spell-check.md
name: Spell Check
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
push:
pull_request:
schedule:
# Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates.
- cron: "0 8 * * TUE"
workflow_dispatch:
repository_dispatch:
jobs:
spellcheck:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Spell check
uses: codespell-project/actions-codespell@v2
================================================
FILE: .github/workflows/sync-labels.yml
================================================
# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md
name: Sync Labels
# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows
on:
push:
paths:
- ".github/workflows/sync-labels.ya?ml"
- ".github/label-configuration-files/*.ya?ml"
pull_request:
paths:
- ".github/workflows/sync-labels.ya?ml"
- ".github/label-configuration-files/*.ya?ml"
schedule:
# Run daily at 8 AM UTC to sync with changes to shared label configurations.
- cron: "0 8 * * *"
workflow_dispatch:
repository_dispatch:
env:
CONFIGURATIONS_FOLDER: .github/label-configuration-files
CONFIGURATIONS_ARTIFACT: label-configuration-files
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Download JSON schema for labels configuration file
id: download-schema
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json
location: ${{ runner.temp }}/label-configuration-schema
- name: Install JSON schema validator
run: |
sudo npm install \
--global \
ajv-cli \
ajv-formats
- name: Validate local labels configuration
run: |
# See: https://github.com/ajv-validator/ajv-cli#readme
ajv validate \
--all-errors \
-c ajv-formats \
-s "${{ steps.download-schema.outputs.file-path }}" \
-d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}"
download:
needs: check
runs-on: ubuntu-latest
strategy:
matrix:
filename:
# Filenames of the shared configurations to apply to the repository in addition to the local configuration.
# https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels
- universal.yml
steps:
- name: Download
uses: carlosperate/download-file-action@v2
with:
file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }}
- name: Pass configuration files to next job via workflow artifact
uses: actions/upload-artifact@v7
with:
path: |
*.yaml
*.yml
if-no-files-found: error
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
sync:
needs: download
runs-on: ubuntu-latest
steps:
- name: Set environment variables
run: |
# See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable
echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV"
- name: Determine whether to dry run
id: dry-run
if: >
github.event_name == 'pull_request' ||
(
(
github.event_name == 'push' ||
github.event_name == 'workflow_dispatch'
) &&
github.ref != format('refs/heads/{0}', github.event.repository.default_branch)
)
run: |
# Use of this flag in the github-label-sync command will cause it to only check the validity of the
# configuration.
echo "::set-output name=flag::--dry-run"
- name: Checkout repository
uses: actions/checkout@v6
- name: Download configuration files artifact
uses: actions/download-artifact@v8
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
path: ${{ env.CONFIGURATIONS_FOLDER }}
- name: Remove unneeded artifact
uses: geekyeggo/delete-artifact@v6
with:
name: ${{ env.CONFIGURATIONS_ARTIFACT }}
- name: Merge label configuration files
run: |
# Merge all configuration files
shopt -s extglob
cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}"
- name: Install github-label-sync
run: sudo npm install --global github-label-sync
- name: Sync labels
env:
GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# See: https://github.com/Financial-Times/github-label-sync
github-label-sync \
--labels "${{ env.MERGED_CONFIGURATION_PATH }}" \
${{ steps.dry-run.outputs.flag }} \
${{ github.repository }}
================================================
FILE: .github/workflows/unit-tests.yml
================================================
name: Unit Tests
on:
pull_request:
paths:
- ".github/workflows/unit-tests.yml"
- 'extras/test/**'
- 'src/**'
push:
paths:
- ".github/workflows/unit-tests.yml"
- 'extras/test/**'
- 'src/**'
jobs:
test:
name: Run unit tests
runs-on: ubuntu-latest
env:
COVERAGE_DATA_PATH: extras/coverage-data/coverage.info
steps:
- name: Checkout
uses: actions/checkout@v6
- uses: arduino/cpp-test-action@main
with:
runtime-paths: |
- extras/test/build/bin/TEST_TARGET_UUID
- extras/test/build/bin/TEST_TARGET_DISC_DEVICE
- extras/test/build/bin/TEST_TARGET_ADVERTISING_DATA
coverage-exclude-paths: |
- '*/extras/test/*'
- '/usr/*'
coverage-data-path: ${{ env.COVERAGE_DATA_PATH }}
# A token is used to avoid intermittent spurious job failures caused by rate limiting.
- name: Set up Codecov upload token
run: |
if [[ "${{ github.repository }}" == "arduino-libraries/ArduinoBLE" ]]; then
# In order to avoid uploads of data from forks, only use the token for runs in the parent repo.
# Token is intentionally exposed.
# See: https://community.codecov.com/t/upload-issues-unable-to-locate-build-via-github-actions-api/3954
CODECOV_TOKEN="8118de48-b2af-48b4-a66a-26026847bfc5"
else
# codecov/codecov-action does unauthenticated upload if empty string is passed via the `token` input.
CODECOV_TOKEN=""
fi
echo "CODECOV_TOKEN=$CODECOV_TOKEN" >> "$GITHUB_ENV"
- name: Upload coverage report to Codecov
uses: codecov/codecov-action@v3
with:
file: "${{ env.COVERAGE_DATA_PATH }}"
fail_ci_if_error: true
token: ${{ env.CODECOV_TOKEN }}
================================================
FILE: .gitignore
================================================
.DS_Store
================================================
FILE: CHANGELOG
================================================
ArduinoBLE ?.?.? - ????.??.??
ArduinoBLE 1.1.2 - 2019.11.12
* cordio: switch to lower power when polling with timeout
* Fixed issue with wrong types for disconnection event handling. Thanks @cparata
ArduinoBLE 1.1.1 - 2019.09.05
* [Cordio] Fixed crashing when BLE.begin() is not called
* Fixed ACL RX packet fragmentation, affected devices that supported large MTUs
* Fixed BLECharacteristic::readValue(...) triggering a read request after a notification/indication was received
* Added support for case insensitive comparison of UUID or address string inputs
* Added (optional) company ID argument to BLE.setManufacturerData(...). Thanks @konikoni428
ArduinoBLE 1.1.0 - 2019.08.27
* Added BLE Central support
ArduinoBLE 1.0.0 - 2019.07.31
* Added support for Arduino Nano 33 BLE boards
ArduinoBLE 0.1.2 and older
* Changes not recorded
================================================
FILE: LICENSE
================================================
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
(This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.)
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
{signature of Ty Coon}, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
================================================
FILE: README.md
================================================
# ArduinoBLE
[](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Compile+Examples) [](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Spell+Check)
Enables Bluetooth® Low Energy connectivity on the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev2, Arduino Nano 33 IoT, Arduino Nano 33 BLE, Arduino Portenta H7, Arduino Giga R1 and Arduino UNO R4 WiFi.
This library supports creating a Bluetooth® Low Energy peripheral & central mode.
For more information about this library please visit us at:
https://www.arduino.cc/en/Reference/ArduinoBLE
## Firmware compatibility
| Board | Library Version | Required Firmware |
| :--- | :--- | :--- |
| **MKR WiFi 1010, UNO WiFi Rev2,
Nano 33 IoT, Nano RP2040 Connect** | **v2.0.0 or later** | [NINA-W102](https://github.com/arduino/nina-fw) **v3.0.0+** |
| **MKR WiFi 1010, UNO WiFi Rev2,
Nano 33 IoT, Nano RP2040 Connect** | **Versions prior to v2.0.0** | [NINA-W102](https://github.com/arduino/nina-fw) **v1.2.0 – v2.0.0** |
| **Arduino UNO R4 WiFi** | All versions | [ESP32-S3](https://github.com/arduino/uno-r4-wifi-usb-bridge) **v0.2.0+** |
## License
```
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
```
================================================
FILE: docs/api.md
================================================
# ArduinoBLE library
## BLE class
Used to enable the Bluetooth® Low Energy module.
### `BLE.begin()`
Initializes the Bluetooth® Low Energy device.
#### Syntax
```
BLE.begin()
```
#### Parameters
None
#### Returns
- 1 on success
- 0 on failure
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
```
### `BLE.end()`
Stops the Bluetooth® Low Energy device.
#### Syntax
```
BLE.end()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ....
BLE.end();
```
### `BLE.poll()`
Poll for Bluetooth® Low Energy radio events and handle them.
#### Syntax
```
BLE.poll()
BLE.poll(timeout)
```
#### Parameters
**timeout**: optional timeout in ms, to wait for event. If not specified defaults to 0 ms.
#### Returns
Nothing
#### Example
```arduino
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
BLE.poll();
```
### `BLE.setEventHandler()`
Set the event handler (callback) function that will be called when the specified event occurs.
#### Syntax
```
BLE.setEventHandler(eventType, callback)
```
#### Parameters
- **eventType**: event type (BLEConnected, BLEDisconnected)
- **callback**: function to call when event occurs
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
void blePeripheralConnectHandler(BLEDevice central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
```
### `BLE.connected()`
Query if another Bluetooth® Low Energy device is connected
#### Syntax
```
BLE.connected()
```
#### Parameters
None
#### Returns
- **true** if another Bluetooth® Low Energy device is connected,
- otherwise **false**.
#### Example
```arduino
// while the central is still connected to peripheral:
while (BLE.connected()) {
// ...
}
```
### `BLE.disconnect()`
Disconnect any Bluetooth® Low Energy devices that are connected
#### Syntax
```
BLE.disconnect()
```
#### Parameters
None
#### Returns
- **true** if any Bluetooth® Low Energy device that was previously connected was disconnected,
- otherwise **false**.
#### Example
```arduino
if (BLE.connected()) {
BLE.disconnect();
}
```
### `BLE.address()`
Query the Bluetooth® address of the Bluetooth® Low Energy device.
#### Syntax
```
BLE.address()
```
#### Parameters
None
#### Returns
- The **Bluetooth® address** of the Bluetooth® Low Energy device (as a String).
#### Example
```arduino
String address = BLE.address();
Serial.print("Local address is: ");
Serial.println(address);
```
### `BLE.rssi()`
Query the RSSI (Received signal strength indication) of the connected Bluetooth® Low Energy device.
#### Syntax
```
BLE.rssi()
```
#### Parameters
None
#### Returns
- The **RSSI** of the connected Bluetooth® Low Energy device, 127 if no Bluetooth® Low Energy device is connected.
#### Example
```arduino
if (BLE.connected()) {
Serial.print("RSSI = ");
Serial.println(BLE.rssi());
}
```
### `BLE.setAdvertisedServiceUuid()`
Set the advertised service UUID used when advertising.
#### Syntax
```
BLE.setAdvertisedServiceUuid(uuid)
```
#### Parameters
- **uuid:** 16-bit or 128-bit Bluetooth® Low Energy UUID in **String** format
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAdvertisedServiceUuid("19B10000-E8F2-537E-4F6C-D104768A1214");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setAdvertisedService()`
Set the advertised service UUID used when advertising to the value of the BLEService provided.
#### Syntax
```
BLE.setAdvertisedService(bleService)
```
#### Parameters
- **bleService:** BLEService to use UUID from
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// ...
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAdvertisedService(ledService);
// ...
// start advertising
BLE.advertise();
```
### `BLE.setManufacturerData()`
Set the manufacturer data value used when advertising.
#### Syntax
```
BLE.setManufacturerData(data, length)
```
#### Parameters
- **data:** byte array containing manufacturer data
- **length:** length of manufacturer data array
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
byte data[5] = { 0x01, 0x02, 0x03, 0x04, 0x05};
BLE.setManufacturerData(data, 5);
// ...
// start advertising
BLE.advertise();
```
### `BLE.setLocalName()`
Set the local value used when advertising.
#### Syntax
```
BLE.setLocalName(name)
```
#### Parameters
- **name:** local name value to use when advertising
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setLocalName("LED");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setDeviceName()`
Set the device name in the built in device name characteristic. If not set, the value defaults to “Arduino”.
#### Syntax
```
BLE.setDeviceName(name)
```
#### Parameters
- **name:** device name value
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setDeviceName("LED");
// ...
// start advertising
BLE.advertise();
```
### `BLE.setAppearance()`
Set the appearance in the built in appearance characteristic. If not set, the value defaults to 0x0000.
#### Syntax
```
BLE.setAppearance(appearance)
```
#### Parameters
- **appearance:** appearance value
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
BLE.setAppearance(0x8000);
// ...
// start advertising
BLE.advertise();
```
### `BLE.addService()`
Add a BLEService to the set of services the Bluetooth® Low Energy device provides
#### Syntax
```
BLE.addService(service)
```
#### Parameters
- **service:** BLEService to add
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.addService(ledService);
// ...
```
### `BLE.advertise()`
Start advertising.
#### Syntax
```
BLE.advertise()
```
#### Parameters
None
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.advertise();
// ...
```
### `BLE.stopAdvertise()`
Stop advertising.
#### Syntax
```
BLE.stopAdvertise()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.advertise();
// ...
BLE.stopAdvertise();
```
### `BLE.central()`
Query the central Bluetooth® Low Energy device connected.
#### Syntax
```
BLE.central()
```
#### Parameters
None
#### Returns
- **BLEDevice** representing the central.
#### Example
```arduino
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
}
```
### `BLE.setAdvertisingInterval()`
Set the advertising interval in units of 0.625 ms. Defaults to 100ms (160 * 0.625 ms) if not provided.
#### Syntax
```
BLE.setAdvertisingInterval(advertisingInterval)
```
#### Parameters
- **advertisingInterval:** advertising interval in units of 0.625 ms
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setAdvertisingInterval(320); // 200 * 0.625 ms
BLE.advertise();
```
### `BLE.setConnectionInterval()`
Set the minimum and maximum desired connection intervals in units of 1.25 ms.
#### Syntax
```
BLE.setConnectionInterval(minimum, maximum)
```
#### Parameters
- **minimum:** minimum desired connection interval in units of 1.25 ms
- **maximum:** maximum desired connection interval in units of 1.25 ms
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setConnectionInterval(0x0006, 0x0c80); // 7.5 ms minimum, 4 s maximum
```
### `BLE.setConnectable()`
Set if the device is connectable after advertising, defaults to **true**.
#### Syntax
```
BLE.setConnectable(connectable)
```
#### Parameters
- **true**: the device will be connectable when advertising
- **false**: the device will NOT be connectable when advertising
#### Returns
Nothing.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// ...
BLE.setConnectable(false); // make the device unconnectable when advertising
```
### `BLE.scan()`
Start scanning for Bluetooth® Low Energy devices that are advertising.
#### Syntax
```
BLE.scan()
BLE.scan(withDuplicates)
```
#### Parameters
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForName()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (local) name.
#### Syntax
```
BLE.scanForName(name)
BLE.scanForName(name, withDuplicates)
```
#### Parameters
- **name:** (local) name of device (as a **String**) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered.
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForName("LED");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForAddress()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (Bluetooth®) address.
#### Syntax
```
BLE.scanForAddress(address)
BLE.scanForAddress(address, withDuplicates)
```
#### Parameters
- **address:** (Bluetooth®) address (as a String) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForAddress("aa:bb:cc:ee:dd:ff");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.scanForUuid()`
Start scanning for Bluetooth® Low Energy devices that are advertising with a particular (service) UUID.
#### Syntax
```
BLE.scanForUuid(uuid)
BLE.scanForUuid(uuid, withDuplicates)
```
#### Parameters
- **uuid:** (service) UUID (as a **String**) to filter for
- **withDuplicates:** optional, defaults to **false**. If **true**, advertisements received more than once will not be filtered.
#### Returns
- 1 on success,
- 0 on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scanForUuid("aa10");
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
### `BLE.stopScan()`
Stop scanning for Bluetooth® Low Energy devices that are advertising.
#### Syntax
```
BLE.stopScan()
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLE.stopScan();
```
### `BLE.available()`
Query for a discovered Bluetooth® Low Energy device that was found during scanning.
#### Syntax
```
BLE.available()
```
#### Parameters
Nothing
#### Returns
- **BLEDevice** representing the discovered device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
}
```
## BLEDevice Class
Used to get information about the devices connected or discovered while scanning
### `bleDevice.poll()`
Poll for Bluetooth® Low Energy radio events for the specified Bluetooth® Low Energy device and handle them.
#### Syntax
```
bleDevice.poll()
bleDevice.poll(timeout)
```
#### Parameters
- **timeout**: optional timeout in ms, to wait for event. If not specified defaults to 0 ms.
#### Returns
Nothing
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
central.poll();
// ...
}
```
### `bleDevice.connected()`
Query if a Bluetooth® Low Energy device is connected
#### Syntax
```
bleDevice.connected()
```
#### Parameters
None
#### Returns
- **true** if the Bluetooth® Low Energy device is connected,
- otherwise **false**.
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
// while the central is still connected
while (central.connected()) {
// ...
}
```
### `bleDevice.disconnect()`
Disconnect the Bluetooth® Low Energy device, if connected
#### Syntax
```
bleDevice.disconnect()
```
#### Parameters
None
#### Returns
- **true** if the Bluetooth® Low Energy device was disconnected,
- otherwise **false**.
#### Example
```arduino
// listen for Bluetooth® Low Energy centrals to connect:
BLEDevice central = BLE.central();
central.disconnect();
```
### `bleDevice.address()`
Query the Bluetooth® address of the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.address()
```
#### Parameters
None
#### Returns
- **Bluetooth® address** of the Bluetooth® Low Energy device (as a String).
#### Example
```arduino
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
}
```
### `bleDevice.rssi()`
Query the RSSI (Received signal strength indication) of the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.rssi()
```
#### Parameters
None
#### Returns
- **RSSI** of the connected Bluetooth® Low Energy device, 127 if the Bluetooth® Low Energy device is not connected.
#### Example
```arduino
if (bleDevice.connected()) {
Serial.print("RSSI = ");
Serial.println(bleDevice.rssi());
}
```
### `bleDevice.characteristic()`
Get a BLECharacteristic representing a Bluetooth® Low Energy characteristic the device provides.
#### Syntax
```
bleDevice.characteristic(index)
bleDevice.characteristic(uuid)
bleDevice.characteristic(uuid, index)
```
#### Parameters
- **index**: index of characteristic
- **uuid**: uuid (as a **String**)
#### Returns
- **BLECharacteristic** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLECharacteristic batteryLevelCharacteristic = peripheral.characteristic("2a19");
if (batteryLevelCharacteristic) {
// use the characteristic
} else {
Serial.println("Peripheral does NOT have battery level characteristic");
}
// ...
}
```
### `bleDevice.discoverAttributes()`
Discover all of the attributes of Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.discoverAttributes()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// ...
}
```
### `bleDevice.discoverService()`
Discover the attributes of a particular service on the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.discoverService(serviceUuid)
```
#### Parameters
- **serviceUuid:** service UUID to discover (as a **String**)
#### Returns
- **true**, if successful,
- **false** on failure.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover service attributes
Serial.println("Discovering service attributes ...");
if (peripheral.serviceUuid("fffe")) {
Serial.println("Service attributes discovered");
} else {
Serial.println("Service attribute discovery failed!");
peripheral.disconnect();
return;
}
// ...
}
```
### `bleDevice.deviceName()`
Query the device name (BLE characteristic UUID 0x2a00) of a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.deviceName()
```
#### Parameters
None
#### Returns
- **Device name** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// ...
}
```
### `bleDevice.appearance()`
Query the appearance (BLE characteristic UUID 0x2a01) of a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.appearance()
```
#### Parameters
None
#### Returns
- **Appearance value** (as a number).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// ...
}
```
### `bleDevice.serviceCount()`
Query the number of services discovered for the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.serviceCount()
```
#### Parameters
None
#### Returns
- The number of **services discovered** for the Bluetooth® Low Energy device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
int serviceCount = peripheral.serviceCount();
Serial.print(serviceCount);
Serial.println(" services discovered");
// ...
}
```
### `bleDevice.hasService()`
Query if the Bluetooth® Low Energy device has a particular service.
#### Syntax
```
bleDevice.hasService(uuid)
bleDevice.hasService(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of service to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the device provides the service,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
if (peripheral.hasService("180f")) {
Serial.println("Peripheral has battery service");
}
// ...
}
```
### `bleDevice.service()`
Get a BLEService representing a Bluetooth® Low Energy service the device provides.
#### Syntax
```
bleDevice.service(index)
bleDevice.service(uuid)
bleDevice.service(uuid, index)
```
#### Parameters
- **index**: index of service
- **uuid**: uuid (as a **String**)
#### Returns
- **BLEService** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleDevice.characteristicCount()`
Query the number of characteristics discovered for the Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.characteristicCount()
```
#### Parameters
None
#### Returns
- The **number of characteristics** discovered for the Bluetooth® Low Energy device.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
int characteristicCount = peripheral.characteristicCount();
Serial.print(characteristicCount);
Serial.println(" characteristics discovered");
// ...
}
```
### `bleDevice.hasCharacteristic()`
Query if the Bluetooth® Low Energy device has a particular characteristic.
#### Syntax
```
bleDevice.hasCharacteristic(uuid)
bleDevice.hasCharacteristic(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of characteristic to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the device provides the characteristic,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
if (peripheral.hasCharacteristic("2a19")) {
Serial.println("Peripheral has battery level characteristic");
}
// ...
}
```
### `bleDevice.hasLocalName()`
Query if a discovered Bluetooth® Low Energy device is advertising a local name.
#### Syntax
```
bleDevice.hasLocalName()
```
#### Parameters
Nothing
#### Returns
- **true**, if the device is advertising a local name,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// ...
}
```
### `bleDevice.hasAdvertisedServiceUuid()`
Query if a discovered Bluetooth® Low Energy device is advertising a service UUID.
#### Syntax
```
bleDevice.hasAdvertisedServiceUuid()
bleDevice.hasAdvertisedServiceUuid(index)
```
#### Parameters
- **index**: optional, defaults to 0, the index of the service UUID, if the device is advertising more than one.
#### Returns
- **true**, if the device is advertising a service UUID,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.advertisedServiceUuidCount()`
Query the number of advertised services a discovered Bluetooth® Low Energy device is advertising.
#### Syntax
```
bleDevice.advertisedServiceUuidCount()
```
#### Parameters
None
#### Returns
- The **number of advertised services** a discovered Bluetooth® Low Energy device is advertising.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.localName()`
Query the local name a discovered Bluetooth® Low Energy device is advertising with.
#### Syntax
```
bleDevice.localName()
```
#### Parameters
Nothing
#### Returns
- **Advertised local name** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// ...
}
```
### `bleDevice.advertisedServiceUuid()`
Query an advertised service UUID discovered Bluetooth® Low Energy device is advertising.
#### Syntax
```
bleDevice.advertisedServiceUuid()
bleDevice.advertisedServiceUuid(index)
```
#### Parameters
- **index**: optional, defaults to 0, the index of the **service UUID**, if the device is advertising more than one.
#### Returns
- Advertised service **UUID** (as a String).
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// ...
}
```
### `bleDevice.connect()`
Connect to a Bluetooth® Low Energy device.
#### Syntax
```
bleDevice.connect()
```
#### Parameters
None
#### Returns
- **true**, if the connection was successful,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// ...
}
```
## BLEService Class
Used to enable the services board provides or interact with services a remote board provides.
### `BLEService()`
Create a new Bluetooth® Low Energy service.
#### Syntax
```
BLEService(uuid)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in **String** format
#### Returns
- New **BLEService** with the specified **UUID**
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
```
### `bleService.uuid()`
Query the UUID of the specified BLEService.
#### Syntax
```
bleService.uuid()
```
#### Parameters
None
#### Returns
- UUID of the Bluetooth® Low Energy service as a **String**.
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
Serial.print("LED service UUID = ");
Serial.println(ledService.uuid());
```
### `bleService.addCharacteristic()`
Add a BLECharacteristic to the Bluetooth® Low Energy service.
#### Syntax
```
bleService.addCharacteristic(bleCharacteristic)
```
#### Parameters
None
#### Returns
Nothing
#### Example
```arduino
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, readable and writable by central
BLECharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite, 1);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
```
### `bleService.characteristicCount()`
Query the number of characteristics discovered for the Bluetooth® Low Energy service.
#### Syntax
```
bleService.characteristicCount()
```
#### Parameters
None
#### Returns
- The **number of characteristics** discovered for the Bluetooth® Low Energy service.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
int characteristicCount = batteryService.characteristicCount();
Serial.print(characteristicCount);
Serial.println(" characteristics discovered in battery service");
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleService.hasCharacteristic()`
Query if the Bluetooth® Low Energy service has a particular characteristic.
#### Syntax
```
bleService.hasCharacteristic(uuid)
bleService.hasCharacteristic(uuid, index)
```
#### Parameters
- **uuid**: uuid to check (as a **String**)
- **index**: optional, index of characteristic to check if the device provides more than on. Defaults to 0, if not provided.
#### Returns
- **true**, if the service provides the characteristic,
- **false** otherwise.
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
if (batteryService.hasCharacteristic("2a19")) {
Serial.println("Battery service has battery level characteristic");
}
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
### `bleService.characteristic()`
Get a BLECharacteristic representing a Bluetooth® Low Energy characteristic the service provides.
#### Syntax
```
bleService.characteristic(index)
bleService.characteristic(uuid)
bleService.characteristic(uuid, index)
```
#### Parameters
- **index**: index of characteristic
- **uuid**: uuid (as a **String**)
#### Returns
- **BLECharacteristic** for provided parameters
#### Example
```arduino
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BLE Central scan");
// start scanning for peripheral
BLE.scan();
BLEDevice peripheral = BLE.available();
if (peripheral) {
// ...
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
BLEService batteryService = peripheral.service("180f");
if (batteryService) {
// use the service
BLECharacteristic batteryLevelCharacteristic = peripheral.characteristic("2a19");
if (batteryLevelCharacteristic) {
// use the characteristic
} else {
Serial.println("Peripheral does NOT have battery level characteristic");
}
} else {
Serial.println("Peripheral does NOT have battery service");
}
// ...
}
```
## BLECharacteristic Class
Used to enable the characteristics board offers in a service or interact with characteristics a remote board provides.
### `BLECharacteristic()`
Create a new Bluetooth® Low Energy characteristic.
#### Syntax
```
BLECharacteristic(uuid, properties, valueSize)
BLECharacteristic(uuid, properties, valueSize, fixedLength)
BLECharacteristic(uuid, properties, stringValue)
BLEBoolCharacteristic(uuid, properties)
BLEBooleanCharacteristic(uuid, properties)
BLECharCharacteristic(uuid, properties)
BLEUnsignedCharCharacteristic(uuid, properties)
BLEByteCharacteristic(uuid, properties)
BLEShortCharacteristic(uuid, properties)
BLEUnsignedShortCharacteristic(uuid, properties)
BLEWordCharacteristic(uuid, properties)
BLEIntCharacteristic(uuid, properties)
BLEUnsignedIntCharacteristic(uuid, properties)
BLELongCharacteristic(uuid, properties)
BLEUnsignedLongCharacteristic(uuid, properties)
BLEFloatCharacteristic(uuid, properties)
BLEDoubleCharacteristic(uuid, properties)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in **String** format
- **properties**: mask of the properties (BLEBroadcast, BLERead, BLEWriteWithoutResponse, BLEWrite, BLENotify, BLEIndicate)
- **valueSize**: (maximum) size of characteristic value
- **fixedLength**: if true, size of characteristic value is fixed
- **stringValue**: value as a string
#### Returns
- New **BLECharacteristic** with the specified **UUID** and value
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
```
### `bleCharacteristic.uuid()`
Query the UUID of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.uuid()
```
#### Parameters
None
#### Returns
- **UUID** of the Bluetooth® Low Energy service as a **String**.
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("Switch characteristic UUID = ");
Serial.println(switchCharacteristic.uuid());
```
### `bleCharacteristic.properties()`
Query the property mask of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.properties()
```
#### Parameters
None
#### Returns
- **Properties of the characteristic masked** (BLEBroadcast, BLERead, BLEWriteWithoutResponse, BLEWrite, BLENotify, BLEIndicate)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
byte properties = switchCharacteristic.properties();
if (properties & BLERead) {
// characteristic is readable ...
}
if (properties & (BLEWrite | BLEWriteWithoutResponse)) {
// characteristic is writable ...
}
```
### `bleCharacteristic.valueSize()`
Query the maximum value size of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.valueSize()
```
#### Parameters
None
#### Returns
- The **maximum value** size of the characteristic (in bytes)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("value size = ");
Serial.println(switchCharacteristic.valueSize());
```
### `bleCharacteristic.value()`
Query the current value of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.value()
```
#### Parameters
None
#### Returns
- The **current value** of the characteristic, value type depends on the constructor used
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
```
### `bleCharacteristic.valueLength()`
Query the current value size of the specified BLECharacteristic.
#### Syntax
```
bleCharacteristic.valueLength()
```
#### Parameters
None
#### Returns
- The **current value** size of the characteristic (in bytes)
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
Serial.print("value length = ");
Serial.println(switchCharacteristic.valueLength());
```
### `bleCharacteristic.readValue()`
Read the current value of the characteristic. If the characteristic is on a remote device, a read request will be sent.
#### Syntax
```
bleCharacteristic.readValue(buffer, length)
bleCharacteristic.readValue(value)
```
#### Parameters
- **buffer:** byte array to read value into length: size of buffer argument in bytes
- **value**: variable to read value into (by reference)
#### Returns
- **Number of bytes** read
#### Example
```arduino
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
```
### `bleCharacteristic.writeValue()`
Write the value of the characteristic. If the characteristic is on a remote device, a write request or command will be sent.
#### Syntax
```
bleCharacteristic.writeValue(buffer, length)
bleCharacteristic.writeValue(value)
```
#### Parameters
- **buffer**: byte array to write value with
- **length**: number of bytes of the buffer argument to write
- **value**: value to write
#### Returns
- 1 on success,
- 0 on failure
#### Example
```arduino
// read the button pin
int buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState) {
// button changed
oldButtonState = buttonState;
if (buttonState) {
Serial.println("button pressed");
// button is pressed, write 0x01 to turn the LED on
ledCharacteristic.writeValue((byte)0x01);
} else {
Serial.println("button released");
// button is released, write 0x00 to turn the LED off
ledCharacteristic.writeValue((byte)0x00);
}
}
```
### `bleCharacteristic.setEventHandler()`
Set the event handler (callback) function that will be called when the specified event occurs.
#### Syntax
```
bleCharacteristic.setEventHandler(eventType, callback)
```
#### Parameters
- **eventType**: event type (BLESubscribed, BLEUnsubscribed, BLERead, BLEWritten)
- **callback**: function to call when the event occurs
#### Returns
Nothing
#### Example
```arduino
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
// central wrote new value to characteristic, update LED
Serial.print("Characteristic event, written: ");
if (switchCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
```
### `bleCharacteristic.broadcast()`
Broadcast the characteristics value as service data when advertising.
#### Syntax
```
bleCharacteristic.broadcast()
```
#### Parameters
None
#### Returns
- 1 on success,
- 0 on failure
#### Example
```arduino
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify | BLEBroadcast);
buttonCharacteristic.broadcast();
```
### `bleCharacteristic.written()`
Query if the characteristic value has been written by another Bluetooth® Low Energy device.
#### Syntax
```
bleCharacteristic.written()
```
#### Parameters
None
#### Returns
- **true** if the characteristic value has been written by another Bluetooth® Low Energy device,
- **false** otherwise
#### Example
```arduino
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected()) {
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written()) {
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
```
### `bleCharacteristic.subscribed()`
Query if the characteristic has been subscribed to by another Bluetooth® Low Energy device.
#### Syntax
```
bleCharacteristic.subscribed()
```
#### Parameters
None
#### Returns
- **true** if the characteristic value has been subscribed to by another Bluetooth® Low Energy device,
- **false** otherwise
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
if (batteryLevelChar.subscribed()) {
// set a new value , that well be pushed to subscribed Bluetooth® Low Energy devices
batteryLevelChar.writeValue(0xab);
}
```
### `bleCharacteristic.addDescriptor()`
Add a BLEDescriptor to the characteristic.
#### Syntax
```
bleCharacteristic.addDescriptor(bleDescriptor)
```
#### Parameters
- **bleDescriptor**: descriptor to add to the characteristic
#### Returns
Nothing
#### Example
```arduino
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
BLEDescriptor batteryLevelDescriptor("2901", "millis");
batteryLevelChar.addDescriptor(batteryLevelDescriptor);
```
### `bleCharacteristic.descriptorCount()`
Query the number of Bluetooth® Low Energy descriptors discovered for the characteristic.
#### Syntax
```
bleCharacteristic.descriptorCount()
```
#### Parameters
None
#### Returns
- The **number of Bluetooth® Low Energy descriptors** discovered for the characteristic
#### Example
```arduino
// loop the descriptors of the characteristic and explore each
for (int i = 0; i < characteristic.descriptorCount(); i++) {
BLEDescriptor descriptor = characteristic.descriptor(i);
// ...
}
```
### `bleCharacteristic.hasDescriptor()`
Check if a characteristic has a particular descriptor.
#### Syntax
```
bleCharacteristic.hasDescriptor(uuid)
bleCharacteristic.hasDescriptor(uuid, index)
```
#### Parameters
- **index**: index of descriptor
- **uuid**: uuid (as a **String**)
#### Returns
- **true**, if the characteristic has a matching descriptor,
- otherwise **false**.
#### Example
```arduino
if (characteristic.hasDescriptor("2901")) {
Serial.println("characteristic has description descriptor");
}
```
### `bleCharacteristic.descriptor()`
Get a BLEDescriptor that represents a characteristics Bluetooth® Low Energy descriptor.
#### Syntax
```
bleCharacteristic.descriptor(index)
bleCharacteristic.descriptor(uuid)
bleCharacteristic.descriptor(uuid, index)
```
#### Parameters
- **index**: index of descriptor
- **uuid**: uuid (as a **String**)
#### Returns
- BLEDescriptor that represents a characteristics Bluetooth® Low Energy descriptor
#### Example
```arduino
if (characteristic.hasDescriptor("2901")) {
Serial.println("characteristic has description descriptor");
}
```
### `bleCharacteristic.canRead()`
Query if a Bluetooth® Low Energy characteristic is readable.
#### Syntax
```
bleCharacteristic.canRead()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is readable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canRead("2901")) {
Serial.println("characteristic is readable");
}
```
read
Perform a read request for the characteristic.
#### Syntax
```
bleCharacteristic.read()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure
#### Example
```arduino
if (characteristic.read()) {
Serial.println("characteristic value read");
// ...
} else {
Serial.println("error reading characteristic value");
}
```
### `bleCharacteristic.canWrite()`
Query if a Bluetooth® Low Energy characteristic is writable.
#### Syntax
```
bleCharacteristic.canWrite()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is writable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canWrite()) {
Serial.println("characteristic is writable");
}
```
### `bleCharacteristic.canSubscribe()`
Query if a Bluetooth® Low Energy characteristic is subscribable.
#### Syntax
```
bleCharacteristic.canSubscribe()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is subscribable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canSubscribe()) {
Serial.println("characteristic is subscribable");
}
```
### `bleCharacteristic.subscribe()`
Subscribe to a Bluetooth® Low Energy characteristics notification or indications.
#### Syntax
```
bleCharacteristic.subscribe()
```
#### Parameters
None
#### Returns
- **true**, on success,
- **false** on failure
#### Example
```arduino
// ...
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
}
// ...
```
### `bleCharacteristic.canUnsubscribe()`
Query if a Bluetooth® Low Energy characteristic is unsubscribable.
#### Syntax
```
bleCharacteristic.canUnsubscribe()
```
#### Parameters
None
#### Returns
- **true**, if characteristic is unsubscribable,
- **false** otherwise
#### Example
```arduino
if (characteristic.canUnsubscribe()) {
Serial.println("characteristic is unsubscribable");
}
```
### `bleCharacteristic.unsubscribe()`
Unsubscribe to a Bluetooth® Low Energy characteristics notifications or indications.
#### Syntax
```
bleCharacteristic.unsubscribe()
```
#### Parameters
None
#### Returns
- **true**, on success,
- **false** on failure
#### Example
```arduino
// ...
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
}
// ...
simpleKeyCharacteristic.unsubscribe();
```
### `bleCharacteristic.valueUpdated()`
Has the characteristics value been updated via a notification or indication.
#### Syntax
```
bleCharacteristic.valueUpdated()
```
#### Parameters
None
#### Returns
- **true**, if the characteristics value been updated via a notification or indication
#### Example
```arduino
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
```
## BLEDescriptor Class
Used to describe a characteristic the board offers
### `BLEDescriptor()`
Create a new Bluetooth® Low Energy descriptor.
#### Syntax
```
BLEDescriptor(uuid, value, valueSize)
BLEDescriptor(uuid, stringValue)
```
#### Parameters
- **uuid**: 16-bit or 128-bit UUID in string format
- **value**: byte array value
- **valueSize**: size of byte array value
- **stringValue**: value as a string
#### Returns
- New **BLEDescriptor** with the specified **UUID** and value
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
```
### `bleDescriptor.uuid()`
Query the UUID of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.uuid()
```
#### Parameters
None
#### Returns
- **UUID** of the Bluetooth® Low Energy descriptor (as a String).
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
Serial.print("millis label descriptor UUID = ");
Serial.println(millisLabelDescriptor.uuid());
```
### `bleDescriptor.valueSize()`
Query the value size of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.valueSize()
```
#### Parameters
None
#### Returns
- **Value size** (in bytes) of the Bluetooth® Low Energy descriptor.
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
Serial.print("millis label descriptor value size = ");
Serial.println(millisLabelDescriptor.valueSize());
```
### `bleDescriptor.valueLength()`
Query the length, in bytes, of the descriptor current value.
#### Syntax
```
bleDescriptor.valueLength()
```
#### Parameters
None
#### Returns
- **Length of descriptor** value in bytes.
#### Example
```arduino
// read the descriptor value
descriptor.read();
// print out the value of the descriptor
Serial.print(", value 0x");
printData(descriptor.value(), descriptor.valueLength());
// ...
void printData(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b < 16) {
Serial.print("0");
}
Serial.print(b, HEX);
}
}
```
### `bleDescriptor.value()`
Query the value of the specified BLEDescriptor.
#### Syntax
```
bleDescriptor.value()
```
#### Parameters
None
#### Returns
- Value byte array of the **BLE descriptor**.
#### Example
```arduino
BLEDescriptor millisLabelDescriptor("2901", "millis");
int descriptorValueSize = millisLabelDescriptor.valueSize();
byte descriptorValue[descriptorValueSize];
for (int i = 0; i < descriptorValueSize; i++) {
descriptorValue[i] = millisLabelDescriptor.value()[i];
}
```
### `bleDescriptor.readValue()`
Read the current value of the descriptor. If the descriptor is on a remote device, a read request will be sent.
#### Syntax
```
bleDescriptor.readValue(buffer, length)
bleDescriptor.readValue(value)
```
#### Parameters
- **buffer**: byte array to read value into
- **length**: size of buffer argument in bytes
- **value**: variable to read value into (by reference)
#### Returns
- **Number of bytes** read
#### Example
```arduino
byte value = 0;
// get the value, descriptor is 1 byte so use byte value
descriptor.readValue(value);
```
### `bleDescriptor.read()`
Perform a read request for the descriptor.
#### Syntax
```
bleDescriptor.read()
```
#### Parameters
None
#### Returns
- **true**, if successful,
- **false** on failure
#### Example
```arduino
if (descriptor.read()) {
Serial.println("descriptor value read");
// ...
} else {
Serial.println("error reading descriptor value");
}
```
================================================
FILE: docs/readme.md
================================================
# ArduinoBLE library
This library supports all the Arduino boards that have the hardware enabled for Bluetooth® Low Energy and Bluetooth® 4.0 and above; these include Nano 33 BLE, Arduino NANO 33 IoT, Uno WiFi Rev2, MKR WiFi 1010, Nicla Sense ME.
To use this library
``#include ``
## A quick introduction to BLE
Bluetooth® 4.0 includes both traditional Bluetooth®, now labeled "Bluetooth® Classic", and the Bluetooth® Low Energy. Bluetooth® Low Energy is optimized for low power use at low data rates, and was designed to operate from simple lithium coin cell batteries.
Unlike standard Bluetooth® communication basically based on an asynchronous serial connection (UART) a Bluetooth® LE radio acts like a community bulletin board. The computers that connect to it are like community members that read the bulletin board. Each radio acts as either the bulletin board or the reader. If your radio is a bulletin board (called a peripheral device in Bluetooth® LE parlance) it posts data for all radios in the community to read. If your radio is a reader (called a central device in Bluetooth LE terms) it reads from any of the bulletin boards (peripheral devices) that have information about which it cares. You can also think of peripheral devices as the servers in a client-server transaction, because they contain the information that reader radios ask for. Similarly, central devices are the clients of the Bluetooth® LE world because they read information available from the peripherals.

Think of a Bluetooth® LE peripheral device as a bulletin board and central devices as viewers of the board. Central devices view the services, get the data, then move on. Each transaction is quick (a few milliseconds), so multiple central devices can get data from one peripheral.
The information presented by a peripheral is structured as **services**, each of which is subdivided into **characteristics**. You can think of services as the notices on a bulletin board, and characteristics as the individual paragraphs of those notices. If you're a peripheral device, you just update each service characteristic when it needs updating and don't worry about whether the central devices read them or not. If you're a central device, you connect to the peripheral then read the boxes you want. If a given characteristic is readable and writable, then the peripheral and central can both change it.
## Notify
The Bluetooth® LE specification includes a mechanism known as **notify** that lets you know when data's changed. When notify on a characteristic is enabled and the sender writes to it, the new value is automatically sent to the receiver, without the receiver explicitly issuing a read command. This is commonly used for streaming data such as accelerometer or other sensor readings. There's a variation on this specification called **indicate** which works similarly, but in the indicate specification, the reader sends an acknowledgment of the pushed data.
The client-server structure of Bluetooth® LE, combined with the notify characteristic, is generally called a **publish-and-subscribe model**.
## Update a characteristic
Your peripheral should update characteristics when there's a significant change to them. For example, when a switch changes from off to on, update its characteristic. When an analog sensor changes by a significant amount, update its characteristic.
Just as with writing to a characteristic, you could update your characteristics on a regular interval, but this wastes processing power and energy if the characteristic has not changed.
## Central and Peripheral Devices
**Central** devices are **clients**. They read and write data from peripheral devices. **Peripheral** devices are **servers**. They provide data from sensors as readable characteristics, and provide read/writable characteristics to control actuators like motors, lights, and so forth.
## Services, characteristics, and UUIDs
A Bluetooth® Low Energy peripheral will provide **services**, which in turn provide **characteristics**. You can define your own services, or use standard services (see section 3.4 in the [Assigned Numbers document](https://www.bluetooth.com/specifications/assigned-numbers/)).
Services are identified by unique numbers known as UUIDs. You know about UUIDs from other contexts. Standard services have a 16-bit UUID and custom services have a 128-bit UUID. The ability to define services and characteristics depends on the radio you're using and its firmware.
## Service design patterns
A characteristic value can be up to 512 bytes long. This is a key constraint in designing services. Given this limit, you should consider how best to store data about your sensors and actuators most effectively for your application. The simplest design pattern is to store one sensor or actuator value per characteristic, in ASCII encoded values.
|**Characteristic**|**Value**|
|------------------|---------|
|Accelerometer X|200|
|Accelerometer Y|134|
|Accelerometer Z|150|
This is also the most expensive in memory terms, and would take the longest to read. But it's the simplest for development and debugging.
You could also combine readings into a single characteristic, when a given sensor or actuator has multiple values associated with it.
|**Characteristic**|**Value**|
|------------------|---------|
|Motor Speed, Direction|150,1|
|Accelerometer X, Y, Z|200,133,150|
This is more efficient, but you need to be careful not to exceed the 512-byte limit. The accelerometer characteristic above, for example, takes 11 bytes as an ASCII-encoded string.
## Read/write/notify/indicate
There are 4 things a central device can do with a characteristic:
- **Read:** ask the peripheral to send back the current value of the characteristic. Often used for characteristics that don't change very often, for example characteristics used for configuration, version numbers, etc.
- **Write:** modify the value of the characteristic. Often used for things that are like commands, for example telling the peripheral to turn a motor on or off.
- **Indicate** and **Notify:** ask the peripheral to continuously send updated values of the characteristic, without the central having to constantly ask for it.
## Advertising and GAP
BLE devices let other devices know that they exist by advertising using the **General Advertising Profile (GAP)**. Advertising packets can contain a device name, some other information, and also a list of the services it provides.
Advertising packets have a limited size. You will only be able to fit a single 128-bit service UUID in the packet. Make sure the device name is not too long, or you won't even be able to fit that.
You can provide additional services that are not advertised. Central devices will learn about these through the connection/bonding process. Non-advertised services cannot be used to discover devices, though. Sometimes this is not an issue. For example, you may have a custom peripheral device with a custom service, but in your central device app you may know that it also provides the Battery Service and other services.
## GATT
The Bluetooth LE protocol operates on multiple layers. **General Attribute Profile (GATT)** is the layer that defines services and characteristics and enables read/write/notify/indicate operations on them. When reading more about GATT, you may encounter GATT concepts of a "server" and "client". These don't always correspond to central and peripherals. In most cases, though, the peripheral is the GATT server (since it provides the services and characteristics), while the central is the GATT client.
## Library structure
As the library enables multiple types of functionality, there are a number of different classes.
- `BLE` used to enable the Bluetooth® Low Energy module.
- `BLEDevice` used to get information about the devices connected or discovered while scanning.
- `BLEService` used to enable the services board provides or interact with services a remote board provides.
- `BLECharacteristic` used to enable the characteristics board offers in a service or interact with characteristics a remote board provides.
- `BLEDescriptor` used to describe a characteristic the board offers.
================================================
FILE: examples/Central/LedControl/LedControl.ino
================================================
/*
LED Control
This example scans for Bluetooth® Low Energy peripherals until one with the advertised service
"19b10000-e8f2-537e-4f6c-d104768a1214" UUID is found. Once discovered and connected,
it will remotely control the Bluetooth® Low Energy peripheral's LED, when the button is pressed or released.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- Button with pull-up resistor connected to pin 2.
You can use it with another board that is compatible with this library and the
Peripherals -> LED example.
This example code is in the public domain.
*/
#include
// variables for button
const int buttonPin = 2;
int oldButtonState = LOW;
void setup() {
Serial.begin(9600);
while (!Serial);
// configure the button pin as input
pinMode(buttonPin, INPUT);
// initialize the Bluetooth® Low Energy hardware
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - LED control");
// start scanning for peripherals
BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
if (peripheral.localName() != "LED") {
return;
}
// stop scanning
BLE.stopScan();
controlLed(peripheral);
// peripheral disconnected, start scanning again
BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214");
}
}
void controlLed(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// retrieve the LED characteristic
BLECharacteristic ledCharacteristic = peripheral.characteristic("19b10001-e8f2-537e-4f6c-d104768a1214");
if (!ledCharacteristic) {
Serial.println("Peripheral does not have LED characteristic!");
peripheral.disconnect();
return;
} else if (!ledCharacteristic.canWrite()) {
Serial.println("Peripheral does not have a writable LED characteristic!");
peripheral.disconnect();
return;
}
while (peripheral.connected()) {
// while the peripheral is connected
// read the button pin
int buttonState = digitalRead(buttonPin);
if (oldButtonState != buttonState) {
// button changed
oldButtonState = buttonState;
if (buttonState) {
Serial.println("button pressed");
// button is pressed, write 0x01 to turn the LED on
ledCharacteristic.writeValue((byte)0x01);
} else {
Serial.println("button released");
// button is released, write 0x00 to turn the LED off
ledCharacteristic.writeValue((byte)0x00);
}
}
}
Serial.println("Peripheral disconnected");
}
================================================
FILE: examples/Central/PeripheralExplorer/PeripheralExplorer.ino
================================================
/*
Peripheral Explorer
This example scans for Bluetooth® Low Energy peripherals until one with a particular name ("LED")
is found. Then connects, and discovers + prints all the peripheral's attributes.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use it with another board that is compatible with this library and the
Peripherals -> LED example.
This example code is in the public domain.
*/
#include
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - Peripheral Explorer");
// start scanning for peripherals
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
// see if peripheral is a LED
if (peripheral.localName() == "LED") {
// stop scanning
BLE.stopScan();
explorerPeripheral(peripheral);
// peripheral disconnected, we are done
while (1) {
// do nothing
}
}
}
}
void explorerPeripheral(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering attributes ...");
if (peripheral.discoverAttributes()) {
Serial.println("Attributes discovered");
} else {
Serial.println("Attribute discovery failed!");
peripheral.disconnect();
return;
}
// read and print device name of peripheral
Serial.println();
Serial.print("Device name: ");
Serial.println(peripheral.deviceName());
Serial.print("Appearance: 0x");
Serial.println(peripheral.appearance(), HEX);
Serial.println();
// loop the services of the peripheral and explore each
for (int i = 0; i < peripheral.serviceCount(); i++) {
BLEService service = peripheral.service(i);
exploreService(service);
}
Serial.println();
// we are done exploring, disconnect
Serial.println("Disconnecting ...");
peripheral.disconnect();
Serial.println("Disconnected");
}
void exploreService(BLEService service) {
// print the UUID of the service
Serial.print("Service ");
Serial.println(service.uuid());
// loop the characteristics of the service and explore each
for (int i = 0; i < service.characteristicCount(); i++) {
BLECharacteristic characteristic = service.characteristic(i);
exploreCharacteristic(characteristic);
}
}
void exploreCharacteristic(BLECharacteristic characteristic) {
// print the UUID and properties of the characteristic
Serial.print("\tCharacteristic ");
Serial.print(characteristic.uuid());
Serial.print(", properties 0x");
Serial.print(characteristic.properties(), HEX);
// check if the characteristic is readable
if (characteristic.canRead()) {
// read the characteristic value
characteristic.read();
if (characteristic.valueLength() > 0) {
// print out the value of the characteristic
Serial.print(", value 0x");
printData(characteristic.value(), characteristic.valueLength());
}
}
Serial.println();
// loop the descriptors of the characteristic and explore each
for (int i = 0; i < characteristic.descriptorCount(); i++) {
BLEDescriptor descriptor = characteristic.descriptor(i);
exploreDescriptor(descriptor);
}
}
void exploreDescriptor(BLEDescriptor descriptor) {
// print the UUID of the descriptor
Serial.print("\t\tDescriptor ");
Serial.print(descriptor.uuid());
// read the descriptor value
descriptor.read();
// print out the value of the descriptor
Serial.print(", value 0x");
printData(descriptor.value(), descriptor.valueLength());
Serial.println();
}
void printData(const unsigned char data[], int length) {
for (int i = 0; i < length; i++) {
unsigned char b = data[i];
if (b < 16) {
Serial.print("0");
}
Serial.print(b, HEX);
}
}
================================================
FILE: examples/Central/Scan/Scan.ino
================================================
/*
Scan
This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:
address, local name, advertised service UUID's.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
This example code is in the public domain.
*/
#include
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central scan");
// start scanning for peripheral
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral
Serial.println("Discovered a peripheral");
Serial.println("-----------------------");
// print address
Serial.print("Address: ");
Serial.println(peripheral.address());
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// print the RSSI
Serial.print("RSSI: ");
Serial.println(peripheral.rssi());
Serial.println();
}
}
================================================
FILE: examples/Central/ScanCallback/ScanCallback.ino
================================================
/*
Scan Callback
This example scans for Bluetooth® Low Energy peripherals and prints out their advertising details:
address, local name, advertised service UUIDs. Unlike the Scan example, it uses
the callback style APIs and disables filtering so the peripheral discovery is
reported for every single advertisement it makes.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
This example code is in the public domain.
*/
#include
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central scan callback");
// set the discovered event handle
BLE.setEventHandler(BLEDiscovered, bleCentralDiscoverHandler);
// start scanning for peripherals with duplicates
BLE.scan(true);
}
void loop() {
// poll the central for events
BLE.poll();
}
void bleCentralDiscoverHandler(BLEDevice peripheral) {
// discovered a peripheral
Serial.println("Discovered a peripheral");
Serial.println("-----------------------");
// print address
Serial.print("Address: ");
Serial.println(peripheral.address());
// print the local name, if present
if (peripheral.hasLocalName()) {
Serial.print("Local Name: ");
Serial.println(peripheral.localName());
}
// print the advertised service UUIDs, if present
if (peripheral.hasAdvertisedServiceUuid()) {
Serial.print("Service UUIDs: ");
for (int i = 0; i < peripheral.advertisedServiceUuidCount(); i++) {
Serial.print(peripheral.advertisedServiceUuid(i));
Serial.print(" ");
}
Serial.println();
}
// print the RSSI
Serial.print("RSSI: ");
Serial.println(peripheral.rssi());
Serial.println();
}
================================================
FILE: examples/Central/SensorTagButton/SensorTagButton.ino
================================================
/*
SensorTag Button
This example scans for Bluetooth® Low Energy peripherals until a TI SensorTag is discovered.
It then connects to it, discovers the attributes of the 0xffe0 service,
subscribes to the Simple Key Characteristic (UUID 0xffe1). When a button is
pressed on the SensorTag a notification is received and the button state is
outputted to the Serial Monitor when one is pressed.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- TI SensorTag
This example code is in the public domain.
*/
#include
void setup() {
Serial.begin(9600);
while (!Serial);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - SensorTag button");
Serial.println("Make sure to turn on the device.");
// start scanning for peripheral
BLE.scan();
}
void loop() {
// check if a peripheral has been discovered
BLEDevice peripheral = BLE.available();
if (peripheral) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral.address());
Serial.print(" '");
Serial.print(peripheral.localName());
Serial.print("' ");
Serial.print(peripheral.advertisedServiceUuid());
Serial.println();
// Check if the peripheral is a SensorTag, the local name will be:
// "CC2650 SensorTag"
if (peripheral.localName() == "CC2650 SensorTag") {
// stop scanning
BLE.stopScan();
monitorSensorTagButtons(peripheral);
// peripheral disconnected, start scanning again
BLE.scan();
}
}
}
void monitorSensorTagButtons(BLEDevice peripheral) {
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// discover peripheral attributes
Serial.println("Discovering service 0xffe0 ...");
if (peripheral.discoverService("ffe0")) {
Serial.println("Service discovered");
} else {
Serial.println("Attribute discovery failed.");
peripheral.disconnect();
while (1);
return;
}
// retrieve the simple key characteristic
BLECharacteristic simpleKeyCharacteristic = peripheral.characteristic("ffe1");
// subscribe to the simple key characteristic
Serial.println("Subscribing to simple key characteristic ...");
if (!simpleKeyCharacteristic) {
Serial.println("no simple key characteristic found!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.canSubscribe()) {
Serial.println("simple key characteristic is not subscribable!");
peripheral.disconnect();
return;
} else if (!simpleKeyCharacteristic.subscribe()) {
Serial.println("subscription failed!");
peripheral.disconnect();
return;
} else {
Serial.println("Subscribed");
Serial.println("Press the right and left buttons on your SensorTag.");
}
while (peripheral.connected()) {
// while the peripheral is connected
// check if the value of the simple key characteristic has been updated
if (simpleKeyCharacteristic.valueUpdated()) {
// yes, get the value, characteristic is 1 byte so use byte value
byte value = 0;
simpleKeyCharacteristic.readValue(value);
if (value & 0x01) {
// first bit corresponds to the right button
Serial.println("Right button pressed");
}
if (value & 0x02) {
// second bit corresponds to the left button
Serial.println("Left button pressed");
}
}
}
Serial.println("SensorTag disconnected!");
}
================================================
FILE: examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino
================================================
#include
BLEService myService("fff0");
BLEIntCharacteristic myCharacteristic("fff1", BLERead | BLEBroadcast);
// Advertising parameters should have a global scope. Do NOT define them in 'setup' or in 'loop'
const uint8_t manufactData[4] = {0x01, 0x02, 0x03, 0x04};
const uint8_t serviceData[3] = {0x00, 0x01, 0x02};
void setup() {
Serial.begin(9600);
while (!Serial);
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
myService.addCharacteristic(myCharacteristic);
BLE.addService(myService);
// Build scan response data packet
BLEAdvertisingData scanData;
// Set parameters for scan response packet
scanData.setLocalName("Test enhanced advertising");
// Copy set parameters in the actual scan response packet
BLE.setScanResponseData(scanData);
// Build advertising data packet
BLEAdvertisingData advData;
// Set parameters for advertising packet
advData.setManufacturerData(0x004C, manufactData, sizeof(manufactData));
advData.setAdvertisedService(myService);
advData.setAdvertisedServiceData(0xfff0, serviceData, sizeof(serviceData));
// Copy set parameters in the actual advertising packet
BLE.setAdvertisingData(advData);
BLE.advertise();
Serial.println("advertising ...");
}
void loop() {
BLE.poll();
}
================================================
FILE: examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino
================================================
#include
BLEService myService("fff0");
BLEIntCharacteristic myCharacteristic("fff1", BLERead | BLEBroadcast);
// Advertising parameters should have a global scope. Do NOT define them in 'setup' or in 'loop'
const uint8_t completeRawAdvertisingData[] = {0x02,0x01,0x06,0x09,0xff,0x01,0x01,0x00,0x01,0x02,0x03,0x04,0x05};
void setup() {
Serial.begin(9600);
while (!Serial);
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
myService.addCharacteristic(myCharacteristic);
BLE.addService(myService);
// Build advertising data packet
BLEAdvertisingData advData;
// If a packet has a raw data parameter, then all the other parameters of the packet will be ignored
advData.setRawData(completeRawAdvertisingData, sizeof(completeRawAdvertisingData));
// Copy set parameters in the actual advertising packet
BLE.setAdvertisingData(advData);
// Build scan response data packet
BLEAdvertisingData scanData;
scanData.setLocalName("Test advertising raw data");
// Copy set parameters in the actual scan response packet
BLE.setScanResponseData(scanData);
BLE.advertise();
Serial.println("advertising ...");
}
void loop() {
BLE.poll();
}
================================================
FILE: examples/Peripheral/BatteryMonitor/BatteryMonitor.ino
================================================
/*
Battery Monitor
This example creates a Bluetooth® Low Energy peripheral with the standard battery service and
level characteristic. The A0 pin is used to calculate the battery level.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include
// Bluetooth® Low Energy Battery Service
BLEService batteryService("180F");
// Bluetooth® Low Energy Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
int oldBatteryLevel = 0; // last battery level reading from analog input
long previousMillis = 0; // last time the battery level was checked, in ms
void setup() {
Serial.begin(9600); // initialize serial communication
while (!Serial);
pinMode(LED_BUILTIN, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
/* Set a local name for the Bluetooth® Low Energy device
This name will appear in advertising packets
and can be used by remote devices to identify this Bluetooth® Low Energy device
The name can be changed but maybe be truncated based on space left in advertisement packet
*/
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService); // add the service UUID
batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
BLE.addService(batteryService); // Add the battery service
batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic
/* Start advertising Bluetooth® Low Energy. It will start continuously transmitting Bluetooth® Low Energy
advertising packets and will be visible to remote Bluetooth® Low Energy central devices
until it receives a new connection */
// start advertising
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
void loop() {
// wait for a Bluetooth® Low Energy central
BLEDevice central = BLE.central();
// if a central is connected to the peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's BT address:
Serial.println(central.address());
// turn on the LED to indicate the connection:
digitalWrite(LED_BUILTIN, HIGH);
// check the battery level every 200 ms
// while the central is connected:
while (central.connected()) {
long currentMillis = millis();
// if 200 ms have passed, check the battery level:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
updateBatteryLevel();
}
}
// when the central disconnects, turn off the LED:
digitalWrite(LED_BUILTIN, LOW);
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}
}
void updateBatteryLevel() {
/* Read the current voltage level on the A0 analog input pin.
This is used here to simulate the charge level of a battery.
*/
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
if (batteryLevel != oldBatteryLevel) { // if the battery level has changed
Serial.print("Battery Level % is now: "); // print it
Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel); // and update the battery level characteristic
oldBatteryLevel = batteryLevel; // save the level for next comparison
}
}
================================================
FILE: examples/Peripheral/ButtonLED/ButtonLED.ino
================================================
/*
Button LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED and another characteristic that
represents the state of the button.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
- Button connected to pin 4
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include
const int ledPin = LED_BUILTIN; // set ledPin to on-board LED
const int buttonPin = 4; // set buttonPin to digital pin 4
BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, OUTPUT); // use the LED as an output
pinMode(buttonPin, INPUT); // use button pin as an input
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("ButtonLED");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(ledService);
// add the characteristics to the service
ledService.addCharacteristic(ledCharacteristic);
ledService.addCharacteristic(buttonCharacteristic);
// add the service
BLE.addService(ledService);
ledCharacteristic.writeValue(0);
buttonCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("Bluetooth® device active, waiting for connections...");
}
void loop() {
// poll for Bluetooth® Low Energy events
BLE.poll();
// read the current button pin state
char buttonValue = digitalRead(buttonPin);
// has the value changed since the last read
bool buttonChanged = (buttonCharacteristic.value() != buttonValue);
if (buttonChanged) {
// button state changed, update characteristics
ledCharacteristic.writeValue(buttonValue);
buttonCharacteristic.writeValue(buttonValue);
}
if (ledCharacteristic.written() || buttonChanged) {
// update LED, either central has written to characteristic or button state has changed
if (ledCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
}
================================================
FILE: examples/Peripheral/CallbackLED/CallbackLED.ino
================================================
/*
Callback LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED. The callback features of the
library are used.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
const int ledPin = LED_BUILTIN; // pin to use for the LED
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, OUTPUT); // use the LED pin as an output
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("LEDCallback");
// set the UUID for the service this peripheral advertises
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// assign event handlers for connected, disconnected to peripheral
BLE.setEventHandler(BLEConnected, blePeripheralConnectHandler);
BLE.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);
// assign event handlers for characteristic
switchCharacteristic.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
switchCharacteristic.setValue(0);
// start advertising
BLE.advertise();
Serial.println(("Bluetooth® device active, waiting for connections..."));
}
void loop() {
// poll for Bluetooth® Low Energy events
BLE.poll();
}
void blePeripheralConnectHandler(BLEDevice central) {
// central connected event handler
Serial.print("Connected event, central: ");
Serial.println(central.address());
}
void blePeripheralDisconnectHandler(BLEDevice central) {
// central disconnected event handler
Serial.print("Disconnected event, central: ");
Serial.println(central.address());
}
void switchCharacteristicWritten(BLEDevice central, BLECharacteristic characteristic) {
// unused parameters
(void)central;
(void)characteristic;
// central wrote new value to characteristic, update LED
Serial.print("Characteristic event, written: ");
if (switchCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
================================================
FILE: examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino
================================================
/*
Battery Monitor
This example creates a BLE peripheral with the standard battery service and
level characteristic. The A0 pin is used to calculate the battery level.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic BLE central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include
#define PAIR_BUTTON 3 // button for pairing
#define PAIR_LED 24 // LED used to signal pairing
#define PAIR_LED_ON LOW // Blue LED on Nano BLE has inverted logic
#define PAIR_LED_OFF HIGH // ... so these are inverted as well
#define PAIR_INTERVAL 30000 // interval for pairing after button press in ms
#define CTRL_LED LED_BUILTIN
// BLE Battery Service
BLEService batteryService("180F");
// BLE Battery Level Characteristic
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
BLEStringCharacteristic stringcharacteristic("183E", BLERead | BLEWrite, 31);
// Add BLEEncryption tag to require pairing. This controls the LED.
BLEUnsignedCharCharacteristic secretValue("2a3F", BLERead | BLEWrite | BLEEncryption);
int oldBatteryLevel = 0; // last battery level reading from analog input
unsigned long previousMillis = 0; // last time the battery level was checked, in ms
unsigned long pairingStarted = 0; // pairing start time when button is pressed
bool wasConnected = 0;
bool acceptOrReject = true;
void setup() {
Serial.begin(9600); // initialize serial communication
while (!Serial);
pinMode(CTRL_LED, OUTPUT); // initialize the built-in LED pin to indicate when a central is connected
pinMode(PAIR_LED, OUTPUT);
pinMode(PAIR_BUTTON, INPUT_PULLUP);
Serial.println("Serial connected");
// Callback function with confirmation code when new device is pairing.
BLE.setDisplayCode([](uint32_t confirmCode){
Serial.println("New device pairing request.");
Serial.print("Confirm code matches pairing device: ");
char code[7];
sprintf(code, "%06d", confirmCode);
Serial.println(code);
});
// Callback to allow accepting or rejecting pairing
BLE.setBinaryConfirmPairing([](){
Serial.print("Should we confirm pairing? ");
delay(5000);
if(acceptOrReject){
acceptOrReject = false;
Serial.println("yes");
return true;
}else{
acceptOrReject = true;
Serial.println("no");
return false;
}
});
// IRKs are keys that identify the true owner of a random mac address.
// Add IRKs of devices you are bonded with.
BLE.setGetIRKs([](uint8_t* nIRKs, uint8_t** BDaddrTypes, uint8_t*** BDAddrs, uint8_t*** IRKs){
// Set to number of devices
*nIRKs = 2;
*BDAddrs = new uint8_t*[*nIRKs];
*IRKs = new uint8_t*[*nIRKs];
*BDaddrTypes = new uint8_t[*nIRKs];
// Set these to the mac and IRK for your bonded devices as printed in the serial console after bonding.
uint8_t device1Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device1IRK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2IRK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
(*BDaddrTypes)[0] = 0; // Type 0 is for pubc address, type 1 is for static random
(*BDAddrs)[0] = new uint8_t[6];
(*IRKs)[0] = new uint8_t[16];
memcpy((*IRKs)[0] , device1IRK,16);
memcpy((*BDAddrs)[0], device1Mac, 6);
(*BDaddrTypes)[1] = 0;
(*BDAddrs)[1] = new uint8_t[6];
(*IRKs)[1] = new uint8_t[16];
memcpy((*IRKs)[1] , device2IRK,16);
memcpy((*BDAddrs)[1], device2Mac, 6);
return 1;
});
// The LTK is the secret key which is used to encrypt bluetooth traffic
BLE.setGetLTK([](uint8_t* address, uint8_t* LTK){
// address is input
Serial.print("Received request for address: ");
btct.printBytes(address,6);
// Set these to the MAC and LTK of your devices after bonding.
uint8_t device1Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device1LTK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2Mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t device2LTK[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if(memcmp(device1Mac, address, 6) == 0) {
memcpy(LTK, device1LTK, 16);
return 1;
}else if(memcmp(device2Mac, address, 6) == 0) {
memcpy(LTK, device2LTK, 16);
return 1;
}
return 0;
});
BLE.setStoreIRK([](uint8_t* address, uint8_t* IRK){
Serial.print(F("New device with MAC : "));
btct.printBytes(address,6);
Serial.print(F("Need to store IRK : "));
btct.printBytes(IRK,16);
return 1;
});
BLE.setStoreLTK([](uint8_t* address, uint8_t* LTK){
Serial.print(F("New device with MAC : "));
btct.printBytes(address,6);
Serial.print(F("Need to store LTK : "));
btct.printBytes(LTK,16);
return 1;
});
while(1){
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("BT init");
delay(200);
/* Set a local name for the BLE device
This name will appear in advertising packets
and can be used by remote devices to identify this BLE device
The name can be changed but maybe be truncated based on space left in advertisement packet
*/
BLE.setDeviceName("Arduino");
BLE.setLocalName("BatteryMonitor");
BLE.setAdvertisedService(batteryService); // add the service UUID
batteryService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
batteryService.addCharacteristic(stringcharacteristic);
batteryService.addCharacteristic(secretValue);
BLE.addService(batteryService); // Add the battery service
batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic
const char* stringCharValue = "string";
stringcharacteristic.writeValue(stringCharValue);
secretValue.writeValue(0);
delay(1000);
// prevent pairing until button is pressed (will show a pairing rejected message)
BLE.setPairable(false);
/* Start advertising BLE. It will start continuously transmitting BLE
advertising packets and will be visible to remote BLE central devices
until it receives a new connection */
// start advertising
if(!BLE.advertise()){
Serial.println("failed to advertise bluetooth.");
BLE.stopAdvertise();
delay(500);
}else{
Serial.println("advertising...");
break;
}
BLE.end();
delay(100);
}
}
void loop() {
// wait for a BLE central
BLEDevice central = BLE.central();
// If button is pressed, allow pairing for 30 sec
if (!BLE.pairable() && digitalRead(PAIR_BUTTON) == LOW){
pairingStarted = millis();
BLE.setPairable(Pairable::ONCE);
Serial.println("Accepting pairing for 30 s");
} else if (BLE.pairable() && millis() > pairingStarted + PAIR_INTERVAL){
BLE.setPairable(false);
Serial.println("No longer accepting pairing");
}
// Make LED blink while pairing is allowed, steady ON when paired
bool led_status = BLE.pairable() ? (millis()%400)<200 : BLE.paired();
digitalWrite(PAIR_LED, led_status ? PAIR_LED_ON : PAIR_LED_OFF);
// if a central is connected to the peripheral:
if (central && central.connected()) {
if (!wasConnected){
wasConnected = true;
Serial.print("Connected to central: ");
// print the central's BT address:
Serial.println(central.address());
}
// check the battery level every 200ms
// while the central is connected:
long currentMillis = millis();
// if 200ms have passed, check the battery level:
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
updateBatteryLevel();
digitalWrite(CTRL_LED, secretValue.value()>0 ? HIGH : LOW);
}
} else if (wasConnected){
wasConnected = false;
Serial.print("Disconnected from central: ");
Serial.println(central.address());
}
}
void updateBatteryLevel() {
/* Read the current voltage level on the A0 analog input pin.
This is used here to simulate the charge level of a battery.
*/
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
if (batteryLevel != oldBatteryLevel) { // if the battery level has changed
// Serial.print("Battery Level % is now: "); // print it
// Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel); // and update the battery level characteristic
oldBatteryLevel = batteryLevel; // save the level for next comparison
}
}
================================================
FILE: examples/Peripheral/LED/LED.ino
================================================
/*
LED
This example creates a Bluetooth® Low Energy peripheral with service that contains a
characteristic to control an LED.
The circuit:
- Arduino MKR WiFi 1010, Arduino Uno WiFi Rev2 board, Arduino Nano 33 IoT,
Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board.
You can use a generic Bluetooth® Low Energy central app, like LightBlue (iOS and Android) or
nRF Connect (Android), to interact with the services and characteristics
created in this sketch.
This example code is in the public domain.
*/
#include
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service
// Bluetooth® Low Energy LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
const int ledPin = LED_BUILTIN; // pin to use for the LED
void setup() {
Serial.begin(9600);
while (!Serial);
// set LED pin to output mode
pinMode(ledPin, OUTPUT);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
// set advertised local name and service UUID:
BLE.setLocalName("LED");
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
// add service
BLE.addService(ledService);
// set the initial value for the characteristic:
switchCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("BLE LED Peripheral");
}
void loop() {
// listen for Bluetooth® Low Energy peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected()) {
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written()) {
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
}
================================================
FILE: extras/arduino-ble-parser.py
================================================
'''
Convert ArduinoBLE debug files into Btsnoop files ready to be analyzed using wireshark or hcidump
Btsnoop file format reference
https://www.fte.com/WebHelpII/Sodera/Content/Technical_Information/BT_Snoop_File_Format.htm
'''
import os
import argparse
DEBUG = False
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='inputPath', type=str, required=True, help='input file containing debug log')
parser.add_argument('-o', dest='outputPath', type=str, required=True, help='result file that will contain the btsnoop encoded debug file')
args = parser.parse_args()
# Extract only hci debug messages
def extractHCIDebugPrint(inputPath, outputPath):
inputFile = open(inputPath, 'r')
outputFile = open(outputPath, 'w')
for inputLine in inputFile:
lineItems = inputLine.split()
if (len(lineItems) < 7) or (lineItems[1] != "->") or (lineItems[2] != "HCI"):
if (len(lineItems) < 4) or (lineItems[0] != "HCI") or ((lineItems[3] != "<-") and (lineItems[3] != "->")):
continue
outputFile.write(inputLine)
outputFile.close()
# Return packet in btsnoop format
def buildBinaryPacket(hciMessage, hciDirection, hciType):
commandFlag = 1 if (hciType == "COMMAND" or hciType == "EVENT") else 0
directionFlag = 0 if (hciDirection == "TX") else 1
flagHex = ("0" * 7) + str((commandFlag * 2) + directionFlag)
timestampHex = "0" * 16
packetDropHex = "0" * 8
dataLengthHex = format( (int(len(hciMessage) / 2)), 'x')
packetLengthHex = ("0" * (8 - len(dataLengthHex))) + dataLengthHex
binaryPacket = bytearray.fromhex(packetLengthHex + packetLengthHex + flagHex + packetDropHex + timestampHex + hciMessage)
if DEBUG:
print(len(hciMessage))
print(dataLengthHex)
print(packetLengthHex)
print(flagHex)
print('\n')
return binaryPacket
def buildBinaryHeader():
defaultHeader = "6274736e6f6f700000000001000003ea"
binaryHeader = bytearray.fromhex(defaultHeader)
return binaryHeader
def convertToBtsnoop(inputPath, outputPath):
# Open output file and write the Btsnoop header
outputFile = open(outputPath,'wb')
header = buildBinaryHeader()
outputFile.write(header)
# Open input file containing HCI debug packets
inputFile = open(inputPath, 'r')
for inputLine in inputFile:
lineItems = inputLine.split()
# For a safer script, do not use indexes but look for symbols in the line
baseIndex = lineItems.index("HCI")
hciMessage = lineItems[baseIndex + 4]
hciDirection = lineItems[baseIndex + 2]
hciType = lineItems[baseIndex + 1]
# Build and write the encoded line
btsnoopPacket = buildBinaryPacket(hciMessage, hciDirection, hciType)
outputFile.write(btsnoopPacket)
if DEBUG:
print(hciDirection)
print(hciMessage)
print(hciType)
print('\n')
outputFile.close()
inputPath = args.inputPath
outputPath = args.outputPath
tempFile = "temp-debug-print.txt"
# Run
extractHCIDebugPrint(inputPath,tempFile)
convertToBtsnoop(tempFile, outputPath)
# Delete temp file
os.remove(tempFile)
================================================
FILE: extras/test/.gitignore
================================================
build
### CMake ###
CMakeLists.txt.user
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
_deps
### CMake Patch ###
# External projects
*-prefix/
================================================
FILE: extras/test/CMakeLists.txt
================================================
##########################################################################
set(CMAKE_VERBOSE_MAKEFILE ON)
cmake_minimum_required(VERSION 3.5)
##########################################################################
project(testArduinoBLE)
Include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.4.0
)
FetchContent_MakeAvailable(Catch2)
##########################################################################
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
##########################################################################
set(COMMON_TEST_SRCS
src/test_main.cpp
src/Arduino.cpp
src/util/itoa.c
src/util/TestUtil.cpp
src/util/String.cpp
src/util/Common.cpp
)
set(DUT_SRCS
../../src/utility/BLEUuid.cpp
../../src/BLEDevice.cpp
../../src/BLECharacteristic.cpp
../../src/BLEDescriptor.cpp
../../src/BLEService.cpp
../../src/BLEAdvertisingData.cpp
../../src/utility/ATT.cpp
../../src/utility/GAP.cpp
../../src/utility/HCI.cpp
../../src/utility/GATT.cpp
../../src/utility/L2CAPSignaling.cpp
../../src/utility/keyDistribution.cpp
../../src/utility/bitDescriptions.cpp
../../src/utility/btct.cpp
../../src/local/BLELocalAttribute.cpp
../../src/local/BLELocalCharacteristic.cpp
../../src/local/BLELocalDescriptor.cpp
../../src/local/BLELocalDevice.cpp
../../src/local/BLELocalService.cpp
../../src/remote/BLERemoteAttribute.cpp
../../src/remote/BLERemoteCharacteristic.cpp
../../src/remote/BLERemoteDescriptor.cpp
../../src/remote/BLERemoteDevice.cpp
../../src/remote/BLERemoteService.cpp
../../src/BLEStringCharacteristic.cpp
../../src/BLETypedCharacteristics.cpp
)
set(TEST_TARGET_UUID_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_uuid/test_uuid.cpp
# DUT files
#${DUT_SRCS}
../../src/utility/BLEUuid.cpp
)
set(TEST_TARGET_DISC_DEVICE_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_discovered_device/test_discovered_device.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_discovered_device/FakeGAP.cpp
)
set(TEST_TARGET_ADVERTISING_DATA_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_advertising_data/test_advertising_data.cpp
src/test_advertising_data/test_service.cpp
src/test_advertising_data/test_local_name.cpp
src/test_advertising_data/test_manufacturer.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_advertising_data/FakeBLELocalDevice.cpp
)
set(TEST_TARGET_CHARACTERISTIC_SRCS
# Test files
${COMMON_TEST_SRCS}
src/test_characteristic/test_permissions.cpp
src/test_characteristic/test_writeValue.cpp
# DUT files
${DUT_SRCS}
# Fake classes files
src/util/HCIFakeTransport.cpp
src/test_advertising_data/FakeBLELocalDevice.cpp
)
##########################################################################
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} "--coverage")
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "--coverage")
##########################################################################
add_executable(TEST_TARGET_UUID ${TEST_TARGET_UUID_SRCS})
add_executable(TEST_TARGET_DISC_DEVICE ${TEST_TARGET_DISC_DEVICE_SRCS})
add_executable(TEST_TARGET_ADVERTISING_DATA ${TEST_TARGET_ADVERTISING_DATA_SRCS})
add_executable(TEST_TARGET_CHARACTERISTIC_DATA ${TEST_TARGET_CHARACTERISTIC_SRCS})
##########################################################################
include_directories(include)
include_directories(include/util)
include_directories(../../src)
include_directories(../../src/local)
include_directories(../../src/remote)
include_directories(../../src/utility)
target_include_directories(TEST_TARGET_DISC_DEVICE PUBLIC include/test_discovered_device)
target_include_directories(TEST_TARGET_ADVERTISING_DATA PUBLIC include/test_advertising_data)
target_include_directories(TEST_TARGET_CHARACTERISTIC_DATA PUBLIC include/test_advertising_data)
##########################################################################
target_compile_definitions(TEST_TARGET_DISC_DEVICE PUBLIC FAKE_GAP)
target_compile_definitions(TEST_TARGET_ADVERTISING_DATA PUBLIC FAKE_BLELOCALDEVICE)
target_compile_definitions(TEST_TARGET_CHARACTERISTIC_DATA PUBLIC FAKE_BLELOCALDEVICE)
##########################################################################
# Build unit tests as a post build step
add_custom_command(TARGET TEST_TARGET_UUID POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_UUID
)
add_custom_command(TARGET TEST_TARGET_DISC_DEVICE POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_DISC_DEVICE
)
add_custom_command(TARGET TEST_TARGET_ADVERTISING_DATA POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_ADVERTISING_DATA
)
add_custom_command(TARGET TEST_TARGET_CHARACTERISTIC_DATA POST_BUILD
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TEST_TARGET_CHARACTERISTIC_DATA
)
##########################################################################
target_link_libraries( TEST_TARGET_UUID Catch2WithMain )
target_link_libraries( TEST_TARGET_DISC_DEVICE Catch2WithMain )
target_link_libraries( TEST_TARGET_ADVERTISING_DATA Catch2WithMain )
target_link_libraries( TEST_TARGET_CHARACTERISTIC_DATA Catch2WithMain )
================================================
FILE: extras/test/include/Arduino.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef TEST_ARDUINO_H_
#define TEST_ARDUINO_H_
/******************************************************************************
INCLUDE
******************************************************************************/
#include
#include
#include "String.h"
#include "Stream.h"
#include "itoa.h"
#include "Common.h"
/******************************************************************************
TYPEDEF
******************************************************************************/
typedef arduino::String String;
typedef bool boolean;
#if defined(__cplusplus)
#undef F
// C++11 F replacement declaration
template
auto F(T1&& A)
-> const arduino::__FlashStringHelper*
{
return (const arduino::__FlashStringHelper*)A;
}
#endif
/******************************************************************************
FUNCTION PROTOTYPES
******************************************************************************/
#endif /* TEST_ARDUINO_H_ */
================================================
FILE: extras/test/include/test_advertising_data/FakeBLELocalDevice.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _FAKE_BLELOCALDEVICE_H_
#define _FAKE_BLELOCALDEVICE_H_
#define private public
#define protected public
#include "BLELocalDevice.h"
class FakeBLELocalDevice : public BLELocalDevice {
public:
FakeBLELocalDevice();
virtual ~FakeBLELocalDevice();
int advertise();
};
#endif
================================================
FILE: extras/test/include/test_discovered_device/FakeGAP.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _FAKE_GAP_H_
#define _FAKE_GAP_H_
#define private public
#define protected public
#include "GAP.h"
class FakeGAPClass : public GAPClass {
public:
FakeGAPClass();
virtual ~FakeGAPClass();
};
#endif
================================================
FILE: extras/test/include/util/Common.h
================================================
#pragma once
#include
#ifdef __cplusplus
extern "C"{
#endif
void yield(void);
typedef enum {
LOW = 0,
HIGH = 1,
CHANGE = 2,
FALLING = 3,
RISING = 4,
} PinStatus;
typedef enum {
INPUT = 0x0,
OUTPUT = 0x1,
INPUT_PULLUP = 0x2,
INPUT_PULLDOWN = 0x3,
} PinMode;
typedef enum {
LSBFIRST = 0,
MSBFIRST = 1,
} BitOrder;
#define PI 3.1415926535897932384626433832795
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105
#define EULER 2.718281828459045235360287471352
#define SERIAL 0x0
#define DISPLAY 0x1
#ifndef constrain
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#endif
#ifndef radians
#define radians(deg) ((deg)*DEG_TO_RAD)
#endif
#ifndef degrees
#define degrees(rad) ((rad)*RAD_TO_DEG)
#endif
#ifndef sq
#define sq(x) ((x)*(x))
#endif
typedef void (*voidFuncPtr)(void);
typedef void (*voidFuncPtrParam)(void*);
// interrupts() / noInterrupts() must be defined by the core
#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitToggle(value, bit) ((value) ^= (1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
#ifndef bit
#define bit(b) (1UL << (b))
#endif
/* TODO: request for removal */
typedef bool boolean;
typedef uint8_t byte;
typedef uint16_t word;
void init(void);
void initVariant(void);
int atexit(void (*func)()) __attribute__((weak));
int main() __attribute__((weak));
#ifdef EXTENDED_PIN_MODE
// Platforms who wnat to declare more than 256 pins need to define EXTENDED_PIN_MODE globally
typedef uint32_t pin_size_t;
#else
typedef uint8_t pin_size_t;
#endif
void pinMode(pin_size_t pinNumber, PinMode pinMode);
void digitalWrite(pin_size_t pinNumber, PinStatus status);
PinStatus digitalRead(pin_size_t pinNumber);
int analogRead(pin_size_t pinNumber);
void analogReference(uint8_t mode);
void analogWrite(pin_size_t pinNumber, int value);
unsigned long millis(void);
unsigned long micros(void);
void delay(unsigned long);
void delayMicroseconds(unsigned int us);
unsigned long pulseIn(pin_size_t pin, uint8_t state, unsigned long timeout);
unsigned long pulseInLong(pin_size_t pin, uint8_t state, unsigned long timeout);
void shiftOut(pin_size_t dataPin, pin_size_t clockPin, BitOrder bitOrder, uint8_t val);
pin_size_t shiftIn(pin_size_t dataPin, pin_size_t clockPin, BitOrder bitOrder);
void attachInterrupt(pin_size_t interruptNumber, voidFuncPtr callback, PinStatus mode);
void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, PinStatus mode, void* param);
void detachInterrupt(pin_size_t interruptNumber);
void setup(void);
void loop(void);
#ifdef __cplusplus
} // extern "C"
#endif
#ifdef __cplusplus
template
auto min(const T& a, const L& b) -> decltype((b < a) ? b : a)
{
return (b < a) ? b : a;
}
template
auto max(const T& a, const L& b) -> decltype((b < a) ? b : a)
{
return (a < b) ? b : a;
}
#else
#ifndef min
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#endif
#ifndef max
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#endif
#endif
#ifdef __cplusplus
/* C++ prototypes */
uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);
#define word(...) makeWord(__VA_ARGS__)
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
void noTone(uint8_t _pin);
// WMath prototypes
long random(long);
long random(long, long);
void randomSeed(unsigned long);
long map(long, long, long, long, long);
#endif // __cplusplus
================================================
FILE: extras/test/include/util/HCIFakeTransport.h
================================================
//#include "Common.h"
#pragma once
#include "HCITransport.h"
class HCIFakeTransportClass : public HCITransportInterface
{
public:
HCIFakeTransportClass() {};
~HCIFakeTransportClass() {};
int begin() {return 0;}
void end() {return;}
void wait(unsigned long timeout) {return;}
int available() {return 0;}
int peek() {return 0;}
int read() {return 0;}
size_t write(const uint8_t* data, size_t length) {return 0;}
};
================================================
FILE: extras/test/include/util/Stream.h
================================================
//#include "Common.h"
#pragma once
#define DEC 10
#define HEX 16
#define OCT 8
#define BIN 2
class Stream
{
public:
Stream(const char *name = NULL);
~Stream();
void flush() {}
size_t print(const char[]) { return 0; }
size_t print(char) { return 0; }
size_t print(unsigned char, int) { return 0; }
size_t print(int, int) { return 0; }
size_t print(unsigned int, int) { return 0; }
size_t print(long, int) { return 0; }
size_t print(unsigned long, int) { return 0; }
size_t print(long long, int) { return 0; }
size_t print(unsigned long long, int) { return 0; }
size_t print(double, int) { return 0; }
size_t print(void) { return 0; }
size_t println(const char[]) { return 0; }
size_t println(char) { return 0; }
size_t println(unsigned char, int) { return 0; }
size_t println(int, int) { return 0; }
size_t println(unsigned int, int) { return 0; }
size_t println(long, int) { return 0; }
size_t println(unsigned long, int) { return 0; }
size_t println(long long, int) { return 0; }
size_t println(unsigned long long, int) { return 0; }
size_t println(double, int) { return 0; }
size_t println(void) { return 0; }
};
================================================
FILE: extras/test/include/util/String.h
================================================
/*
String library for Wiring & Arduino
...mostly rewritten by Paul Stoffregen...
Copyright (c) 2009-10 Hernando Barragan. All right reserved.
Copyright 2011, Paul Stoffregen, paul@pjrc.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef __cplusplus
#ifndef __ARDUINO_STRINGS__
#define __ARDUINO_STRINGS__
#include
#include
#include
namespace arduino {
// When compiling programs with this class, the following gcc parameters
// dramatically increase performance and memory (RAM) efficiency, typically
// with little or no increase in code size.
// -felide-constructors
// -std=c++0x
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast(PSTR(string_literal)))
// An inherited class for holding the result of a concatenation. These
// result objects are assumed to be writable by subsequent concatenations.
class StringSumHelper;
// The string class
class String
{
friend class StringSumHelper;
// use a function pointer to allow for "if (s)" without the
// complications of an operator bool(). for more information, see:
// http://www.artima.com/cppsource/safebool.html
typedef void (String::*StringIfHelperType)() const;
void StringIfHelper() const {}
public:
// constructors
// creates a copy of the initial value.
// if the initial value is null or invalid, or if memory allocation
// fails, the string will be marked as invalid (i.e. "if (s)" will
// be false).
String(const char *cstr = "");
String(const String &str);
String(const __FlashStringHelper *str);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String(String &&rval);
String(StringSumHelper &&rval);
#endif
explicit String(char c);
explicit String(unsigned char, unsigned char base=10);
explicit String(int, unsigned char base=10);
explicit String(unsigned int, unsigned char base=10);
explicit String(long, unsigned char base=10);
explicit String(unsigned long, unsigned char base=10);
//explicit String(float, unsigned char decimalPlaces=2);
//explicit String(double, unsigned char decimalPlaces=2);
~String(void);
// memory management
// return true on success, false on failure (in which case, the string
// is left unchanged). reserve(0), if successful, will validate an
// invalid string (i.e., "if (s)" will be true afterwards)
unsigned char reserve(unsigned int size);
inline unsigned int length(void) const {return len;}
// creates a copy of the assigned value. if the value is null or
// invalid, or if the memory allocation fails, the string will be
// marked as invalid ("if (s)" will be false).
String & operator = (const String &rhs);
String & operator = (const char *cstr);
//String & operator = (const __FlashStringHelper *str);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & operator = (String &&rval);
String & operator = (StringSumHelper &&rval);
#endif
// concatenate (works w/ built-in types)
// returns true on success, false on failure (in which case, the string
// is left unchanged). if the argument is null or invalid, the
// concatenation is considered unsucessful.
unsigned char concat(const String &str);
unsigned char concat(const char *cstr);
unsigned char concat(char c);
unsigned char concat(unsigned char c);
unsigned char concat(int num);
unsigned char concat(unsigned int num);
unsigned char concat(long num);
unsigned char concat(unsigned long num);
unsigned char concat(float num);
//unsigned char concat(double num);
unsigned char concat(const __FlashStringHelper * str);
// if there's not enough memory for the concatenated value, the string
// will be left unchanged (but this isn't signalled in any way)
String & operator += (const String &rhs) {concat(rhs); return (*this);}
String & operator += (const char *cstr) {concat(cstr); return (*this);}
String & operator += (char c) {concat(c); return (*this);}
String & operator += (unsigned char num) {concat(num); return (*this);}
String & operator += (int num) {concat(num); return (*this);}
String & operator += (unsigned int num) {concat(num); return (*this);}
String & operator += (long num) {concat(num); return (*this);}
String & operator += (unsigned long num) {concat(num); return (*this);}
String & operator += (float num) {concat(num); return (*this);}
//String & operator += (double num) {concat(num); return (*this);}
String & operator += (const __FlashStringHelper *str){concat(str); return (*this);}
friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs);
friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr);
friend StringSumHelper & operator + (const StringSumHelper &lhs, char c);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, long num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, float num);
//friend StringSumHelper & operator + (const StringSumHelper &lhs, double num);
//friend StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs);
// comparison (only works w/ Strings and "strings")
operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; }
int compareTo(const String &s) const;
int compareTo(const char *cstr) const;
unsigned char equals(const String &s) const;
unsigned char equals(const char *cstr) const;
friend unsigned char operator == (const String &a, const String &b) { return a.equals(b); }
friend unsigned char operator == (const String &a, const char *b) { return a.equals(b); }
friend unsigned char operator == (const char *a, const String &b) { return b == a; }
friend unsigned char operator < (const String &a, const String &b) { return a.compareTo(b) < 0; }
friend unsigned char operator < (const String &a, const char *b) { return a.compareTo(b) < 0; }
friend unsigned char operator < (const char *a, const String &b) { return b.compareTo(a) > 0; }
friend unsigned char operator != (const String &a, const String &b) { return !(a == b); }
friend unsigned char operator != (const String &a, const char *b) { return !(a == b); }
friend unsigned char operator != (const char *a, const String &b) { return !(a == b); }
friend unsigned char operator > (const String &a, const String &b) { return b < a; }
friend unsigned char operator > (const String &a, const char *b) { return b < a; }
friend unsigned char operator > (const char *a, const String &b) { return b < a; }
friend unsigned char operator <= (const String &a, const String &b) { return !(b < a); }
friend unsigned char operator <= (const String &a, const char *b) { return !(b < a); }
friend unsigned char operator <= (const char *a, const String &b) { return !(b < a); }
friend unsigned char operator >= (const String &a, const String &b) { return !(a < b); }
friend unsigned char operator >= (const String &a, const char *b) { return !(a < b); }
friend unsigned char operator >= (const char *a, const String &b) { return !(a < b); }
unsigned char equalsIgnoreCase(const String &s) const;
unsigned char startsWith( const String &prefix) const;
unsigned char startsWith(const String &prefix, unsigned int offset) const;
unsigned char endsWith(const String &suffix) const;
// character acccess
char charAt(unsigned int index) const;
void setCharAt(unsigned int index, char c);
char operator [] (unsigned int index) const;
char& operator [] (unsigned int index);
void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;
void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const
{ getBytes((unsigned char *)buf, bufsize, index); }
const char* c_str() const { return buffer; }
char* begin() { return buffer; }
char* end() { return buffer + length(); }
const char* begin() const { return c_str(); }
const char* end() const { return c_str() + length(); }
// search
int indexOf( char ch ) const;
int indexOf( char ch, unsigned int fromIndex ) const;
int indexOf( const String &str ) const;
int indexOf( const String &str, unsigned int fromIndex ) const;
int lastIndexOf( char ch ) const;
int lastIndexOf( char ch, unsigned int fromIndex ) const;
int lastIndexOf( const String &str ) const;
int lastIndexOf( const String &str, unsigned int fromIndex ) const;
String substring( unsigned int beginIndex ) const { return substring(beginIndex, len); };
String substring( unsigned int beginIndex, unsigned int endIndex ) const;
// modification
void replace(char find, char replace);
void replace(const String& find, const String& replace);
void remove(unsigned int index);
void remove(unsigned int index, unsigned int count);
void toLowerCase(void);
void toUpperCase(void);
void trim(void);
// parsing/conversion
long toInt(void) const;
float toFloat(void) const;
double toDouble(void) const;
protected:
char *buffer; // the actual char array
unsigned int capacity; // the array length minus one (for the '\0')
unsigned int len; // the String length (not counting the '\0')
protected:
void init(void);
void invalidate(void);
unsigned char changeBuffer(unsigned int maxStrLen);
unsigned char concat(const char *cstr, unsigned int length);
// copy and move
String & copy(const char *cstr, unsigned int length);
String & copy(const __FlashStringHelper *pstr, unsigned int length);
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
void move(String &rhs);
#endif
};
class StringSumHelper : public String
{
public:
StringSumHelper(const String &s) : String(s) {}
StringSumHelper(const char *p) : String(p) {}
StringSumHelper(char c) : String(c) {}
StringSumHelper(unsigned char num) : String(num) {}
StringSumHelper(int num) : String(num) {}
StringSumHelper(unsigned int num) : String(num) {}
StringSumHelper(long num) : String(num) {}
StringSumHelper(unsigned long num) : String(num) {}
//StringSumHelper(float num) : String(num) {}
//StringSumHelper(double num) : String(num) {}
};
} // namespace arduino
#endif // __cplusplus
#endif // __ARDUINO_STRINGS__
================================================
FILE: extras/test/include/util/TestUtil.h
================================================
/*
* Copyright (c) 2020 Arduino. All rights reserved.
*/
================================================
FILE: extras/test/include/util/itoa.h
================================================
/*
Copyright (c) 2016 Arduino LLC. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
// Standard C functions required in Arduino API
// If these functions are not provided by the standard library, the
// core should supply an implementation of them.
#ifdef __cplusplus
extern "C" {
#endif
extern char* itoa(int value, char *string, int radix);
extern char* ltoa(long value, char *string, int radix);
extern char* utoa(unsigned value, char *string, int radix);
extern char* ultoa(unsigned long value, char *string, int radix);
#ifdef __cplusplus
} // extern "C"
#endif
================================================
FILE: extras/test/src/Arduino.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/******************************************************************************
INCLUDE
******************************************************************************/
#include
/******************************************************************************
GLOBAL VARIABLES
******************************************************************************/
static unsigned long current_millis = 0;
/******************************************************************************
PUBLIC FUNCTIONS
******************************************************************************/
void set_millis(unsigned long const millis)
{
current_millis = millis;
}
unsigned long millis()
{
return current_millis;
}
================================================
FILE: extras/test/src/test_advertising_data/FakeBLELocalDevice.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "FakeBLELocalDevice.h"
FakeBLELocalDevice::FakeBLELocalDevice()
{
}
FakeBLELocalDevice::~FakeBLELocalDevice()
{
}
int FakeBLELocalDevice::advertise()
{
_advertisingData.updateData();
_scanResponseData.updateData();
return 1;
}
FakeBLELocalDevice FakeBLEObj;
BLELocalDevice& BLE = FakeBLEObj;
================================================
FILE: extras/test/src/test_advertising_data/test_advertising_data.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
TEST_CASE("Test flags override", "[ArduinoBLE::BLEAdvertisingData]")
{
// Mocking advertisement packet
BLEAdvertisingData advData;
// Expected results
const uint8_t defaultData[] = {0x02, BLEFieldFlags, 0x06};
const uint8_t goldenFlags[] = {0x02, 0x01, BLEFlagsBREDRNotSupported};
WHEN("Default options for flags")
{
BLE.advertise();
REQUIRE( 0 == (memcmp(defaultData, BLE.getAdvertisingData().data(), sizeof(defaultData))) );
REQUIRE( BLE.getScanResponseData().dataLength() == 0 );
}
WHEN("Setting external advertising data which has flags")
{
advData.setFlags(BLEFlagsBREDRNotSupported);
advData.updateData();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 3 == BLE.getAdvertisingData().dataLength());
REQUIRE( 0 == (memcmp(goldenFlags, advData.data(), sizeof(goldenFlags))) );
REQUIRE( 0 == (memcmp(goldenFlags, BLE.getAdvertisingData().data(), sizeof(goldenFlags))) );
REQUIRE( 0 != (memcmp(defaultData, BLE.getAdvertisingData().data(), sizeof(defaultData))) );
}
WHEN("Setting external advertising data without flags")
{
advData.clear();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 0 == (memcmp(defaultData, BLE.getAdvertisingData().data(), sizeof(defaultData))) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
TEST_CASE("Set default flags in an already full advertising data packet", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
bool retVal;
const char* name = "tes";
const uint8_t manufacturerData[24] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23};
const uint8_t defaultFlags[3] = {0x02, 0x01, 0x06};
const uint8_t goldenData[31] = {
(sizeof(manufacturerData) + 1), BLEFieldManufacturerData, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23,
((uint8_t)(strlen(name) + 1)), BLEFieldCompleteLocalName, 't', 'e', 's'
};
WHEN("Test flags when advertising data is full")
{
retVal = advData.setLocalName("tes");
retVal = advData.setManufacturerData(manufacturerData, sizeof(manufacturerData));
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE(0 != memcmp(defaultFlags, BLE.getAdvertisingData().data(), sizeof(defaultFlags)));
REQUIRE(0 == memcmp(goldenData, BLE.getAdvertisingData().data(), sizeof(goldenData)));
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
TEST_CASE("BLE overwrite a full internal advertising data with an external built one", "[ArduinoBLE::BLEAdvertisingData]")
{
bool verify;
BLEAdvertisingData advData;
BLEAdvertisingData internalData;
WHEN("Copy empty external advertising data")
{
BLE.setLocalName("test");
BLE.setAdvertisedServiceUuid("1818");
BLE.advertise();
THEN("Check that BLE advertising data has been set")
{
verify = (BLE.getAdvertisingData().dataLength() == (3 + (2+2)));
REQUIRE(verify);
}
THEN("Check that BLE scan response data has been set")
{
verify = (BLE.getScanResponseData().dataLength() == (4+2));
REQUIRE(verify);
}
// Copy external empty adv data into advertising data
BLE.setAdvertisingData(advData);
BLE.advertise();
THEN("BLE advertising data should be erased")
{
verify = (BLE.getAdvertisingData().dataLength() == 3);
REQUIRE(verify);
}
// Copy external empty adv data into scan response data
BLE.setScanResponseData(advData);
BLE.advertise();
THEN("BLE scan response data should be erased")
{
verify = (BLE.getScanResponseData().dataLength() == 0);
REQUIRE(verify);
}
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
TEST_CASE("BLE test raw data", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
bool retVal;
WHEN("Set too large raw data")
{
const uint8_t data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
retVal = advData.setRawData(data, sizeof(data));
THEN("Set raw data should return false. The parameter should not be set")
{
REQUIRE(!retVal);
}
advData.clear();
}
WHEN("Set correct raw data")
{
const uint8_t data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
retVal = advData.setRawData(data, sizeof(data));
THEN("Set raw data should return true. The parameter should be correctly set")
{
REQUIRE(retVal);
}
advData.updateData();
REQUIRE( 0 == memcmp(data, advData.data(), sizeof(data)) );
advData.clear();
}
WHEN("Hide other parameters by setting raw data")
{
const uint8_t data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
advData.setLocalName("test");
advData.setRawData(data, sizeof(data));
advData.updateData();
REQUIRE( 0 == memcmp(data, advData.data(), sizeof(data)) );
advData.setLocalName("test");
advData.updateData();
REQUIRE( 0 == memcmp(data, advData.data(), sizeof(data)) );
advData.clear();
advData.setLocalName("test");
advData.updateData();
REQUIRE( 0 != memcmp(data, advData.data(), sizeof(data)) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
================================================
FILE: extras/test/src/test_advertising_data/test_local_name.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
TEST_CASE("Test local name setting", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
int oldRemainingLength = advData.remainingLength();
bool retVal;
WHEN("Set correct local name")
{
const char* name = "test";
retVal = advData.setLocalName(name);
THEN("Set local name should return true. The name parameter should be correctly set")
{
REQUIRE(retVal);
}
THEN("Check the exact number of bytes occupied by the name just set")
{
REQUIRE( (strlen(name) + 2) == (oldRemainingLength - advData.remainingLength()) );
}
oldRemainingLength = advData.remainingLength();
advData.updateData();
REQUIRE(advData.dataLength() == (strlen(name) + 2));
}
WHEN("Set too long local name")
{
const char* name = "way too long local name (len 32)";
retVal = advData.setLocalName(name);
THEN("Set local name should return false. The name parameter should not be set")
{
REQUIRE(!retVal);
REQUIRE( oldRemainingLength == advData.remainingLength() );
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH - oldRemainingLength) );
}
}
WHEN("Overwrite local name with a name as long as max data length")
{
const char* name = "local name with full length ";
retVal = advData.setLocalName(name);
THEN("The name parameter should be correctly overwritten. The remaining length should be 0")
{
REQUIRE(retVal);
REQUIRE( (strlen(name) + 2) == (oldRemainingLength - advData.remainingLength()) );
oldRemainingLength = advData.remainingLength();
advData.updateData();
REQUIRE(advData.dataLength() == (strlen(name) + 2));
// advData should be full now
REQUIRE( 0 == advData.remainingLength() );
REQUIRE( 0 == advData.availableForWrite() );
}
}
WHEN("Check consistency when setting the external advertising data")
{
const auto goldenData = advData.data();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 0 == memcmp(goldenData, BLE.getAdvertisingData().data(), advData.dataLength()) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
================================================
FILE: extras/test/src/test_advertising_data/test_manufacturer.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
TEST_CASE("Test manufacturer data setting", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
int oldRemainingLength = advData.remainingLength();
const uint16_t companyId = 0x1100;
bool retVal;
WHEN("Set correct manufacturer data without id")
{
const uint8_t data[] = {0x00, 0x11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const uint8_t goldenData[] = {(sizeof(data) + 1), BLEFieldManufacturerData,
0x00, 0x11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
retVal = advData.setManufacturerData(data, sizeof(data));
THEN("Check that the manufacturer data has been correctly set")
{
REQUIRE(retVal);
REQUIRE( (sizeof(data) + 2) == (oldRemainingLength - advData.remainingLength()) );
}
oldRemainingLength = advData.remainingLength();
advData.updateData();
REQUIRE(advData.dataLength() == sizeof(goldenData));
REQUIRE( 0 == memcmp(goldenData, advData.data(), sizeof(goldenData)) );
}
WHEN("Set correct manufacturer data given a manufacturer id")
{
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const uint8_t goldenData[] = {(sizeof(data) + sizeof(companyId) + 1), BLEFieldManufacturerData,
0x00, 0x11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
retVal = advData.setManufacturerData(companyId, data, sizeof(data));
THEN("Check that the manufacturer data has been correctly set")
{
REQUIRE(retVal);
REQUIRE( (sizeof(data) + sizeof(companyId) + 2) == (oldRemainingLength - advData.remainingLength()) );
}
oldRemainingLength = advData.remainingLength();
advData.updateData();
REQUIRE(advData.dataLength() == sizeof(goldenData));
REQUIRE( 0 == memcmp(goldenData, advData.data(), sizeof(goldenData)) );
}
WHEN("Set too long manufacturer data given id")
{
// extreme case, 1 byte more than the maximum
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};
retVal = advData.setManufacturerData(companyId, data, sizeof(data));
THEN("Manufacturer data was too long, check that it has not been set")
{
REQUIRE(!retVal);
REQUIRE( oldRemainingLength == advData.remainingLength() );
}
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH - oldRemainingLength) );
}
WHEN("Set too long manufacturer data without id")
{
// extreme case, 1 byte more than the maximum
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
retVal = advData.setManufacturerData(data, sizeof(data));
THEN("Manufacturer data was too long, check that it has not been set")
{
REQUIRE(!retVal);
REQUIRE( oldRemainingLength == advData.remainingLength() );
}
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH - oldRemainingLength) );
}
WHEN("Set manufacturer data without id after setting manufacturer data given id")
{
advData.clear();
const uint8_t dataGivenId[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28};
THEN("Check that first insertion of manufacturer data given id is correctly done")
{
retVal = advData.setManufacturerData(companyId, dataGivenId, sizeof(dataGivenId));
REQUIRE(retVal);
}
THEN("Check that the insertion of manufacturer data without after one with id is correctly done")
{
retVal = advData.setManufacturerData(data, sizeof(data));
REQUIRE(retVal);
REQUIRE( 0 == advData.remainingLength() );
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH) );
}
}
WHEN("Set manufacturer data given id after setting manufacturer data without id")
{
advData.clear();
// dataGivenId is too long!! it should not pass
const uint8_t dataGivenId[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28};
THEN("Check that first insertion of manufacturer data WITHOUT id is correctly done")
{
retVal = advData.setManufacturerData(data, sizeof(data));
REQUIRE(retVal);
}
THEN("Check that the insertion of manufacturer data given id after one without id is correctly done")
{
retVal = advData.setManufacturerData(companyId, dataGivenId, sizeof(dataGivenId));
REQUIRE(!retVal);
}
}
WHEN("Overwrite manufacturer data with one as long as max data length")
{
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
const uint8_t goldenData[] = {(sizeof(data) + sizeof(companyId) + 1), BLEFieldManufacturerData,
0x00, 0x11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
retVal = advData.setManufacturerData(companyId, data, sizeof(data));
THEN("Manufacturer data should be set correctly")
{
REQUIRE(retVal);
advData.updateData();
REQUIRE( 0 == advData.remainingLength() );
REQUIRE( 0 == advData.availableForWrite() );
REQUIRE( 0 == memcmp(goldenData, advData.data(), sizeof(goldenData)) );
}
}
WHEN("Check consistency when setting the external advertising data")
{
const auto goldenData = advData.data();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 0 == memcmp(goldenData, BLE.getAdvertisingData().data(), advData.dataLength()) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
================================================
FILE: extras/test/src/test_advertising_data/test_service.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
TEST_CASE("Test advertised service id setting", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
int oldRemainingLength = advData.remainingLength();
bool retVal;
WHEN("Set correct advertised service")
{
const char* service = "00112233445566770011223344556677";
retVal = advData.setAdvertisedServiceUuid(service);
REQUIRE(retVal);
REQUIRE( (16 + 2) == (oldRemainingLength - advData.remainingLength()) );
oldRemainingLength = advData.remainingLength();
advData.updateData();
REQUIRE(advData.dataLength() == (16 + 2));
}
WHEN("Set an advertised id too long with respect to the remaining length")
{
advData.clear();
const char* name = "12 chars str";
const char* service = "00112233445566770011223344556677";
advData.setLocalName(name);
oldRemainingLength = advData.remainingLength();
THEN("Check that the too long parameter has not been set")
{
REQUIRE(!advData.setAdvertisedServiceUuid(service));
REQUIRE( oldRemainingLength == advData.remainingLength() );
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH - oldRemainingLength) );
}
}
WHEN("Fill to maximum an advertising packet with a service id")
{
advData.clear();
const char* name = "11 char str";
const char* service = "00112233445566770011223344556677";
advData.setLocalName(name);
REQUIRE(advData.setAdvertisedServiceUuid(service));
advData.updateData();
REQUIRE(advData.dataLength() == (MAX_AD_DATA_LENGTH));
// advData should be full now
REQUIRE( 0 == advData.remainingLength() );
REQUIRE( 0 == advData.availableForWrite() );
}
WHEN("Check consistency when setting the external advertising data")
{
const auto goldenData = advData.data();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 0 == memcmp(goldenData, BLE.getAdvertisingData().data(), advData.dataLength()) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
TEST_CASE("Test service data setting", "[ArduinoBLE::BLEAdvertisingData]")
{
BLEAdvertisingData advData;
int oldRemainingLength = advData.remainingLength();
const uint16_t uuid = 0x1100;
bool retVal;
WHEN("Set correct service data")
{
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const uint8_t goldenData[] = {(sizeof(data) + sizeof(uuid) + 1), BLEFieldServiceData,
0x00, 0x11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
retVal = advData.setAdvertisedServiceData(uuid, data, sizeof(data));
THEN("Correctly set parameter")
{
REQUIRE(retVal);
REQUIRE( (sizeof(data) + 2 + sizeof(uuid)) == (oldRemainingLength - advData.remainingLength()) );
}
oldRemainingLength = advData.remainingLength();
advData.updateData();
THEN("Check parameter analyzing advertising raw data")
{
REQUIRE(advData.dataLength() == (sizeof(data) + 2 + sizeof(uuid)));
REQUIRE(advData.dataLength() == sizeof(goldenData));
REQUIRE( 0 == memcmp(goldenData, advData.data(), sizeof(goldenData)) );
}
}
WHEN("Set too long service data")
{
// extreme case, 1 byte more than the maximum
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};
retVal = advData.setAdvertisedServiceData(uuid, data, sizeof(data));
THEN("Check that the too long parameter has not been set")
{
REQUIRE(!retVal);
}
REQUIRE( oldRemainingLength == advData.remainingLength() );
advData.updateData();
REQUIRE( advData.dataLength() == (MAX_AD_DATA_LENGTH - oldRemainingLength) );
}
WHEN("Overwrite service data with one as long as max data length")
{
const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
retVal = advData.setAdvertisedServiceData(uuid, data, sizeof(data));
THEN("Check correctly set parameter")
{
REQUIRE(retVal);
}
advData.updateData();
// advData should be full now
THEN("advData should be full now")
{
REQUIRE( 0 == advData.remainingLength() );
REQUIRE( 0 == advData.availableForWrite() );
}
}
WHEN("Check consistency when setting the external advertising data")
{
const auto goldenData = advData.data();
BLE.setAdvertisingData(advData);
BLE.advertise();
REQUIRE( 0 == memcmp(goldenData, BLE.getAdvertisingData().data(), advData.dataLength()) );
}
// Clear BLE advertising data
advData.clear();
BLE.setAdvertisingData(advData);
}
================================================
FILE: extras/test/src/test_characteristic/test_permissions.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
#include "BLETypedCharacteristics.h"
#include "BLELocalCharacteristic.h"
#include "BLEStringCharacteristic.h"
#include "BLEProperty.h"
#include
int property[] = {
BLEBroadcast,
BLERead,
BLEWriteWithoutResponse,
BLEWrite,
BLENotify,
BLEIndicate,
BLEAuthSignedWrite,
BLEExtProp,
BLERead | BLEWrite | BLENotify
};
int permission[] = {
BLEEncryption,
BLEAuthentication,
BLEAuthorization,
BLEEncryption | BLEAuthentication
};
const char uuid[][31] = {
"1 Bool",
"2 Char",
"3 UnsignedChar",
"4 Byte",
"5 Short",
"6 UnsignedShort",
"7 Word",
"8 Int",
"9 UnsignedInt",
"A Long",
"B UnsignedLong",
"C Float",
"D Double",
"E String"
};
std::unique_ptr createCharacteristic(const char* uuid, unsigned int properties)
{
switch(uuid[0])
{
case '1':
return std::unique_ptr(new BLEBoolCharacteristic(uuid, properties));
case '2':
return std::unique_ptr(new BLECharCharacteristic(uuid, properties));
case '3':
return std::unique_ptr(new BLEUnsignedCharCharacteristic(uuid, properties));
case '4':
return std::unique_ptr(new BLEByteCharacteristic(uuid, properties));
case '5':
return std::unique_ptr(new BLEShortCharacteristic(uuid, properties));
case '6':
return std::unique_ptr(new BLEUnsignedShortCharacteristic(uuid, properties));
case '7':
return std::unique_ptr(new BLEWordCharacteristic(uuid, properties));
case '8':
return std::unique_ptr(new BLEIntCharacteristic(uuid, properties));
case '9':
return std::unique_ptr(new BLEUnsignedIntCharacteristic(uuid, properties));
case 'A':
return std::unique_ptr(new BLELongCharacteristic(uuid, properties));
case 'B':
return std::unique_ptr(new BLEUnsignedLongCharacteristic(uuid, properties));
case 'C':
return std::unique_ptr(new BLEFloatCharacteristic(uuid, properties));
case 'D':
return std::unique_ptr(new BLEDoubleCharacteristic(uuid, properties));
case 'E':
return std::unique_ptr(new BLEStringCharacteristic(uuid, properties, 2));
default:
break;
}
return nullptr;
}
TEST_CASE("Test characteristic properties and permissions", "[ArduinoBLE::BLECharacteristic]")
{
WHEN("Create a characteristic")
{
for(int i = 0; i < sizeof(property)/sizeof(int); i++)
{
for(int j = 0; j < sizeof(permission)/sizeof(int); j++)
{
for(int k = 0; k < 14; k++)
{
std::unique_ptr ptr = createCharacteristic(uuid[k], property[i] | permission[j]);
REQUIRE(ptr != nullptr);
REQUIRE(ptr->properties() == (property[i]));
BLELocalCharacteristic * local = ptr->local();
REQUIRE(local->permissions() == (permission[j] >> 8));
}
}
}
}
}
================================================
FILE: extras/test/src/test_characteristic/test_writeValue.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "FakeBLELocalDevice.h"
#include "BLEAdvertisingData.h"
#include "BLETypedCharacteristics.h"
#include "BLELocalCharacteristic.h"
#include "BLEStringCharacteristic.h"
#include "BLEProperty.h"
TEST_CASE("Test characteristic writeValue", "[ArduinoBLE::BLECharacteristic]")
{
WHEN("Create a bool characteristic")
{
BLEBoolCharacteristic boolCharacteristic("Bool", BLEBroadcast| BLEIndicate | BLENotify );
bool v = false;;
int written = boolCharacteristic.writeValue(v);
REQUIRE( written == sizeof(bool) );
boolCharacteristic.broadcast();
written = boolCharacteristic.writeValue(v);
REQUIRE( written == sizeof(bool) );
BLEDevice device;
boolCharacteristic.local()->writeCccdValue(device, 0x002);
written = boolCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
boolCharacteristic.local()->writeCccdValue(device, 0x001);
written = boolCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a boolean characteristic")
{
BLEBooleanCharacteristic booleanCharacteristic("Boolean", BLEBroadcast| BLEIndicate | BLENotify);
bool v = false;
int written = booleanCharacteristic.writeValue(v);
REQUIRE( written == sizeof(bool) );
booleanCharacteristic.broadcast();
written = booleanCharacteristic.writeValue(v);
REQUIRE( written == sizeof(bool) );
BLEDevice device;
booleanCharacteristic.local()->writeCccdValue(device, 0x002);
written = booleanCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
booleanCharacteristic.local()->writeCccdValue(device, 0x001);
written = booleanCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a char characteristic")
{
BLECharCharacteristic charCharacteristic("Char", BLEBroadcast| BLEIndicate | BLENotify);
char v = 'a';
int written = charCharacteristic.writeValue(v);
REQUIRE( written == sizeof(char) );
charCharacteristic.broadcast();
written = charCharacteristic.writeValue(v);
REQUIRE( written == sizeof(char) );
BLEDevice device;
charCharacteristic.local()->writeCccdValue(device, 0x002);
written = charCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
charCharacteristic.local()->writeCccdValue(device, 0x001);
written = charCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a unsigned char characteristic")
{
BLEUnsignedCharCharacteristic unsignedCharCharacteristic("UnsignedChar", BLEBroadcast| BLEIndicate | BLENotify);
unsigned char v = 0x01;
int written = unsignedCharCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned char) );
unsignedCharCharacteristic.broadcast();
written = unsignedCharCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned char) );
BLEDevice device;
unsignedCharCharacteristic.local()->writeCccdValue(device, 0x002);
written = unsignedCharCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
unsignedCharCharacteristic.local()->writeCccdValue(device, 0x001);
written = unsignedCharCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a byte characteristic")
{
BLEByteCharacteristic byteCharacteristic("Byte", BLEBroadcast| BLEIndicate | BLENotify);
byte v = 0x01;
int written = byteCharacteristic.writeValue(v);
REQUIRE( written == sizeof(byte) );
byteCharacteristic.broadcast();
written = byteCharacteristic.writeValue(v);
REQUIRE( written == sizeof(byte) );
BLEDevice device;
byteCharacteristic.local()->writeCccdValue(device, 0x002);
written = byteCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
byteCharacteristic.local()->writeCccdValue(device, 0x001);
written = byteCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a short characteristic")
{
BLEShortCharacteristic shortCharacteristic("Short", BLEBroadcast| BLEIndicate | BLENotify);
short v = -1;
int written = shortCharacteristic.writeValue(v);
REQUIRE( written == sizeof(short) );
shortCharacteristic.broadcast();
written = shortCharacteristic.writeValue(v);
REQUIRE( written == sizeof(short) );
BLEDevice device;
shortCharacteristic.local()->writeCccdValue(device, 0x002);
written = shortCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
shortCharacteristic.local()->writeCccdValue(device, 0x001);
written = shortCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a unsigned short characteristic")
{
BLEUnsignedShortCharacteristic unsignedShortCharacteristic("UnsignedShort", BLEBroadcast| BLEIndicate | BLENotify);
unsigned short v = 1;
int written = unsignedShortCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned short) );
unsignedShortCharacteristic.broadcast();
written = unsignedShortCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned short) );
BLEDevice device;
unsignedShortCharacteristic.local()->writeCccdValue(device, 0x002);
written = unsignedShortCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
unsignedShortCharacteristic.local()->writeCccdValue(device, 0x001);
written = unsignedShortCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a word characteristic")
{
BLEWordCharacteristic wordCharacteristic("Word", BLEBroadcast| BLEIndicate | BLENotify);
word v = -1;
int written = wordCharacteristic.writeValue(v);
REQUIRE( written == sizeof(word) );
wordCharacteristic.broadcast();
written = wordCharacteristic.writeValue(v);
REQUIRE( written == sizeof(word) );
BLEDevice device;
wordCharacteristic.local()->writeCccdValue(device, 0x002);
written = wordCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
wordCharacteristic.local()->writeCccdValue(device, 0x001);
written = wordCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a int characteristic")
{
BLEIntCharacteristic intCharacteristic("Int", BLEBroadcast| BLEIndicate | BLENotify);
int v = -1;
int written = intCharacteristic.writeValue(v);
REQUIRE( written == sizeof(int) );
intCharacteristic.broadcast();
written = intCharacteristic.writeValue(v);
REQUIRE( written == sizeof(int) );
BLEDevice device;
intCharacteristic.local()->writeCccdValue(device, 0x002);
written = intCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
intCharacteristic.local()->writeCccdValue(device, 0x001);
written = intCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a unsigned int characteristic")
{
BLEUnsignedIntCharacteristic unsignedIntCharacteristic("UnsignedInt", BLEBroadcast| BLEIndicate | BLENotify);
unsigned int v = 1;
int written = unsignedIntCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned int) );
unsignedIntCharacteristic.broadcast();
written = unsignedIntCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned int) );
BLEDevice device;
unsignedIntCharacteristic.local()->writeCccdValue(device, 0x002);
written = unsignedIntCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
unsignedIntCharacteristic.local()->writeCccdValue(device, 0x001);
written = unsignedIntCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a long characteristic")
{
BLELongCharacteristic longCharacteristic("Long", BLEBroadcast| BLEIndicate | BLENotify);
long v = -1;
int written = longCharacteristic.writeValue(v);
REQUIRE( written == sizeof(long) );
longCharacteristic.broadcast();
written = longCharacteristic.writeValue(v);
REQUIRE( written == sizeof(long) );
BLEDevice device;
longCharacteristic.local()->writeCccdValue(device, 0x002);
written = longCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
longCharacteristic.local()->writeCccdValue(device, 0x001);
written = longCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a unsigned long characteristic")
{
BLEUnsignedLongCharacteristic unsignedLongCharacteristic("UnsignedLong", BLEBroadcast| BLEIndicate | BLENotify);
unsigned long v = 1;
int written = unsignedLongCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned long) );
unsignedLongCharacteristic.broadcast();
written = unsignedLongCharacteristic.writeValue(v);
REQUIRE( written == sizeof(unsigned long) );
BLEDevice device;
unsignedLongCharacteristic.local()->writeCccdValue(device, 0x002);
written = unsignedLongCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
unsignedLongCharacteristic.local()->writeCccdValue(device, 0x001);
written = unsignedLongCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a float characteristic")
{
BLEFloatCharacteristic floatCharacteristic("Float", BLEBroadcast| BLEIndicate | BLENotify);
float v = -1.0f;
int written = floatCharacteristic.writeValue(v);
REQUIRE( written == sizeof(float) );
floatCharacteristic.broadcast();
written = floatCharacteristic.writeValue(v);
REQUIRE( written == sizeof(float) );
BLEDevice device;
floatCharacteristic.local()->writeCccdValue(device, 0x002);
written = floatCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
floatCharacteristic.local()->writeCccdValue(device, 0x001);
written = floatCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a double characteristic")
{
BLEDoubleCharacteristic doubleCharacteristic("Double", BLEBroadcast| BLEIndicate | BLENotify);
double v = -1.0;
int written = doubleCharacteristic.writeValue(v);
REQUIRE( written == sizeof(double) );
doubleCharacteristic.broadcast();
written = doubleCharacteristic.writeValue(v);
REQUIRE( written == sizeof(double) );
BLEDevice device;
doubleCharacteristic.local()->writeCccdValue(device, 0x002);
written = doubleCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
doubleCharacteristic.local()->writeCccdValue(device, 0x001);
written = doubleCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a string characteristic")
{
const int maxStringLength = 64;
BLEStringCharacteristic stringCharacteristic("String", BLEBroadcast| BLEIndicate | BLENotify, maxStringLength);
const char* v = "Hello";
int written = stringCharacteristic.writeValue(v);
REQUIRE( written == min(strlen(v), maxStringLength) );
stringCharacteristic.broadcast();
written = stringCharacteristic.writeValue(v);
REQUIRE( written == min(strlen(v), maxStringLength) );
BLEDevice device;
stringCharacteristic.local()->writeCccdValue(device, 0x002);
written = stringCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
stringCharacteristic.local()->writeCccdValue(device, 0x001);
written = stringCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
WHEN("Create a too long string characteristic")
{
const int maxStringLength = 4;
BLEStringCharacteristic stringCharacteristic("String", BLEBroadcast| BLEIndicate | BLENotify, maxStringLength);
const char* v = "Hello";
int written = stringCharacteristic.writeValue(v);
REQUIRE( written == min(strlen(v), maxStringLength) );
stringCharacteristic.broadcast();
written = stringCharacteristic.writeValue(v);
REQUIRE( written == min(strlen(v), maxStringLength) );
BLEDevice device;
stringCharacteristic.local()->writeCccdValue(device, 0x002);
written = stringCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
stringCharacteristic.local()->writeCccdValue(device, 0x001);
written = stringCharacteristic.writeValue(v);
/* No peers connected */
REQUIRE( written == 0 );
}
}
================================================
FILE: extras/test/src/test_discovered_device/FakeGAP.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "FakeGAP.h"
FakeGAPClass::FakeGAPClass()
{
}
FakeGAPClass::~FakeGAPClass()
{
}
FakeGAPClass GAPFakeObj;
GAPClass& GAP = GAPFakeObj;
================================================
FILE: extras/test/src/test_discovered_device/test_discovered_device.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#define private public
#define protected public
#include "BLEDevice.h"
TEST_CASE("BLE discovered device test", "[ArduinoBLE::BLEDevice]")
{
WHEN("Retrieve local name from advertisement packet")
{
// Mocking advertisement packet
uint8_t advType = 0x03;
uint8_t eirLength = 6;
uint8_t eirData[] = {0x05, 0x09, 't', 'e', 's', 't'};
uint8_t rssi = 0;
// Expected results
String goldenName = "test";
// Simulate device discovery
BLEDevice device = BLEDevice();
device.setAdvertisementData(0x03, eirLength, eirData, rssi);
bool hasName = device.hasLocalName();
REQUIRE(hasName);
String name = device.localName();
REQUIRE(goldenName == name);
}
}
================================================
FILE: extras/test/src/test_main.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define CATCH_CONFIG_MAIN /* This tells Catch to provide a main() - only do this in one cpp file */
#include
================================================
FILE: extras/test/src/test_uuid/test_uuid.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "utility/BLEUuid.h"
TEST_CASE("BLE uuid test", "[ArduinoBLE::BLEUuid]")
{
WHEN("Set and retrieve uuid")
{
bool verify;
const char* goldenUuid = "19b10010-e8f2-537e-4f6c-d104768a1214";
// little-endian order
const uint8_t goldenData[] = {0x14,0x12,0x8A,0x76,0x04,0xD1,0x6C,0x4F,0x7E,0x53,0xF2,0xE8,0x10,0x00,0xB1,0x19};
uint8_t goldenLength = 16;
BLEUuid test(goldenUuid);
uint8_t testLength = test.length();
verify = (goldenLength == testLength);
REQUIRE(verify);
const uint8_t *testData = test.data();
verify = ( 0 == (memcmp(goldenData, testData, sizeof(goldenData))) );
REQUIRE(verify);
const char *testUuid = test.uuidToString(testData, testLength);
verify = ( 0 == strcmp(testUuid, goldenUuid) );
REQUIRE(verify);
// print the uuid
//WARN("test: " << testUuid << ", golden: " << goldenUuid);
}
}
================================================
FILE: extras/test/src/util/Common.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Common.h"
void delay(unsigned long)
{
}
/* C++ prototypes */
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
uint16_t makeWord(uint16_t w) { return w; }
uint16_t makeWord(uint8_t h, uint8_t l) { return (h << 8) | l; }
================================================
FILE: extras/test/src/util/HCIFakeTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "HCIFakeTransport.h"
HCIFakeTransportClass HCIFakeTransport;
HCITransportInterface& HCITransport = HCIFakeTransport;
================================================
FILE: extras/test/src/util/String.cpp
================================================
/*
String library for Wiring & Arduino
...mostly rewritten by Paul Stoffregen...
Copyright (c) 2009-10 Hernando Barragan. All rights reserved.
Copyright 2011, Paul Stoffregen, paul@pjrc.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "String.h"
#include "itoa.h"
/*********************************************/
/* Constructors */
/*********************************************/
namespace arduino {
String::String(const char *cstr)
{
init();
if (cstr) copy(cstr, strlen(cstr));
}
String::String(const String &value)
{
init();
*this = value;
}
String::String(const __FlashStringHelper *pstr)
{
init();
*this = pstr;
}
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String::String(String &&rval)
{
init();
move(rval);
}
String::String(StringSumHelper &&rval)
{
init();
move(rval);
}
#endif
String::String(char c)
{
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
*this = buf;
}
String::String(unsigned char value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned char)];
utoa(value, buf, base);
*this = buf;
}
String::String(int value, unsigned char base)
{
init();
char buf[2 + 8 * sizeof(int)];
itoa(value, buf, base);
*this = buf;
}
String::String(unsigned int value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned int)];
utoa(value, buf, base);
*this = buf;
}
String::String(long value, unsigned char base)
{
init();
char buf[2 + 8 * sizeof(long)];
ltoa(value, buf, base);
*this = buf;
}
String::String(unsigned long value, unsigned char base)
{
init();
char buf[1 + 8 * sizeof(unsigned long)];
ultoa(value, buf, base);
*this = buf;
}
/*
String::String(float value, unsigned char decimalPlaces)
{
init();
char buf[33];
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
String::String(double value, unsigned char decimalPlaces)
{
init();
char buf[33];
*this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}
*/
String::~String()
{
if (buffer) free(buffer);
}
/*********************************************/
/* Memory Management */
/*********************************************/
inline void String::init(void)
{
buffer = NULL;
capacity = 0;
len = 0;
}
void String::invalidate(void)
{
if (buffer) free(buffer);
buffer = NULL;
capacity = len = 0;
}
unsigned char String::reserve(unsigned int size)
{
if (buffer && capacity >= size) return 1;
if (changeBuffer(size)) {
if (len == 0) buffer[0] = 0;
return 1;
}
return 0;
}
unsigned char String::changeBuffer(unsigned int maxStrLen)
{
char *newbuffer = (char *)realloc(buffer, maxStrLen + 1);
if (newbuffer) {
buffer = newbuffer;
capacity = maxStrLen;
return 1;
}
return 0;
}
/*********************************************/
/* Copy and Move */
/*********************************************/
String & String::copy(const char *cstr, unsigned int length)
{
if (!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy(buffer, cstr);
return *this;
}
/*
String & String::copy(const __FlashStringHelper *pstr, unsigned int length)
{
if (!reserve(length)) {
invalidate();
return *this;
}
len = length;
strcpy_P(buffer, (PGM_P)pstr);
return *this;
}
*/
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
void String::move(String &rhs)
{
if (buffer) {
if (rhs && capacity >= rhs.len) {
strcpy(buffer, rhs.buffer);
len = rhs.len;
rhs.len = 0;
return;
} else {
free(buffer);
}
}
buffer = rhs.buffer;
capacity = rhs.capacity;
len = rhs.len;
rhs.buffer = NULL;
rhs.capacity = 0;
rhs.len = 0;
}
#endif
String & String::operator = (const String &rhs)
{
if (this == &rhs) return *this;
if (rhs.buffer) copy(rhs.buffer, rhs.len);
else invalidate();
return *this;
}
#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & String::operator = (String &&rval)
{
if (this != &rval) move(rval);
return *this;
}
String & String::operator = (StringSumHelper &&rval)
{
if (this != &rval) move(rval);
return *this;
}
#endif
String & String::operator = (const char *cstr)
{
if (cstr) copy(cstr, strlen(cstr));
else invalidate();
return *this;
}
/*
String & String::operator = (const __FlashStringHelper *pstr)
{
if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
else invalidate();
return *this;
}
*/
/*********************************************/
/* concat */
/*********************************************/
unsigned char String::concat(const String &s)
{
return concat(s.buffer, s.len);
}
unsigned char String::concat(const char *cstr, unsigned int length)
{
unsigned int newlen = len + length;
if (!cstr) return 0;
if (length == 0) return 1;
if (!reserve(newlen)) return 0;
strcpy(buffer + len, cstr);
len = newlen;
return 1;
}
unsigned char String::concat(const char *cstr)
{
if (!cstr) return 0;
return concat(cstr, strlen(cstr));
}
unsigned char String::concat(char c)
{
char buf[2];
buf[0] = c;
buf[1] = 0;
return concat(buf, 1);
}
unsigned char String::concat(unsigned char num)
{
char buf[1 + 3 * sizeof(unsigned char)];
itoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(int num)
{
char buf[2 + 3 * sizeof(int)];
itoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(unsigned int num)
{
char buf[1 + 3 * sizeof(unsigned int)];
utoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(long num)
{
char buf[2 + 3 * sizeof(long)];
ltoa(num, buf, 10);
return concat(buf, strlen(buf));
}
unsigned char String::concat(unsigned long num)
{
char buf[1 + 3 * sizeof(unsigned long)];
ultoa(num, buf, 10);
return concat(buf, strlen(buf));
}
/*
unsigned char String::concat(float num)
{
char buf[20];
char* string = dtostrf(num, 4, 2, buf);
return concat(string, strlen(string));
}
unsigned char String::concat(double num)
{
char buf[20];
char* string = dtostrf(num, 4, 2, buf);
return concat(string, strlen(string));
}
unsigned char String::concat(const __FlashStringHelper * str)
{
if (!str) return 0;
int length = strlen_P((const char *) str);
if (length == 0) return 1;
unsigned int newlen = len + length;
if (!reserve(newlen)) return 0;
strcpy_P(buffer + len, (const char *) str);
len = newlen;
return 1;
}
*/
/*********************************************/
/* Concatenate */
/*********************************************/
StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(rhs.buffer, rhs.len)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr)
{
StringSumHelper &a = const_cast(lhs);
if (!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, char c)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(c)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, int num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, long num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
/*
StringSumHelper & operator + (const StringSumHelper &lhs, float num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, double num)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(num)) a.invalidate();
return a;
}
StringSumHelper & operator + (const StringSumHelper &lhs, const __FlashStringHelper *rhs)
{
StringSumHelper &a = const_cast(lhs);
if (!a.concat(rhs)) a.invalidate();
return a;
}
*/
/*********************************************/
/* Comparison */
/*********************************************/
int String::compareTo(const String &s) const
{
if (!buffer || !s.buffer) {
if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
if (buffer && len > 0) return *(unsigned char *)buffer;
return 0;
}
return strcmp(buffer, s.buffer);
}
int String::compareTo(const char *cstr) const
{
if (!buffer || !cstr) {
if (cstr && !*cstr) return 0 - *(unsigned char *)cstr;
if (buffer && len > 0) return *(unsigned char *)buffer;
return 0;
}
return strcmp(buffer, cstr);
}
unsigned char String::equals(const String &s2) const
{
return (len == s2.len && compareTo(s2) == 0);
}
unsigned char String::equals(const char *cstr) const
{
if (len == 0) return (cstr == NULL || *cstr == 0);
if (cstr == NULL) return buffer[0] == 0;
return strcmp(buffer, cstr) == 0;
}
unsigned char String::equalsIgnoreCase( const String &s2 ) const
{
if (this == &s2) return 1;
if (len != s2.len) return 0;
if (len == 0) return 1;
const char *p1 = buffer;
const char *p2 = s2.buffer;
while (*p1) {
if (tolower(*p1++) != tolower(*p2++)) return 0;
}
return 1;
}
unsigned char String::startsWith( const String &s2 ) const
{
if (len < s2.len) return 0;
return startsWith(s2, 0);
}
unsigned char String::startsWith( const String &s2, unsigned int offset ) const
{
if (offset > len - s2.len || !buffer || !s2.buffer) return 0;
return strncmp( &buffer[offset], s2.buffer, s2.len ) == 0;
}
unsigned char String::endsWith( const String &s2 ) const
{
if ( len < s2.len || !buffer || !s2.buffer) return 0;
return strcmp(&buffer[len - s2.len], s2.buffer) == 0;
}
/*********************************************/
/* Character Access */
/*********************************************/
char String::charAt(unsigned int loc) const
{
return operator[](loc);
}
void String::setCharAt(unsigned int loc, char c)
{
if (loc < len) buffer[loc] = c;
}
char & String::operator[](unsigned int index)
{
static char dummy_writable_char;
if (index >= len || !buffer) {
dummy_writable_char = 0;
return dummy_writable_char;
}
return buffer[index];
}
char String::operator[]( unsigned int index ) const
{
if (index >= len || !buffer) return 0;
return buffer[index];
}
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
{
if (!bufsize || !buf) return;
if (index >= len) {
buf[0] = 0;
return;
}
unsigned int n = bufsize - 1;
if (n > len - index) n = len - index;
strncpy((char *)buf, buffer + index, n);
buf[n] = 0;
}
/*********************************************/
/* Search */
/*********************************************/
int String::indexOf(char c) const
{
return indexOf(c, 0);
}
int String::indexOf( char ch, unsigned int fromIndex ) const
{
if (fromIndex >= len) return -1;
const char* temp = strchr(buffer + fromIndex, ch);
if (temp == NULL) return -1;
return temp - buffer;
}
int String::indexOf(const String &s2) const
{
return indexOf(s2, 0);
}
int String::indexOf(const String &s2, unsigned int fromIndex) const
{
if (fromIndex >= len) return -1;
const char *found = strstr(buffer + fromIndex, s2.buffer);
if (found == NULL) return -1;
return found - buffer;
}
int String::lastIndexOf( char theChar ) const
{
return lastIndexOf(theChar, len - 1);
}
int String::lastIndexOf(char ch, unsigned int fromIndex) const
{
if (fromIndex >= len) return -1;
char tempchar = buffer[fromIndex + 1];
buffer[fromIndex + 1] = '\0';
char* temp = strrchr( buffer, ch );
buffer[fromIndex + 1] = tempchar;
if (temp == NULL) return -1;
return temp - buffer;
}
int String::lastIndexOf(const String &s2) const
{
return lastIndexOf(s2, len - s2.len);
}
int String::lastIndexOf(const String &s2, unsigned int fromIndex) const
{
if (s2.len == 0 || len == 0 || s2.len > len) return -1;
if (fromIndex >= len) fromIndex = len - 1;
int found = -1;
for (char *p = buffer; p <= buffer + fromIndex; p++) {
p = strstr(p, s2.buffer);
if (!p) break;
if ((unsigned int)(p - buffer) <= fromIndex) found = p - buffer;
}
return found;
}
String String::substring(unsigned int left, unsigned int right) const
{
if (left > right) {
unsigned int temp = right;
right = left;
left = temp;
}
String out;
if (left >= len) return out;
if (right > len) right = len;
char temp = buffer[right]; // save the replaced character
buffer[right] = '\0';
out = buffer + left; // pointer arithmetic
buffer[right] = temp; //restore character
return out;
}
/*********************************************/
/* Modification */
/*********************************************/
void String::replace(char find, char replace)
{
if (!buffer) return;
for (char *p = buffer; *p; p++) {
if (*p == find) *p = replace;
}
}
void String::replace(const String& find, const String& replace)
{
if (len == 0 || find.len == 0) return;
int diff = replace.len - find.len;
char *readFrom = buffer;
char *foundAt;
if (diff == 0) {
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
memcpy(foundAt, replace.buffer, replace.len);
readFrom = foundAt + replace.len;
}
} else if (diff < 0) {
char *writeTo = buffer;
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
unsigned int n = foundAt - readFrom;
memcpy(writeTo, readFrom, n);
writeTo += n;
memcpy(writeTo, replace.buffer, replace.len);
writeTo += replace.len;
readFrom = foundAt + find.len;
len += diff;
}
strcpy(writeTo, readFrom);
} else {
unsigned int size = len; // compute size needed for result
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
readFrom = foundAt + find.len;
size += diff;
}
if (size == len) return;
if (size > capacity && !changeBuffer(size)) return; // XXX: tell user!
int index = len - 1;
while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
readFrom = buffer + index + find.len;
memmove(readFrom + diff, readFrom, len - (readFrom - buffer));
len += diff;
buffer[len] = 0;
memcpy(buffer + index, replace.buffer, replace.len);
index--;
}
}
}
void String::remove(unsigned int index){
// Pass the biggest integer as the count. The remove method
// below will take care of truncating it at the end of the
// string.
remove(index, (unsigned int)-1);
}
void String::remove(unsigned int index, unsigned int count){
if (index >= len) { return; }
if (count <= 0) { return; }
if (count > len - index) { count = len - index; }
char *writeTo = buffer + index;
len = len - count;
memmove(writeTo, buffer + index + count,len - index);
buffer[len] = 0;
}
void String::toLowerCase(void)
{
if (!buffer) return;
for (char *p = buffer; *p; p++) {
*p = tolower(*p);
}
}
void String::toUpperCase(void)
{
if (!buffer) return;
for (char *p = buffer; *p; p++) {
*p = toupper(*p);
}
}
void String::trim(void)
{
if (!buffer || len == 0) return;
char *begin = buffer;
while (isspace(*begin)) begin++;
char *end = buffer + len - 1;
while (isspace(*end) && end >= begin) end--;
len = end + 1 - begin;
if (begin > buffer) memmove(buffer, begin, len);
buffer[len] = 0;
}
/*********************************************/
/* Parsing / Conversion */
/*********************************************/
long String::toInt(void) const
{
if (buffer) return atol(buffer);
return 0;
}
float String::toFloat(void) const
{
return float(toDouble());
}
double String::toDouble(void) const
{
if (buffer) return atof(buffer);
return 0;
}
} // namespace arduino
================================================
FILE: extras/test/src/util/TestUtil.cpp
================================================
/*
* Copyright (c) 2020 Arduino. All rights reserved.
*/
================================================
FILE: extras/test/src/util/itoa.c
================================================
/*
Copyright (c) 2014 Arduino LLC. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include
#ifdef __cplusplus
extern "C" {
#endif
extern char* itoa( int value, char *string, int radix )
{
return ltoa( value, string, radix ) ;
}
extern char* ltoa( long value, char *string, int radix )
{
char tmp[33];
char *tp = tmp;
long i;
unsigned long v;
int sign;
char *sp;
if ( string == NULL )
{
return 0 ;
}
if (radix > 36 || radix <= 1)
{
return 0 ;
}
sign = (radix == 10 && value < 0);
if (sign)
{
v = -value;
}
else
{
v = (unsigned long)value;
}
while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}
sp = string;
if (sign)
*sp++ = '-';
while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}
extern char* utoa( unsigned int value, char *string, int radix )
{
return ultoa( value, string, radix ) ;
}
extern char* ultoa( unsigned long value, char *string, int radix )
{
char tmp[33];
char *tp = tmp;
long i;
unsigned long v = value;
char *sp;
if ( string == NULL )
{
return 0;
}
if (radix > 36 || radix <= 1)
{
return 0;
}
while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}
sp = string;
while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}
#ifdef __cplusplus
} // extern "C"
#endif
================================================
FILE: keywords.txt
================================================
#######################################
# Syntax Coloring Map For ArduinoBLE
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
ArduinoBLE KEYWORD1
BLE KEYWORD1
BLEDevice KEYWORD1
BLECharacteristic KEYWORD1
BLEDescriptor KEYWORD1
BLEService KEYWORD1
BLEBoolCharacteristic KEYWORD1
BLEBooleanCharacteristic KEYWORD1
BLECharCharacteristic KEYWORD1
BLEUnsignedCharCharacteristic KEYWORD1
BLEByteCharacteristic KEYWORD1
BLEShortCharacteristic KEYWORD1
BLEUnsignedShortCharacteristic KEYWORD1
BLEWordCharacteristic KEYWORD1
BLEIntCharacteristic KEYWORD1
BLEUnsignedIntCharacteristic KEYWORD1
BLELongCharacteristic KEYWORD1
BLEUnsignedLongCharacteristic KEYWORD1
BLEFloatCharacteristic KEYWORD1
BLEDoubleCharacteristic KEYWORD1
BLEStringCharacteristic KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
poll KEYWORD2
end KEYWORD2
connected KEYWORD2
disconnect KEYWORD2
address KEYWORD2
hasLocalName KEYWORD2
hasAdvertisedServiceUuid KEYWORD2
advertisedServiceUuidCount KEYWORD2
localName KEYWORD2
advertisedServiceUuid KEYWORD2
rssi KEYWORD2
connect KEYWORD2
discoverAttributes KEYWORD2
discoverService KEYWORD2
deviceName KEYWORD2
appearance KEYWORD2
serviceCount KEYWORD2
hasService KEYWORD2
service KEYWORD2
characteristicCount KEYWORD2
characteristic KEYWORD2
setAdvertisedServiceUuid KEYWORD2
setManufacturerData KEYWORD2
setLocalName KEYWORD2
setDeviceName KEYWORD2
setAppearance KEYWORD2
addService KEYWORD2
advertise KEYWORD2
stopAdvertise KEYWORD2
scan KEYWORD2
scanForName KEYWORD2
scanForUuid KEYWORD2
scanForAddress KEYWORD2
stopScan KEYWORD2
central KEYWORD2
available KEYWORD2
setEventHandler KEYWORD2
setAdvertisingInterval KEYWORD2
setConnectionInterval KEYWORD2
setConnectable KEYWORD2
setPairable KEYWORD2
setTimeout KEYWORD2
debug KEYWORD2
noDebug KEYWORD2
pairable KEYWORD2
paired KEYWORD2
properties KEYWORD2
valueSize KEYWORD2
value KEYWORD2
valueLength KEYWORD2
readValue KEYWORD2
writeValue KEYWORD2
setValue KEYWORD2
broadcast KEYWORD2
written KEYWORD2
subscribed KEYWORD2
valueUpdated KEYWORD2
addDescriptor KEYWORD2
descriptorCount KEYWORD2
hasDescriptor KEYWORD2
descriptor KEYWORD2
canRead KEYWORD2
read KEYWORD2
canWrite KEYWORD2
canSubscribe KEYWORD2
subscribe KEYWORD2
canUnsubscribe KEYWORD2
unsubscribe KEYWORD2
writeValueLE KEYWORD2
setValueLE KEYWORD2
valueLE KEYWORD2
writeValueBE KEYWORD2
setValueBE KEYWORD2
valueBE KEYWORD2
uuid KEYWORD2
addCharacteristic KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
BLEConnected LITERAL1
BLEDisconnected LITERAL1
BLEDiscovered LITERAL1
BLEBroadcast LITERAL1
BLERead LITERAL1
BLEWriteWithoutResponse LITERAL1
BLEWrite LITERAL1
BLENotify LITERAL1
BLEIndicate LITERAL1
BLESubscribed LITERAL1
BLEUnsubscribed LITERAL1
BLEWritten LITERAL1
BLEUpdated LITERAL1
================================================
FILE: library.properties
================================================
name=ArduinoBLE
version=2.0.1
author=Arduino
maintainer=Arduino
sentence=Enables Bluetooth® Low Energy connectivity on the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev2, Arduino Nano 33 IoT, Arduino Nano 33 BLE, Nicla Sense ME and UNO R4 WiFi.
paragraph=This library supports creating a Bluetooth® Low Energy peripheral & central mode.
category=Communication
url=https://www.arduino.cc/en/Reference/ArduinoBLE
architectures=*
includes=ArduinoBLE.h
depends=Arduino_SpiNINA
================================================
FILE: src/ArduinoBLE.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _ARDUINO_BLE_H_
#define _ARDUINO_BLE_H_
#include "local/BLELocalDevice.h"
#include "BLEProperty.h"
#include "BLEStringCharacteristic.h"
#include "BLETypedCharacteristics.h"
#include "utility/btct.h"
#endif
================================================
FILE: src/BLEAdvertisingData.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLEAdvertisingData.h"
#define AD_FIELD_OVERHEAD (2)
BLEAdvertisingData::BLEAdvertisingData() :
_dataLength(0),
_remainingLength(MAX_AD_DATA_LENGTH),
_rawData(NULL),
_rawDataLength(0),
_flags(0),
_hasFlags(false),
_localName(NULL),
_manufacturerData(NULL),
_manufacturerDataLength(0),
_manufacturerCompanyId(0),
_hasManufacturerCompanyId(false),
_advertisedServiceUuid(NULL),
_advertisedServiceUuidLength(0),
_serviceData(NULL),
_serviceDataLength(0)
{
}
BLEAdvertisingData::~BLEAdvertisingData()
{
}
inline bool BLEAdvertisingData::updateRemainingLength(int oldFieldLength, int newFieldLength)
{
int updatedRemaining = _remainingLength + (oldFieldLength - newFieldLength);
if (updatedRemaining >= 0) {
_remainingLength = updatedRemaining;
return true;
}
return false;
}
int BLEAdvertisingData::remainingLength() const
{
return _remainingLength;
}
int BLEAdvertisingData::availableForWrite()
{
int available = (_remainingLength - AD_FIELD_OVERHEAD);
if (available < 0) available = 0;
return available;
}
void BLEAdvertisingData::clear()
{
_remainingLength = MAX_AD_DATA_LENGTH;
_rawData = NULL;
_rawDataLength = 0;
_hasFlags = false;
_localName = NULL;
_manufacturerData = NULL;
_manufacturerDataLength = 0;
_hasManufacturerCompanyId = false;
_advertisedServiceUuid = NULL;
_advertisedServiceUuidLength = 0;
_serviceData = NULL;
_serviceDataLength = 0;
}
void BLEAdvertisingData::copy(const BLEAdvertisingData& adv)
{
_remainingLength = adv._remainingLength;
_rawData = adv._rawData;
_rawDataLength = adv._rawDataLength;
_flags = adv._flags;
_hasFlags = adv._hasFlags;
_localName = adv._localName;
_manufacturerData = adv._manufacturerData;
_manufacturerDataLength = adv._manufacturerDataLength;
_manufacturerCompanyId = adv._manufacturerCompanyId;
_hasManufacturerCompanyId = adv._hasManufacturerCompanyId;
_advertisedServiceUuid = adv._advertisedServiceUuid;
_advertisedServiceUuidLength = adv._advertisedServiceUuidLength;
_serviceDataUuid = adv._serviceDataUuid;
_serviceData = adv._serviceData;
_serviceDataLength = adv._serviceDataLength;
}
BLEAdvertisingData& BLEAdvertisingData::operator=(const BLEAdvertisingData &other)
{
copy(other);
return *this;
}
bool BLEAdvertisingData::setAdvertisedServiceUuid(const char* advertisedServiceUuid)
{
BLEUuid uuid(advertisedServiceUuid);
int previousLength = (_advertisedServiceUuidLength > 0) ? (_advertisedServiceUuidLength + AD_FIELD_OVERHEAD) : 0;
bool success = updateRemainingLength(previousLength, (uuid.length() + AD_FIELD_OVERHEAD));
if (success) {
_advertisedServiceUuid = advertisedServiceUuid;
_advertisedServiceUuidLength = uuid.length();
}
return success;
}
bool BLEAdvertisingData::setAdvertisedService(const BLEService& service)
{
return setAdvertisedServiceUuid(service.uuid());
}
bool BLEAdvertisingData::setManufacturerData(const uint8_t manufacturerData[], int manufacturerDataLength)
{
int previousLength = 0;
if (_manufacturerDataLength) {
previousLength = _manufacturerDataLength + AD_FIELD_OVERHEAD;
if (_hasManufacturerCompanyId) {
previousLength += sizeof(_manufacturerCompanyId);
}
}
bool success = updateRemainingLength(previousLength, (manufacturerDataLength + AD_FIELD_OVERHEAD));
if (success) {
_manufacturerData = manufacturerData;
_manufacturerDataLength = manufacturerDataLength;
_hasManufacturerCompanyId = false;
}
return success;
}
bool BLEAdvertisingData::setManufacturerData(const uint16_t companyId, const uint8_t manufacturerData[], int manufacturerDataLength)
{
int previousLength = 0;
if (_manufacturerDataLength) {
previousLength = _manufacturerDataLength + AD_FIELD_OVERHEAD;
if (_hasManufacturerCompanyId) {
previousLength += sizeof(_manufacturerCompanyId);
}
}
bool success = updateRemainingLength(previousLength, (manufacturerDataLength + sizeof(companyId) + AD_FIELD_OVERHEAD));
if (success) {
_manufacturerData = manufacturerData;
_manufacturerDataLength = manufacturerDataLength;
_manufacturerCompanyId = companyId;
_hasManufacturerCompanyId = true;
}
return success;
}
bool BLEAdvertisingData::setAdvertisedServiceData(uint16_t uuid, const uint8_t data[], int length)
{
int previousLength = (_serviceDataLength > 0) ? (_serviceDataLength + sizeof(uuid) + AD_FIELD_OVERHEAD) : 0;
bool success = updateRemainingLength(previousLength, (length + sizeof(uuid) + AD_FIELD_OVERHEAD));
if (success) {
_serviceDataUuid = uuid;
_serviceData = data;
_serviceDataLength = length;
}
return success;
}
bool BLEAdvertisingData::setLocalName(const char *localName)
{
int previousLength = (_localName && strlen(_localName) > 0) ? (strlen(_localName) + AD_FIELD_OVERHEAD) : 0;
bool success = updateRemainingLength(previousLength, (strlen(localName) + AD_FIELD_OVERHEAD));
if (success) {
_localName = localName;
}
return success;
}
bool BLEAdvertisingData::setRawData(const uint8_t* data, int length)
{
if (length > MAX_AD_DATA_LENGTH) {
return false;
}
_rawData = data;
_rawDataLength = length;
return true;
}
bool BLEAdvertisingData::setRawData(const BLEAdvertisingRawData& rawData)
{
if (rawData.length > MAX_AD_DATA_LENGTH) {
return false;
}
_rawData = rawData.data;
_rawDataLength = rawData.length;
return true;
}
bool BLEAdvertisingData::setFlags(uint8_t flags)
{
int previousLength = (_hasFlags) ? (sizeof(_flags) + AD_FIELD_OVERHEAD) : 0;
bool success = updateRemainingLength(previousLength, (sizeof(flags) + AD_FIELD_OVERHEAD));
if (success) {
_hasFlags = true;
_flags = flags;
}
return success;
}
bool BLEAdvertisingData::updateData()
{
// Success indicates whether all the fields have been inserted
bool success = true;
// Reset data
_dataLength = 0;
// If rawData is present, then only rawData is inserted in the advertising packet
if (_rawData && _rawDataLength) {
return addRawData(_rawData, _rawDataLength);
}
// Try to add flags into the current advertising packet
if (_hasFlags) {
success &= addFlags(_flags);
}
// Try to add Advertised service uuid into the current advertising packet
if (_advertisedServiceUuid) {
success &= addAdvertisedServiceUuid(_advertisedServiceUuid);
}
// Try to add Manufacturer data into the current advertising packet
if (_manufacturerData && _manufacturerDataLength) {
if (_hasManufacturerCompanyId) {
success &= addManufacturerData(_manufacturerCompanyId, _manufacturerData, _manufacturerDataLength);
} else {
success &= addManufacturerData(_manufacturerData, _manufacturerDataLength);
}
}
// Try to add Service data into the current advertising packet
if (_serviceData && _serviceDataLength) {
success &= addAdvertisedServiceData(_serviceDataUuid, _serviceData, _serviceDataLength);
}
// Try to add Local name into the current advertising packet
if (_localName) {
success &= addLocalName(_localName);
}
return success;
}
uint8_t* BLEAdvertisingData::data()
{
return _data;
}
int BLEAdvertisingData::dataLength() const
{
return _dataLength;
}
bool BLEAdvertisingData::hasFlags() const
{
return _hasFlags;
}
bool BLEAdvertisingData::addLocalName(const char *localName)
{
bool success = false;
if (strlen(localName) > (MAX_AD_DATA_LENGTH - AD_FIELD_OVERHEAD)) {
success = addField(BLEFieldShortLocalName, (uint8_t*)localName, (MAX_AD_DATA_LENGTH - AD_FIELD_OVERHEAD));
} else {
success = addField(BLEFieldCompleteLocalName, localName);
}
return success;
}
bool BLEAdvertisingData::addAdvertisedServiceUuid(const char* advertisedServiceUuid)
{
BLEUuid uuid(advertisedServiceUuid);
int uuidLen = uuid.length();
BLEAdField advField;
if (uuidLen > 2) {
advField = BLEFieldIncompleteAdvertisedService128;
} else {
advField = BLEFieldIncompleteAdvertisedService16;
}
return addField(advField, uuid.data(), uuidLen);
}
bool BLEAdvertisingData::addManufacturerData(const uint8_t manufacturerData[], int manufacturerDataLength)
{
return addField(BLEFieldManufacturerData, manufacturerData, manufacturerDataLength);
}
bool BLEAdvertisingData::addManufacturerData(const uint16_t companyId, const uint8_t manufacturerData[], int manufacturerDataLength)
{
int tempDataLength = manufacturerDataLength + sizeof(companyId);
uint8_t tempData[MAX_AD_DATA_LENGTH];
memcpy(tempData, &companyId, sizeof(companyId));
memcpy(&tempData[sizeof(companyId)], manufacturerData, manufacturerDataLength);
return addField(BLEFieldManufacturerData, tempData, tempDataLength);
}
bool BLEAdvertisingData::addAdvertisedServiceData(uint16_t uuid, const uint8_t data[], int length)
{
int tempDataLength = length + sizeof(uuid);
uint8_t tempData[MAX_AD_DATA_LENGTH];
memcpy(tempData, &uuid, sizeof(uuid));
memcpy(&tempData[sizeof(uuid)], data, length);
return addField(BLEFieldServiceData, tempData, tempDataLength);
}
bool BLEAdvertisingData::addRawData(const uint8_t* data, int length)
{
// Bypass addField to add the integral raw data
if (length > (MAX_AD_DATA_LENGTH - _dataLength)) {
// Not enough space
return false;
}
memcpy(&_data[_dataLength], data, length);
_dataLength += length;
return true;
}
bool BLEAdvertisingData::addFlags(uint8_t flags)
{
return addField(BLEFieldFlags, &flags, sizeof(flags));
}
bool BLEAdvertisingData::addField(BLEAdField field, const char* data)
{
int dataLength = strlen(data);
return addField(field, (uint8_t *)data, dataLength);
}
bool BLEAdvertisingData::addField(BLEAdField field, const uint8_t* data, int length)
{
int fieldLength = length + AD_FIELD_OVERHEAD; // Considering data TYPE and LENGTH fields
if (fieldLength > (MAX_AD_DATA_LENGTH - _dataLength)) {
// Not enough space for storing this field
return false;
}
// Insert field into advertising data of the instance
_data[_dataLength++] = length + 1;
_data[_dataLength++] = field;
memcpy(&_data[_dataLength], data, length);
_dataLength += length;
return true;
}
================================================
FILE: src/BLEAdvertisingData.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_ADVERTISING_DATA_H_
#define _BLE_ADVERTISING_DATA_H_
#include
#include "utility/BLEUuid.h"
#include "BLEService.h"
#define MAX_AD_DATA_LENGTH (31)
enum BLEFlags {
BLEFlagsLimitedDiscoverable = 0x01,
BLEFlagsGeneralDiscoverable = 0x02,
BLEFlagsBREDRNotSupported = 0x04
};
enum BLEAdField {
BLEFieldFlags = 0x01,
BLEFieldIncompleteAdvertisedService16 = 0x02,
BLEFieldCompleteAdvertisedService16 = 0x03,
BLEFieldIncompleteAdvertisedService128 = 0x06,
BLEFieldCompleteAdvertisedService128 = 0x07,
BLEFieldShortLocalName = 0x08,
BLEFieldCompleteLocalName = 0x09,
BLEFieldServiceData = 0x16,
BLEFieldManufacturerData = 0xFF,
BLEAdFieldLast
};
struct BLEAdvertisingRawData {
uint8_t data[MAX_AD_DATA_LENGTH];
int length;
};
class BLEAdvertisingData {
public:
BLEAdvertisingData();
virtual ~BLEAdvertisingData();
int availableForWrite();
void clear();
void copy(const BLEAdvertisingData& adv);
BLEAdvertisingData& operator=(const BLEAdvertisingData &other);
bool setAdvertisedService(const BLEService& service);
bool setAdvertisedServiceUuid(const char* advertisedServiceUuid);
bool setManufacturerData(const uint8_t manufacturerData[], int manufacturerDataLength);
bool setManufacturerData(const uint16_t companyId, const uint8_t manufacturerData[], int manufacturerDataLength);
bool setLocalName(const char *localName);
bool setAdvertisedServiceData(uint16_t uuid, const uint8_t data[], int length);
bool setRawData(const uint8_t* data, int length);
bool setRawData(const BLEAdvertisingRawData& data);
bool setFlags(uint8_t flags);
protected:
friend class BLELocalDevice;
bool updateData();
uint8_t* data();
int dataLength() const;
int remainingLength() const;
bool hasFlags() const;
private:
bool updateRemainingLength(int oldFieldLength, int newFieldLength);
bool addAdvertisedServiceUuid(const char* advertisedServiceUuid);
bool addManufacturerData(const uint8_t manufacturerData[], int manufacturerDataLength);
bool addManufacturerData(const uint16_t companyId, const uint8_t manufacturerData[], int manufacturerDataLength);
bool addLocalName(const char *localName);
bool addAdvertisedServiceData(uint16_t uuid, const uint8_t data[], int length);
bool addRawData(const uint8_t* data, int length);
bool addFlags(uint8_t flags);
bool addField(BLEAdField field, const char* data);
bool addField(BLEAdField field, const uint8_t* data, int length);
uint8_t _data[MAX_AD_DATA_LENGTH];
int _dataLength;
int _remainingLength;
const uint8_t* _rawData;
int _rawDataLength;
uint8_t _flags;
bool _hasFlags;
const char* _localName;
const uint8_t* _manufacturerData;
int _manufacturerDataLength;
uint16_t _manufacturerCompanyId;
bool _hasManufacturerCompanyId;
const char* _advertisedServiceUuid;
int _advertisedServiceUuidLength;
uint16_t _serviceDataUuid;
const uint8_t* _serviceData;
int _serviceDataLength;
};
#endif
================================================
FILE: src/BLECharacteristic.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLEProperty.h"
#include "local/BLELocalCharacteristic.h"
#include "remote/BLERemoteCharacteristic.h"
#include "BLECharacteristic.h"
extern "C" int strcasecmp(char const *a, char const *b);
BLECharacteristic::BLECharacteristic() :
BLECharacteristic((BLELocalCharacteristic*)NULL)
{
}
BLECharacteristic::BLECharacteristic(BLELocalCharacteristic* local) :
_local(local),
_remote(NULL)
{
if (_local) {
_local->retain();
}
}
BLECharacteristic::BLECharacteristic(BLERemoteCharacteristic* remote) :
_local(NULL),
_remote(remote)
{
if (_remote) {
_remote->retain();
}
}
BLECharacteristic::BLECharacteristic(const char* uuid, uint16_t permissions, int valueSize, bool fixedLength) :
BLECharacteristic(new BLELocalCharacteristic(uuid, permissions, valueSize, fixedLength))
{
}
BLECharacteristic::BLECharacteristic(const char* uuid, uint16_t permissions, const char* value) :
BLECharacteristic(new BLELocalCharacteristic(uuid, permissions, value))
{
}
BLECharacteristic::BLECharacteristic(const BLECharacteristic& other)
{
_local = other._local;
if (_local) {
_local->retain();
}
_remote = other._remote;
if (_remote) {
_remote->retain();
}
}
BLECharacteristic::~BLECharacteristic()
{
if (_local && _local->release() == 0) {
delete _local;
}
if (_remote && _remote->release() == 0) {
delete _remote;
}
}
const char* BLECharacteristic::uuid() const
{
if (_local) {
return _local->uuid();
}
if (_remote) {
return _remote->uuid();
}
return "";
}
uint8_t BLECharacteristic::properties() const
{
if (_local) {
return _local->properties();
}
if (_remote) {
return _remote->properties();
}
return 0;
}
int BLECharacteristic::valueSize() const
{
if (_local) {
return _local->valueSize();
}
if (_remote) {
return _remote->valueLength();
}
return 0;
}
const uint8_t* BLECharacteristic::value() const
{
if (_local) {
return _local->value();
}
if (_remote) {
return _remote->value();
}
return NULL;
}
int BLECharacteristic::valueLength() const
{
if (_local) {
return _local->valueLength();
}
if (_remote) {
return _remote->valueLength();
}
return 0;
}
uint8_t BLECharacteristic::operator[] (int offset) const
{
if (_local) {
return (*_local)[offset];
}
if (_remote) {
return (*_remote)[offset];
}
return 0;
}
int BLECharacteristic::readValue(uint8_t value[], int length)
{
int bytesRead = 0;
if (_local) {
bytesRead = min(length, _local->valueLength());
memcpy(value, _local->value(), bytesRead);
}
if (_remote) {
// trigger a read if the updated value (notification/indication)
// has already been read and the characteristic is readable
if (_remote->updatedValueRead() && canRead()) {
if (!read()) {
// read failed
return 0;
}
}
bytesRead = min(length, _remote->valueLength());
memcpy(value, _remote->value(), bytesRead);
}
return bytesRead;
}
int BLECharacteristic::readValue(void* value, int length)
{
return readValue((uint8_t*)value, length);
}
int BLECharacteristic::readValue(uint8_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::readValue(int8_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::readValue(uint16_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::readValue(int16_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::readValue(uint32_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::readValue(int32_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLECharacteristic::writeValue(const uint8_t value[], int length, bool withResponse)
{
if (_local) {
return _local->writeValue(value, length);
}
if (_remote) {
return _remote->writeValue(value, length, withResponse);
}
return 0;
}
int BLECharacteristic::writeValue(const void* value, int length, bool withResponse)
{
return writeValue((const uint8_t*)value, length, withResponse);
}
int BLECharacteristic::writeValue(const char* value, bool withResponse)
{
if (_local) {
return _local->writeValue(value);
}
if (_remote) {
return _remote->writeValue(value, withResponse);
}
return 0;
}
int BLECharacteristic::writeValue(uint8_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::writeValue(int8_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::writeValue(uint16_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::writeValue(int16_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::writeValue(uint32_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::writeValue(int32_t value, bool withResponse)
{
return writeValue((uint8_t*)&value, sizeof(value), withResponse);
}
int BLECharacteristic::broadcast()
{
if (_local) {
return _local->broadcast();
}
return 0;
}
bool BLECharacteristic::written()
{
if (_local) {
return _local->written();
}
return false;
}
bool BLECharacteristic::subscribed()
{
if (_local) {
return _local->subscribed();
}
return false;
}
bool BLECharacteristic::valueUpdated()
{
if (_remote) {
return _remote->valueUpdated();
}
return false;
}
void BLECharacteristic::addDescriptor(BLEDescriptor& descriptor)
{
if (_local) {
return _local->addDescriptor(descriptor);
}
}
BLECharacteristic::operator bool() const
{
return (_local != NULL) || (_remote != NULL);
}
BLELocalCharacteristic* BLECharacteristic::local()
{
return _local;
}
void BLECharacteristic::setEventHandler(int event, BLECharacteristicEventHandler eventHandler)
{
if (_local) {
_local->setEventHandler((BLECharacteristicEvent)event, eventHandler);
}
if (_remote) {
_remote->setEventHandler((BLECharacteristicEvent)event, eventHandler);
}
}
int BLECharacteristic::descriptorCount() const
{
if (_remote) {
return _remote->descriptorCount();
}
return 0;
}
bool BLECharacteristic::hasDescriptor(const char* uuid) const
{
return hasDescriptor(uuid, 0);
}
bool BLECharacteristic::hasDescriptor(const char* uuid, int index) const
{
if (_remote) {
int count = 0;
int numDescriptors = _remote->descriptorCount();
for (int i = 0; i < numDescriptors; i++) {
BLERemoteDescriptor* d = _remote->descriptor(i);
if (strcasecmp(uuid, d->uuid()) == 0) {
if (count == index) {
return true;
}
count++;
}
}
}
return false;
}
BLEDescriptor BLECharacteristic::descriptor(int index) const
{
if (_remote) {
return BLEDescriptor(_remote->descriptor(index));
}
return BLEDescriptor();
}
BLEDescriptor BLECharacteristic::descriptor(const char * uuid) const
{
return descriptor(uuid, 0);
}
BLEDescriptor BLECharacteristic::descriptor(const char * uuid, int index) const
{
if (_remote) {
int count = 0;
int numDescriptors = _remote->descriptorCount();
for (int i = 0; i < numDescriptors; i++) {
BLERemoteDescriptor* d = _remote->descriptor(i);
if (strcasecmp(uuid, d->uuid()) == 0) {
if (count == index) {
return BLEDescriptor(d);
}
count++;
}
}
}
return BLEDescriptor();
}
bool BLECharacteristic::canRead()
{
if (_remote) {
return (properties() & BLERead) != 0;
}
return false;
}
bool BLECharacteristic::read()
{
if (_remote) {
return _remote->read();
}
return false;
}
bool BLECharacteristic::canWrite()
{
if (_remote) {
return (properties() & (BLEWrite | BLEWriteWithoutResponse)) != 0;
}
return false;
}
bool BLECharacteristic::canSubscribe()
{
if (_remote) {
return (properties() & (BLENotify | BLEIndicate)) != 0;
}
return false;
}
bool BLECharacteristic::subscribe()
{
if (_remote) {
return _remote->writeCccd((properties() & BLEIndicate) ? 0x0002 : 0x0001);
}
return false;
}
bool BLECharacteristic::canUnsubscribe()
{
return canSubscribe();
}
bool BLECharacteristic::unsubscribe()
{
if (_remote) {
return _remote->writeCccd(0x0000);
}
return false;
}
================================================
FILE: src/BLECharacteristic.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_CHARACTERISTIC_H_
#define _BLE_CHARACTERISTIC_H_
#include
#include "BLEDescriptor.h"
enum BLECharacteristicEvent {
BLESubscribed = 0,
BLEUnsubscribed = 1,
//BLERead = 2, // defined in BLEProperties.h
BLEWritten = 3,
BLEUpdated = BLEWritten, // alias
BLECharacteristicEventLast
};
class BLECharacteristic;
class BLEDevice;
typedef void (*BLECharacteristicEventHandler)(BLEDevice device, BLECharacteristic characteristic);
class BLELocalCharacteristic;
class BLERemoteCharacteristic;
class BLECharacteristic {
public:
BLECharacteristic();
BLECharacteristic(const char* uuid, uint16_t permissions, int valueSize, bool fixedLength = false);
BLECharacteristic(const char* uuid, uint16_t permissions, const char* value);
BLECharacteristic(const BLECharacteristic& other);
virtual ~BLECharacteristic();
const char* uuid() const;
uint8_t properties() const;
int valueSize() const;
const uint8_t* value() const;
int valueLength() const;
uint8_t operator[] (int offset) const;
int readValue(uint8_t value[], int length);
int readValue(void* value, int length);
int readValue(uint8_t& value);
int readValue(int8_t& value);
int readValue(uint16_t& value);
int readValue(int16_t& value);
int readValue(uint32_t& value);
int readValue(int32_t& value);
int writeValue(const uint8_t value[], int length, bool withResponse = true);
int writeValue(const void* value, int length, bool withResponse = true);
int writeValue(const char* value, bool withResponse = true);
int writeValue(uint8_t value, bool withResponse = true);
int writeValue(int8_t value, bool withResponse = true);
int writeValue(uint16_t value, bool withResponse = true);
int writeValue(int16_t value, bool withResponse = true);
int writeValue(uint32_t value, bool withResponse = true);
int writeValue(int32_t value, bool withResponse = true);
// deprecated, use writeValue(...)
int setValue(const uint8_t value[], int length) { return writeValue(value, length); }
int setValue(const char* value) { return writeValue(value); }
int broadcast();
bool written();
bool subscribed();
bool valueUpdated();
void addDescriptor(BLEDescriptor& descriptor);
operator bool() const;
void setEventHandler(int event, BLECharacteristicEventHandler eventHandler);
int descriptorCount() const;
bool hasDescriptor(const char* uuid) const;
bool hasDescriptor(const char* uuid, int index) const;
BLEDescriptor descriptor(int index) const;
BLEDescriptor descriptor(const char * uuid) const;
BLEDescriptor descriptor(const char * uuid, int index) const;
bool canRead();
bool read();
bool canWrite();
bool canSubscribe();
bool subscribe();
bool canUnsubscribe();
bool unsubscribe();
protected:
friend class BLELocalCharacteristic;
friend class BLELocalService;
BLECharacteristic(BLELocalCharacteristic* local);
BLELocalCharacteristic* local();
protected:
friend class BLEDevice;
friend class BLEService;
friend class BLERemoteCharacteristic;
BLECharacteristic(BLERemoteCharacteristic* remote);
private:
BLELocalCharacteristic* _local;
BLERemoteCharacteristic* _remote;
};
#endif
================================================
FILE: src/BLEDescriptor.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "local/BLELocalDescriptor.h"
#include "remote/BLERemoteDescriptor.h"
#include "BLEDescriptor.h"
BLEDescriptor::BLEDescriptor() :
BLEDescriptor((BLELocalDescriptor*)NULL)
{
}
BLEDescriptor::BLEDescriptor(BLELocalDescriptor* local) :
_local(local),
_remote(NULL)
{
if (_local) {
_local->retain();
}
}
BLEDescriptor::BLEDescriptor(BLERemoteDescriptor* remote) :
_local(NULL),
_remote(remote)
{
if (_remote) {
_remote->retain();
}
}
BLEDescriptor::BLEDescriptor(const char* uuid, const uint8_t value[], int valueSize) :
BLEDescriptor(new BLELocalDescriptor(uuid, value, valueSize))
{
}
BLEDescriptor::BLEDescriptor(const char* uuid, const char* value) :
BLEDescriptor(new BLELocalDescriptor(uuid, value))
{
}
BLEDescriptor::BLEDescriptor(const BLEDescriptor& other)
{
_local = other._local;
if (_local) {
_local->retain();
}
_remote = other._remote;
if (_remote) {
_remote->retain();
}
}
BLEDescriptor::~BLEDescriptor()
{
if (_local && _local->release() == 0) {
delete _local;
}
if (_remote && _remote->release() == 0) {
delete _remote;
}
}
const char* BLEDescriptor::uuid() const
{
if (_local) {
return _local->uuid();
}
if (_remote) {
return _remote->uuid();
}
return "";
}
int BLEDescriptor::valueSize() const
{
if (_local) {
return _local->valueSize();
}
if (_remote) {
return _remote->valueLength();
}
return 0;
}
const uint8_t* BLEDescriptor::value() const
{
if (_local) {
return _local->value();
}
if (_remote) {
return _remote->value();
}
return NULL;
}
int BLEDescriptor::valueLength() const
{
return valueSize();
}
uint8_t BLEDescriptor::operator[] (int offset) const
{
if (_local) {
return (*_local)[offset];
}
if (_remote) {
return (*_remote)[offset];
}
return 0;
}
int BLEDescriptor::readValue(uint8_t value[], int length)
{
int bytesRead = 0;
if (_local) {
bytesRead = min(length, _local->valueSize());
memcpy(value, _local->value(), bytesRead);
}
if (_remote) {
if (!read()) {
// read failed
return 0;
}
bytesRead = min(length, _remote->valueLength());
memcpy(value, _remote->value(), bytesRead);
}
return bytesRead;
}
int BLEDescriptor::readValue(void* value, int length)
{
return readValue((uint8_t*)value, length);
}
int BLEDescriptor::readValue(uint8_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLEDescriptor::readValue(int8_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLEDescriptor::readValue(uint16_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLEDescriptor::readValue(int16_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLEDescriptor::readValue(uint32_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
int BLEDescriptor::readValue(int32_t& value)
{
value = 0;
return readValue((uint8_t*)&value, sizeof(value));
}
BLEDescriptor::operator bool() const
{
return (_local != NULL) || (_remote != NULL);
}
bool BLEDescriptor::read()
{
if (_remote) {
return _remote->read();
}
return false;
}
BLELocalDescriptor* BLEDescriptor::local()
{
return _local;
}
================================================
FILE: src/BLEDescriptor.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_DESCRIPTOR_H_
#define _BLE_DESCRIPTOR_H_
#include
class BLELocalDescriptor;
class BLERemoteDescriptor;
class BLEDescriptor {
public:
BLEDescriptor();
BLEDescriptor(const BLEDescriptor& other);
BLEDescriptor(const char* uuid, const uint8_t value[], int valueSize);
BLEDescriptor(const char* uuid, const char* value);
virtual ~BLEDescriptor();
const char* uuid() const;
int valueSize() const;
const uint8_t* value() const;
int valueLength() const;
uint8_t operator[] (int offset) const;
int readValue(uint8_t value[], int length);
int readValue(void* value, int length);
int readValue(uint8_t& value);
int readValue(int8_t& value);
int readValue(uint16_t& value);
int readValue(int16_t& value);
int readValue(uint32_t& value);
int readValue(int32_t& value);
operator bool() const;
bool read();
protected:
friend class BLELocalCharacteristic;
BLEDescriptor(BLELocalDescriptor* local);
BLELocalDescriptor* local();
protected:
friend class BLECharacteristic;
BLEDescriptor(BLERemoteDescriptor* remote);
private:
BLELocalDescriptor* _local;
BLERemoteDescriptor* _remote;
};
#endif
================================================
FILE: src/BLEDevice.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "utility/ATT.h"
#include "utility/BLEUuid.h"
#include "utility/HCI.h"
#include "remote/BLERemoteDevice.h"
#include "BLEDevice.h"
extern "C" int strcasecmp(char const *a, char const *b);
BLEDevice::BLEDevice() :
_advertisementTypeMask(0),
_eirDataLength(0),
_rssi(127)
{
memset(_address, 0x00, sizeof(_address));
}
BLEDevice::BLEDevice(uint8_t addressType, uint8_t address[6]) :
_addressType(addressType),
_advertisementTypeMask(0),
_eirDataLength(0),
_rssi(127)
{
memcpy(_address, address, sizeof(_address));
}
BLEDevice::~BLEDevice()
{
}
void BLEDevice::poll()
{
HCI.poll();
}
void BLEDevice::poll(unsigned long timeout)
{
HCI.poll(timeout);
}
bool BLEDevice::connected() const
{
HCI.poll();
if (!(*this)) {
return false;
}
return ATT.connected(_addressType, _address);
}
bool BLEDevice::disconnect()
{
return ATT.disconnect(_addressType, _address);
}
String BLEDevice::address() const
{
char result[18];
sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x", _address[5], _address[4], _address[3], _address[2], _address[1], _address[0]);
return result;
}
bool BLEDevice::hasLocalName() const
{
return (localName().length() > 0);
}
bool BLEDevice::hasAdvertisedServiceUuid() const
{
return hasAdvertisedServiceUuid(0);
}
bool BLEDevice::hasAdvertisedServiceUuid(int index) const
{
return (advertisedServiceUuid(index).length() > 0);
}
int BLEDevice::advertisedServiceUuidCount() const
{
int advertisedServiceCount = 0;
for (unsigned char i = 0; i < _eirDataLength;) {
int eirLength = _eirData[i++];
int eirType = _eirData[i++];
if (eirType == 0x02 || eirType == 0x03 || eirType == 0x06 || eirType == 0x07) {
int uuidLength;
if (eirType == 0x02 || eirType == 0x03) {
uuidLength = 2;
} else /*if (eirType == 0x06 || eirType == 0x07)*/ {
uuidLength = 16;
}
for (int j = 0; j < (eirLength - 1); j += uuidLength) {
advertisedServiceCount++;
}
}
i += (eirLength - 1);
}
return advertisedServiceCount;
}
String BLEDevice::localName() const
{
String localName = "";
for (int i = 0; i < _eirDataLength;) {
int eirLength = _eirData[i++];
int eirType = _eirData[i++];
if (eirType == 0x08 || eirType == 0x09) {
localName.reserve(eirLength - 1);
for (int j = 0; j < (eirLength - 1); j++) {
localName += (char)_eirData[i + j];
}
break;
}
i += (eirLength - 1);
}
return localName;
}
String BLEDevice::advertisedServiceUuid() const
{
return advertisedServiceUuid(0);
}
String BLEDevice::advertisedServiceUuid(int index) const
{
String serviceUuid;
int uuidIndex = 0;
for (unsigned char i = 0; i < _eirDataLength;) {
int eirLength = _eirData[i++];
int eirType = _eirData[i++];
if (eirType == 0x02 || eirType == 0x03 || eirType == 0x06 || eirType == 0x07) {
int uuidLength;
if (eirType == 0x02 || eirType == 0x03) {
uuidLength = 2;
} else /*if (eirType == 0x06 || eirType == 0x07)*/ {
uuidLength = 16;
}
for (int j = 0; j < (eirLength - 1); j += uuidLength) {
if (uuidIndex == index) {
serviceUuid = BLEUuid::uuidToString(&_eirData[i + j * uuidLength], uuidLength);
}
uuidIndex++;
}
}
i += (eirLength - 1);
}
return serviceUuid;
}
bool BLEDevice::hasAdvertisementData() const
{
return (_eirDataLength > 0);
}
int BLEDevice::advertisementDataLength() const
{
return _eirDataLength;
}
int BLEDevice::advertisementData(uint8_t value[], int length) const
{
if (length > _eirDataLength) length = _eirDataLength;
if (length) {
memcpy(value, _eirData, length);
}
return length;
}
bool BLEDevice::hasManufacturerData() const
{
return (manufacturerDataLength() > 0);
}
int BLEDevice::manufacturerDataLength() const
{
int length = 0;
for (int i = 0; i < _eirDataLength;) {
int eirLength = _eirData[i++];
int eirType = _eirData[i++];
if (eirType == 0xFF) {
length = (eirLength - 1);
break;
}
i += (eirLength - 1);
}
return length;
}
int BLEDevice::manufacturerData(uint8_t value[], int length) const
{
for (int i = 0; i < _eirDataLength;) {
int eirLength = _eirData[i++];
int eirType = _eirData[i++];
if (eirType == 0xFF) {
if (length > (eirLength - 1)) length = (eirLength - 1);
memcpy(value, &_eirData[i], length);
break;
}
i += (eirLength - 1);
}
return length;
}
int BLEDevice::rssi()
{
uint16_t handle = ATT.connectionHandle(_addressType, _address);
if (handle != 0xffff) {
return HCI.readRssi(handle);
}
return _rssi;
}
bool BLEDevice::connect()
{
return ATT.connect(_addressType, _address);
}
bool BLEDevice::discoverAttributes()
{
return ATT.discoverAttributes(_addressType, _address, NULL);
}
bool BLEDevice::discoverService(const char* serviceUuid)
{
return ATT.discoverAttributes(_addressType, _address, serviceUuid);
}
BLEDevice::operator bool() const
{
uint8_t zeros[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,};
return (memcmp(_address, zeros, sizeof(zeros)) != 0);
}
bool BLEDevice::operator==(const BLEDevice& rhs) const
{
return ((_addressType == rhs._addressType) && memcmp(_address, rhs._address, sizeof(_address)) == 0);
}
bool BLEDevice::operator!=(const BLEDevice& rhs) const
{
return ((_addressType != rhs._addressType) || memcmp(_address, rhs._address, sizeof(_address)) != 0);
}
String BLEDevice::deviceName()
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
BLEService genericAccessService = service("1800");
if (genericAccessService) {
BLECharacteristic deviceNameCharacteristic = genericAccessService.characteristic("2a00");
if (deviceNameCharacteristic) {
deviceNameCharacteristic.read();
String result;
int valueLength = deviceNameCharacteristic.valueLength();
const char* value = (const char*)deviceNameCharacteristic.value();
result.reserve(valueLength);
for (int i = 0; i < valueLength; i++) {
result += value[i];
}
return result;
}
}
}
return "";
}
int BLEDevice::appearance()
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
BLEService genericAccessService = service("1801");
if (genericAccessService) {
BLECharacteristic appearanceCharacteristic = genericAccessService.characteristic("2a01");
if (appearanceCharacteristic) {
appearanceCharacteristic.read();
uint16_t result = 0;
memcpy (&result, appearanceCharacteristic.value(), min((int)sizeof(result), appearanceCharacteristic.valueLength()));
return result;
}
}
}
return 0;
}
int BLEDevice::serviceCount() const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
return device->serviceCount();
}
return 0;
}
bool BLEDevice::hasService(const char* uuid) const
{
return hasService(uuid, 0);
}
bool BLEDevice::hasService(const char* uuid, int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int count = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
BLERemoteService* s = device->service(i);
if (strcasecmp(uuid, s->uuid()) == 0) {
if (count == index) {
return true;
}
count++;
}
}
}
return false;
}
BLEService BLEDevice::service(int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
if (index < (int)device->serviceCount()) {
return BLEService(device->service(index));
}
}
return BLEService();
}
BLEService BLEDevice::service(const char * uuid) const
{
return service(uuid, 0);
}
BLEService BLEDevice::service(const char * uuid, int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int count = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
BLERemoteService* s = device->service(i);
if (strcasecmp(uuid, s->uuid()) == 0) {
if (count == index) {
return BLEService(s);
}
count++;
}
}
}
return BLEService();
}
int BLEDevice::characteristicCount() const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int result = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
result += device->service(i)->characteristicCount();
}
return result;
}
return 0;
}
bool BLEDevice::hasCharacteristic(const char* uuid) const
{
return hasCharacteristic(uuid, 0);
}
bool BLEDevice::hasCharacteristic(const char* uuid, int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int count = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
BLERemoteService* s = device->service(i);
int numCharacteristics = s->characteristicCount();
for (int j = 0; j < numCharacteristics; j++) {
BLERemoteCharacteristic* c = s->characteristic(j);
if (strcasecmp(c->uuid(), uuid) == 0) {
if (count == index) {
return true;
}
}
count++;
}
}
}
return false;
}
BLECharacteristic BLEDevice::characteristic(int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int count = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
BLERemoteService* s = device->service(i);
int numCharacteristics = s->characteristicCount();
for (int j = 0; j < numCharacteristics; j++) {
if (count == index) {
BLERemoteCharacteristic* c = s->characteristic(j);
return BLECharacteristic(c);
}
count++;
}
}
}
return BLECharacteristic();
}
BLECharacteristic BLEDevice::characteristic(const char * uuid) const
{
return characteristic(uuid, 0);
}
BLECharacteristic BLEDevice::characteristic(const char * uuid, int index) const
{
BLERemoteDevice* device = ATT.device(_addressType, _address);
if (device) {
int count = 0;
int numServices = device->serviceCount();
for (int i = 0; i < numServices; i++) {
BLERemoteService* s = device->service(i);
int numCharacteristics = s->characteristicCount();
for (int j = 0; j < numCharacteristics; j++) {
BLERemoteCharacteristic* c = s->characteristic(j);
if (strcasecmp(c->uuid(), uuid) == 0) {
if (count == index) {
return BLECharacteristic(c);
}
count++;
}
}
}
}
return BLECharacteristic();
}
bool BLEDevice::hasAddress(uint8_t addressType, uint8_t address[6])
{
return (_addressType == addressType) && (memcmp(_address, address, sizeof(_address)) == 0);
}
void BLEDevice::setAdvertisementData(uint8_t type, uint8_t eirDataLength, uint8_t eirData[], int8_t rssi)
{
_advertisementTypeMask = (1 << type);
_eirDataLength = eirDataLength;
memcpy(_eirData, eirData, eirDataLength);
_rssi = rssi;
}
void BLEDevice::setScanResponseData(uint8_t eirDataLength, uint8_t eirData[], int8_t rssi)
{
_advertisementTypeMask |= (1 << 0x04);
memcpy(&_eirData[_eirDataLength], eirData, eirDataLength);
_eirDataLength += eirDataLength;
_rssi = rssi;
}
bool BLEDevice::discovered()
{
// expect, 0x03 or 0x04 flag to be set
return (_advertisementTypeMask & 0x18) != 0;
}
================================================
FILE: src/BLEDevice.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_DEVICE_H_
#define _BLE_DEVICE_H_
#include
#include "BLEService.h"
enum BLEDeviceEvent {
BLEConnected = 0,
BLEDisconnected = 1,
BLEDiscovered = 2,
BLEDeviceLastEvent
};
class BLEDevice;
typedef void (*BLEDeviceEventHandler)(BLEDevice device);
class BLEDevice {
public:
BLEDevice();
virtual ~BLEDevice();
virtual void poll();
virtual void poll(unsigned long timeout);
virtual bool connected() const;
virtual bool disconnect();
virtual String address() const;
bool hasLocalName() const;
bool hasAdvertisedServiceUuid() const;
bool hasAdvertisedServiceUuid(int index) const;
int advertisedServiceUuidCount() const;
String localName() const;
String advertisedServiceUuid() const;
String advertisedServiceUuid(int index) const;
bool hasAdvertisementData() const;
int advertisementDataLength() const;
int advertisementData(uint8_t value[], int length) const;
bool hasManufacturerData() const;
int manufacturerDataLength() const;
int manufacturerData(uint8_t value[], int length) const;
virtual int rssi();
bool connect();
bool discoverAttributes();
bool discoverService(const char* serviceUuid);
virtual operator bool() const;
virtual bool operator==(const BLEDevice& rhs) const;
virtual bool operator!=(const BLEDevice& rhs) const;
String deviceName();
int appearance();
int serviceCount() const;
bool hasService(const char* uuid) const;
bool hasService(const char* uuid, int index) const;
BLEService service(int index) const;
BLEService service(const char * uuid) const;
BLEService service(const char * uuid, int index) const;
int characteristicCount() const;
bool hasCharacteristic(const char* uuid) const;
bool hasCharacteristic(const char* uuid, int index) const;
BLECharacteristic characteristic(int index) const;
BLECharacteristic characteristic(const char * uuid) const;
BLECharacteristic characteristic(const char * uuid, int index) const;
protected:
friend class ATTClass;
friend class GAPClass;
BLEDevice(uint8_t addressType, uint8_t address[6]);
protected:
friend class GAPClass;
bool hasAddress(uint8_t addressType, uint8_t address[6]);
void setAdvertisementData(uint8_t type, uint8_t eirDataLength, uint8_t eirData[], int8_t rssi);
void setScanResponseData(uint8_t eirDataLength, uint8_t eirData[], int8_t rssi);
bool discovered();
private:
uint8_t _addressType;
uint8_t _address[6];
uint8_t _advertisementTypeMask;
uint8_t _eirDataLength;
uint8_t _eirData[31 * 2];
int8_t _rssi;
};
#endif
================================================
FILE: src/BLEProperty.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
// #include
#ifndef _BLE_PROPERTY_H_
#define _BLE_PROPERTY_H_
enum BLEProperty {
BLEBroadcast = 0x01,
BLERead = 0x02,
BLEWriteWithoutResponse = 0x04,
BLEWrite = 0x08,
BLENotify = 0x10,
BLEIndicate = 0x20,
BLEAuthSignedWrite = 1 << 6,
BLEExtProp = 1 << 7,
};
enum BLEPermission {
BLEEncryption = 1 << 9,
BLEAuthentication = 1 << 10,
BLEAuthorization = 1 << 11,
// BLEWriteEncryption = 1 << 11,
// BLEWriteAuthentication = 1 << 12,
// BLEWriteAuthorization = 1 << 13,
};
#define ESP_GATT_CHAR_PROP_BIT_BROADCAST (1 << 0) /* 0x01 */ /* relate to BTA_GATT_CHAR_PROP_BIT_BROADCAST in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_READ (1 << 1) /* 0x02 */ /* relate to BTA_GATT_CHAR_PROP_BIT_READ in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_WRITE_NR (1 << 2) /* 0x04 */ /* relate to BTA_GATT_CHAR_PROP_BIT_WRITE_NR in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_WRITE (1 << 3) /* 0x08 */ /* relate to BTA_GATT_CHAR_PROP_BIT_WRITE in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_NOTIFY (1 << 4) /* 0x10 */ /* relate to BTA_GATT_CHAR_PROP_BIT_NOTIFY in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_INDICATE (1 << 5) /* 0x20 */ /* relate to BTA_GATT_CHAR_PROP_BIT_INDICATE in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_AUTH (1 << 6) /* 0x40 */ /* relate to BTA_GATT_CHAR_PROP_BIT_AUTH in bta/bta_gatt_api.h */
#define ESP_GATT_CHAR_PROP_BIT_EXT_PROP (1 << 7) /* 0x80 */ /* relate to BTA_GATT_CHAR_PROP_BIT_EXT_PROP in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_READ (1 << 0) /* bit 0 - 0x0001 */ /* relate to BTA_GATT_PERM_READ in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 - 0x0002 */ /* relate to BTA_GATT_PERM_READ_ENCRYPTED in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_READ_ENC_MITM (1 << 2) /* bit 2 - 0x0004 */ /* relate to BTA_GATT_PERM_READ_ENC_MITM in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_WRITE (1 << 4) /* bit 4 - 0x0010 */ /* relate to BTA_GATT_PERM_WRITE in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 - 0x0020 */ /* relate to BTA_GATT_PERM_WRITE_ENCRYPTED in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_WRITE_ENC_MITM (1 << 6) /* bit 6 - 0x0040 */ /* relate to BTA_GATT_PERM_WRITE_ENC_MITM in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 - 0x0080 */ /* relate to BTA_GATT_PERM_WRITE_SIGNED in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_WRITE_SIGNED_MITM (1 << 8) /* bit 8 - 0x0100 */ /* relate to BTA_GATT_PERM_WRITE_SIGNED_MITM in bta/bta_gatt_api.h */
#define ESP_GATT_PERM_READ_AUTHORIZATION (1 << 9) /* bit 9 - 0x0200 */
#define ESP_GATT_PERM_WRITE_AUTHORIZATION (1 << 10) /* bit 10 - 0x0400 */
enum BLE_GATT_PERM_ {
BLE_GATT_READ = 1 << 0,
READ_ENCRYPTED = 1 << 1,
READ_ENC_MITM = 1 << 2,
BLE_GATT_WRITE = 1 << 4,
WRITE_ENCRYPTED = 1 << 5,
WRITE_ENC_MITM = 1 << 6,
WRITE_SIGNED = 1 << 7,
WRITE_SIGNED_MITM = 1 << 8,
READ_AUTHORIZATION = 1 << 9,
WRITE_AUTHORIZATION = 1 << 10,
};
#endif
================================================
FILE: src/BLEService.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "local/BLELocalService.h"
#include "remote/BLERemoteService.h"
#include "BLEService.h"
extern "C" int strcasecmp(char const *a, char const *b);
BLEService::BLEService() :
BLEService((BLELocalService*)NULL)
{
}
BLEService::BLEService(BLELocalService* local) :
_local(local),
_remote(NULL)
{
if (_local) {
_local->retain();
}
}
BLEService::BLEService(BLERemoteService* remote) :
_local(NULL),
_remote(remote)
{
if (_remote) {
_remote->retain();
}
}
BLEService::BLEService(const char* uuid) :
BLEService(new BLELocalService(uuid))
{
}
BLEService::BLEService(const BLEService& other)
{
_local = other._local;
if (_local) {
_local->retain();
}
_remote = other._remote;
if (_remote) {
_remote->retain();
}
}
void BLEService::clear()
{
if (_local) {
_local->clear();
}
}
BLEService::~BLEService()
{
if (_local && _local->release() == 0) {
delete _local;
}
if (_remote && _remote->release() == 0) {
delete _remote;
}
}
const char* BLEService::uuid() const
{
if (_local) {
return _local->uuid();
}
if (_remote) {
return _remote->uuid();
}
return "";
}
void BLEService::addCharacteristic(BLECharacteristic& characteristic)
{
if (_local) {
_local->addCharacteristic(characteristic);
}
}
BLEService::operator bool() const
{
return (_local != NULL) || (_remote != NULL);
}
int BLEService::characteristicCount() const
{
if (_remote) {
return _remote->characteristicCount();
}
return 0;
}
bool BLEService::hasCharacteristic(const char* uuid) const
{
return hasCharacteristic(uuid, 0);
}
bool BLEService::hasCharacteristic(const char* uuid, int index) const
{
if (_remote) {
int count = 0;
int numCharacteristics = _remote->characteristicCount();
for (int i = 0; i < numCharacteristics; i++) {
BLERemoteCharacteristic* c = _remote->characteristic(i);
if (strcasecmp(uuid, c->uuid()) == 0) {
if (count == index) {
return true;
}
count++;
}
}
}
return false;
}
BLECharacteristic BLEService::characteristic(int index) const
{
if (_remote) {
return BLECharacteristic(_remote->characteristic(index));
}
return BLECharacteristic();
}
BLECharacteristic BLEService::characteristic(const char * uuid) const
{
return characteristic(uuid, 0);
}
BLECharacteristic BLEService::characteristic(const char * uuid, int index) const
{
if (_remote) {
int count = 0;
int numCharacteristics = _remote->characteristicCount();
for (int i = 0; i < numCharacteristics; i++) {
BLERemoteCharacteristic* c = _remote->characteristic(i);
if (strcasecmp(uuid, c->uuid()) == 0) {
if (count == index) {
return BLECharacteristic(c);
}
count++;
}
}
}
return BLECharacteristic();
}
BLELocalService* BLEService::local()
{
return _local;
}
================================================
FILE: src/BLEService.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_SERVICE_H_
#define _BLE_SERVICE_H_
#include "BLECharacteristic.h"
class BLELocalService;
class BLERemoteService;
class BLEService {
public:
BLEService();
BLEService(const char* uuid);
BLEService(const BLEService& other);
virtual ~BLEService();
const char* uuid() const;
void clear();
void addCharacteristic(BLECharacteristic& characteristic);
operator bool() const;
int characteristicCount() const;
bool hasCharacteristic(const char* uuid) const;
bool hasCharacteristic(const char* uuid, int index) const;
BLECharacteristic characteristic(int index) const;
BLECharacteristic characteristic(const char * uuid) const;
BLECharacteristic characteristic(const char * uuid, int index) const;
protected:
friend class GATTClass;
BLEService(BLELocalService* local);
BLELocalService* local();
void addCharacteristic(BLELocalCharacteristic* characteristic);
protected:
friend class BLEDevice;
BLEService(BLERemoteService* remote);
private:
BLELocalService* _local;
BLERemoteService* _remote;
};
#endif
================================================
FILE: src/BLEStringCharacteristic.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLEStringCharacteristic.h"
BLEStringCharacteristic::BLEStringCharacteristic(const char* uuid, unsigned int properties, int valueSize) :
BLECharacteristic(uuid, properties, valueSize)
{
}
int BLEStringCharacteristic::writeValue(const String& value)
{
return BLECharacteristic::writeValue(value.c_str());
}
String BLEStringCharacteristic::value(void)
{
String str;
int length = BLECharacteristic::valueLength();
const uint8_t* val = BLECharacteristic::value();
str.reserve(length);
for (int i = 0; i < length; i++) {
str += (char)val[i];
}
return str;
}
================================================
FILE: src/BLEStringCharacteristic.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_STRING_CHARACTERISTIC_H_
#define _BLE_STRING_CHARACTERISTIC_H_
#include
#include "BLECharacteristic.h"
class BLEStringCharacteristic : public BLECharacteristic
{
public:
BLEStringCharacteristic(const char* uuid, unsigned int properties, int valueSize);
int writeValue(const String& value);
int setValue(const String& value) { return writeValue(value); }
String value(void);
private:
};
#endif
================================================
FILE: src/BLETypedCharacteristic.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_TYPED_CHARACTERISTIC_H_
#define _BLE_TYPED_CHARACTERISTIC_H_
#include "BLECharacteristic.h"
template class BLETypedCharacteristic : public BLECharacteristic
{
public:
BLETypedCharacteristic(const char* uuid, unsigned int permissions);
int writeValue(T value);
int setValue(T value) { return writeValue(value); }
T value(void);
int writeValueLE(T value);
int setValueLE(T value) { return writeValueLE(value); }
T valueLE(void);
int writeValueBE(T value);
int setValueBE(T value) { return writeValueBE(value); }
T valueBE(void);
private:
T byteSwap(T value);
};
template BLETypedCharacteristic::BLETypedCharacteristic(const char* uuid, unsigned int permissions) :
BLECharacteristic(uuid, permissions, sizeof(T), true)
{
T value;
memset(&value, 0x00, sizeof(value));
writeValue(value);
}
template int BLETypedCharacteristic::writeValue(T value)
{
return BLECharacteristic::writeValue((uint8_t*)&value, sizeof(T));
}
template T BLETypedCharacteristic::value()
{
T value;
memcpy(&value, (unsigned char*)BLECharacteristic::value(), BLECharacteristic::valueSize());
return value;
}
template int BLETypedCharacteristic::writeValueLE(T value)
{
return writeValue(value);
}
template T BLETypedCharacteristic::valueLE()
{
return value();
}
template int BLETypedCharacteristic::writeValueBE(T value)
{
return writeValue(byteSwap(value));
}
template T BLETypedCharacteristic::valueBE()
{
return byteSwap(value());
}
template T BLETypedCharacteristic::byteSwap(T value)
{
T result;
unsigned char* src = (unsigned char*)&value;
unsigned char* dst = (unsigned char*)&result;
for (int i = 0; i < sizeof(T); i++) {
dst[i] = src[sizeof(T) - i - 1];
}
return result;
}
#endif
================================================
FILE: src/BLETypedCharacteristics.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "BLETypedCharacteristics.h"
BLEBoolCharacteristic::BLEBoolCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEBooleanCharacteristic::BLEBooleanCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLECharCharacteristic::BLECharCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEUnsignedCharCharacteristic::BLEUnsignedCharCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEByteCharacteristic::BLEByteCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEShortCharacteristic::BLEShortCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEUnsignedShortCharacteristic::BLEUnsignedShortCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEWordCharacteristic::BLEWordCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEIntCharacteristic::BLEIntCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEUnsignedIntCharacteristic::BLEUnsignedIntCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLELongCharacteristic::BLELongCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEUnsignedLongCharacteristic::BLEUnsignedLongCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEFloatCharacteristic::BLEFloatCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
BLEDoubleCharacteristic::BLEDoubleCharacteristic(const char* uuid, unsigned int properties) :
BLETypedCharacteristic(uuid, properties)
{
}
================================================
FILE: src/BLETypedCharacteristics.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_TYPED_CHARACTERISTICS_H_
#define _BLE_TYPED_CHARACTERISTICS_H_
#include "BLETypedCharacteristic.h"
class BLEBoolCharacteristic : public BLETypedCharacteristic {
public:
BLEBoolCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEBooleanCharacteristic : public BLETypedCharacteristic {
public:
BLEBooleanCharacteristic(const char* uuid, unsigned int permissions);
};
class BLECharCharacteristic : public BLETypedCharacteristic {
public:
BLECharCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEUnsignedCharCharacteristic : public BLETypedCharacteristic {
public:
BLEUnsignedCharCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEByteCharacteristic : public BLETypedCharacteristic {
public:
BLEByteCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEShortCharacteristic : public BLETypedCharacteristic {
public:
BLEShortCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEUnsignedShortCharacteristic : public BLETypedCharacteristic {
public:
BLEUnsignedShortCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEWordCharacteristic : public BLETypedCharacteristic {
public:
BLEWordCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEIntCharacteristic : public BLETypedCharacteristic {
public:
BLEIntCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEUnsignedIntCharacteristic : public BLETypedCharacteristic {
public:
BLEUnsignedIntCharacteristic(const char* uuid, unsigned int permissions);
};
class BLELongCharacteristic : public BLETypedCharacteristic {
public:
BLELongCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEUnsignedLongCharacteristic : public BLETypedCharacteristic {
public:
BLEUnsignedLongCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEFloatCharacteristic : public BLETypedCharacteristic {
public:
BLEFloatCharacteristic(const char* uuid, unsigned int permissions);
};
class BLEDoubleCharacteristic : public BLETypedCharacteristic {
public:
BLEDoubleCharacteristic(const char* uuid, unsigned int permissions);
};
#endif
================================================
FILE: src/local/BLELocalAttribute.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLELocalAttribute.h"
BLELocalAttribute::BLELocalAttribute(const char* uuid) :
_uuid(uuid),
_refCount(0)
{
}
BLELocalAttribute::~BLELocalAttribute()
{
}
const char* BLELocalAttribute::uuid() const
{
return _uuid.str();
}
const uint8_t* BLELocalAttribute::uuidData() const
{
return _uuid.data();
}
uint8_t BLELocalAttribute::uuidLength() const
{
return _uuid.length();
}
enum BLEAttributeType BLELocalAttribute::type() const
{
return BLETypeUnknown;
}
int BLELocalAttribute::retain()
{
_refCount++;
return _refCount;
}
bool BLELocalAttribute::active()
{
return _refCount > 0;
}
int BLELocalAttribute::release()
{
_refCount--;
return _refCount;
}
================================================
FILE: src/local/BLELocalAttribute.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_LOCAL_ATTRIBUTE_H_
#define _BLE_LOCAL_ATTRIBUTE_H_
#include "utility/BLEUuid.h"
#define BLE_ATTRIBUTE_TYPE_SIZE 2
enum BLEAttributeType {
BLETypeUnknown = 0x0000,
BLETypeService = 0x2800,
BLETypeCharacteristic = 0x2803,
BLETypeDescriptor = 0x2900
};
class BLELocalAttribute
{
public:
BLELocalAttribute(const char* uuid);
virtual ~BLELocalAttribute();
const char* uuid() const;
virtual enum BLEAttributeType type() const;
int retain();
int release();
bool active();
protected:
friend class ATTClass;
friend class GATTClass;
const uint8_t* uuidData() const;
uint8_t uuidLength() const;
private:
BLEUuid _uuid;
int _refCount;
};
#endif
================================================
FILE: src/local/BLELocalCharacteristic.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "BLELocalDevice.h"
#include "utility/ATT.h"
#include "utility/GAP.h"
#include "utility/GATT.h"
#include "BLELocalDescriptor.h"
#include "BLEProperty.h"
#include "BLELocalCharacteristic.h"
BLELocalCharacteristic::BLELocalCharacteristic(const char* uuid, uint16_t permissions, int valueSize, bool fixedLength) :
BLELocalAttribute(uuid),
_properties((uint8_t)(permissions&0x000FF)),
_permissions((uint8_t)((permissions&0xFF00)>>8)),
_valueSize(min(valueSize, 512)),
_valueLength(0),
_fixedLength(fixedLength),
_handle(0x0000),
_broadcast(false),
_written(false),
_cccdValue(0x0000)
{
memset(_eventHandlers, 0x00, sizeof(_eventHandlers));
if (permissions & (BLENotify | BLEIndicate)) {
BLELocalDescriptor* cccd = new BLELocalDescriptor("2902", (uint8_t*)&_cccdValue, sizeof(_cccdValue));
cccd->retain();
_descriptors.add(cccd);
}
_value = (uint8_t*)malloc(valueSize);
}
BLELocalCharacteristic::BLELocalCharacteristic(const char* uuid, uint16_t permissions, const char* value) :
BLELocalCharacteristic(uuid, permissions, strlen(value))
{
writeValue(value);
}
BLELocalCharacteristic::~BLELocalCharacteristic()
{
for (unsigned int i = 0; i < descriptorCount(); i++) {
BLELocalDescriptor* d = descriptor(i);
if (d->release() == 0) {
delete d;
}
}
_descriptors.clear();
if (_value) {
free(_value);
}
}
enum BLEAttributeType BLELocalCharacteristic::type() const
{
return BLETypeCharacteristic;
}
uint8_t BLELocalCharacteristic::properties() const
{
return _properties;
}
uint8_t BLELocalCharacteristic::permissions() const {
return _permissions;
}
int BLELocalCharacteristic::valueSize() const
{
return _valueSize;
}
const uint8_t* BLELocalCharacteristic::value() const
{
return _value;
}
int BLELocalCharacteristic::valueLength() const
{
return _valueLength;
}
uint8_t BLELocalCharacteristic::operator[] (int offset) const
{
return _value[offset];
}
int BLELocalCharacteristic::writeValue(const uint8_t value[], int length)
{
_valueLength = min(length, _valueSize);
memcpy(_value, value, _valueLength);
if (_fixedLength) {
_valueLength = _valueSize;
}
if ((_properties & BLEIndicate) && (_cccdValue & 0x0002)) {
return ATT.handleInd(valueHandle(), _value, _valueLength);
} else if ((_properties & BLENotify) && (_cccdValue & 0x0001)) {
return ATT.handleNotify(valueHandle(), _value, _valueLength);
}
if (_broadcast) {
uint16_t serviceUuid = GATT.serviceUuidForCharacteristic(this);
BLE.setAdvertisedServiceData(serviceUuid, value, _valueLength);
if (!ATT.connected() && GAP.advertising()) {
BLE.advertise();
}
}
return _valueLength;
}
int BLELocalCharacteristic::writeValue(const char* value)
{
return writeValue((uint8_t*)value, strlen(value));
}
int BLELocalCharacteristic::broadcast()
{
if (_properties & BLEBroadcast) {
_broadcast = true;
return 1;
}
return 0;
}
bool BLELocalCharacteristic::written()
{
bool written = _written;
_written = false;
return written;
}
bool BLELocalCharacteristic::subscribed()
{
return (_cccdValue != 0x0000);
}
void BLELocalCharacteristic::addDescriptor(BLEDescriptor& descriptor)
{
BLELocalDescriptor* localDescriptor = descriptor.local();
if (localDescriptor) {
localDescriptor->retain();
_descriptors.add(localDescriptor);
}
}
void BLELocalCharacteristic::setEventHandler(BLECharacteristicEvent event, BLECharacteristicEventHandler eventHandler)
{
if (event < (sizeof(_eventHandlers) / sizeof(_eventHandlers[0]))) {
_eventHandlers[event] = eventHandler;
}
}
void BLELocalCharacteristic::setHandle(uint16_t handle)
{
_handle = handle;
}
uint16_t BLELocalCharacteristic::handle() const
{
return _handle;
}
uint16_t BLELocalCharacteristic::valueHandle() const
{
return (_handle + 1);
}
unsigned int BLELocalCharacteristic::descriptorCount() const
{
return _descriptors.size();
}
BLELocalDescriptor* BLELocalCharacteristic::descriptor(unsigned int index) const
{
return _descriptors.get(index);
}
void BLELocalCharacteristic::readValue(BLEDevice device, uint16_t offset, uint8_t value[], int length)
{
if (_eventHandlers[BLERead]) {
_eventHandlers[BLERead](device, BLECharacteristic(this));
}
memcpy(value, _value + offset, length);
}
void BLELocalCharacteristic::writeValue(BLEDevice device, const uint8_t value[], int length)
{
_written = true;
writeValue(value, length);
if (_eventHandlers[BLEWritten]) {
_eventHandlers[BLEWritten](device, BLECharacteristic(this));
}
}
void BLELocalCharacteristic::writeCccdValue(BLEDevice device, uint16_t value)
{
value &= 0x0003;
if (_cccdValue != value) {
_cccdValue = value;
BLECharacteristicEvent event = (_cccdValue) ? BLESubscribed : BLEUnsubscribed;
if (_eventHandlers[event]) {
_eventHandlers[event](device, BLECharacteristic(this));
}
}
}
================================================
FILE: src/local/BLELocalCharacteristic.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_LOCAL_CHARACTERISTIC_H_
#define _BLE_LOCAL_CHARACTERISTIC_H_
#include
#include "BLECharacteristic.h"
#include "BLEDescriptor.h"
#include "BLELocalAttribute.h"
#include "utility/BLELinkedList.h"
class BLELocalDescriptor;
class BLELocalCharacteristic : public BLELocalAttribute {
public:
BLELocalCharacteristic(const char* uuid, uint16_t permissions, int valueSize, bool fixedLength = false);
BLELocalCharacteristic(const char* uuid, uint16_t permissions, const char* value);
virtual ~BLELocalCharacteristic();
virtual enum BLEAttributeType type() const;
uint8_t properties() const;
uint8_t permissions() const;
int valueSize() const;
const uint8_t* value() const;
int valueLength() const;
uint8_t operator[] (int offset) const;
int writeValue(const uint8_t value[], int length);
int writeValue(const char* value);
int broadcast();
bool written();
bool subscribed();
void addDescriptor(BLEDescriptor& descriptor);
void setEventHandler(BLECharacteristicEvent event, BLECharacteristicEventHandler eventHandler);
protected:
friend class ATTClass;
friend class GATTClass;
void setHandle(uint16_t handle);
uint16_t handle() const;
uint16_t valueHandle() const;
unsigned int descriptorCount() const;
BLELocalDescriptor* descriptor(unsigned int index) const;
void readValue(BLEDevice device, uint16_t offset, uint8_t value[], int length);
void writeValue(BLEDevice device, const uint8_t value[], int length);
void writeCccdValue(BLEDevice device, uint16_t value);
private:
uint8_t _properties;
uint8_t _permissions;
int _valueSize;
uint8_t* _value;
uint16_t _valueLength;
bool _fixedLength;
uint16_t _handle;
bool _broadcast;
bool _written;
uint16_t _cccdValue;
BLELinkedList _descriptors;
BLECharacteristicEventHandler _eventHandlers[BLECharacteristicEventLast];
};
#endif
================================================
FILE: src/local/BLELocalDescriptor.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "BLELocalDescriptor.h"
BLELocalDescriptor::BLELocalDescriptor(const char* uuid, const uint8_t value[], int valueSize) :
BLELocalAttribute(uuid),
_value(value),
_valueSize(min(valueSize, 512)),
_handle(0x0000)
{
}
BLELocalDescriptor::BLELocalDescriptor(const char* uuid, const char* value) :
BLELocalDescriptor(uuid, (const uint8_t*)value, strlen(value))
{
}
BLELocalDescriptor::~BLELocalDescriptor()
{
}
enum BLEAttributeType BLELocalDescriptor::type() const
{
return BLETypeDescriptor;
}
int BLELocalDescriptor::valueSize() const
{
return _valueSize;
}
const uint8_t* BLELocalDescriptor::value() const
{
return _value;
}
uint8_t BLELocalDescriptor::operator[] (int offset) const
{
return _value[offset];
}
void BLELocalDescriptor::setHandle(uint16_t handle)
{
_handle = handle;
}
uint16_t BLELocalDescriptor::handle() const
{
return _handle;
}
================================================
FILE: src/local/BLELocalDescriptor.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_LOCAL_DESCRIPTOR_H_
#define _BLE_LOCAL_DESCRIPTOR_H_
#include
#include "BLELocalAttribute.h"
class BLELocalDescriptor : public BLELocalAttribute {
public:
BLELocalDescriptor(const char* uuid, const uint8_t value[], int valueSize);
BLELocalDescriptor(const char* uuid, const char* value);
virtual ~BLELocalDescriptor();
virtual enum BLEAttributeType type() const;
int valueSize() const;
const uint8_t* value() const;
uint8_t operator[] (int offset) const;
protected:
friend class GATTClass;
void setHandle(uint16_t handle);
uint16_t handle() const;
private:
const uint8_t* _value;
int _valueSize;
uint16_t _handle;
};
#endif
================================================
FILE: src/local/BLELocalDevice.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "utility/ATT.h"
#include "utility/HCI.h"
#include "utility/GAP.h"
#include "utility/GATT.h"
#include "utility/L2CAPSignaling.h"
#include "BLELocalDevice.h"
#ifdef __ZEPHYR__
#undef ARDUINO_PORTENTA_H7_M7
#undef ARDUINO_OPTA
#undef ARDUINO_GIGA
#undef ARDUINO_NICLA_VISION
#undef ARDUINO_PORTENTA_C33
#undef ARDUINO_UNO_Q
#endif
#if defined(ARDUINO_PORTENTA_C33)
#include
#endif
#if defined(PORTENTA_H7_PINS) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_OPTA)
#ifndef BT_REG_ON
#define BT_REG_ON PJ_12
#endif
#elif defined(ARDUINO_NICLA_VISION)
#ifndef BT_REG_ON
#define BT_REG_ON PF_14
#endif
#elif defined(ARDUINO_GIGA)
#ifndef BT_REG_ON
#define BT_REG_ON PA_10
#endif
#endif
BLELocalDevice::BLELocalDevice()
{
_advertisingData.setFlags(BLEFlagsGeneralDiscoverable | BLEFlagsBREDRNotSupported);
}
BLELocalDevice::~BLELocalDevice()
{
}
int BLELocalDevice::begin()
{
#if defined(PORTENTA_H7_PINS) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)
// BT_REG_ON -> HIGH
pinMode(BT_REG_ON, OUTPUT);
digitalWrite(BT_REG_ON, LOW);
delay(500);
digitalWrite(BT_REG_ON, HIGH);
delay(500);
#elif defined(ARDUINO_PORTENTA_C33)
Serial5.begin(921600);
CEspChipManager::getInstance().initialize();
auto _start = millis();
while (millis() - _start < 500) {
if (Serial5.available()) {
Serial5.read();
}
}
//pinMode(94, OUTPUT);
//digitalWrite(94, LOW);
#endif
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
// set SS HIGH
digitalWrite(SPIWIFI_SS, HIGH);
// set RTS HIGH
pinMode(NINA_RTS, OUTPUT);
digitalWrite(NINA_RTS, HIGH);
// set CTS as input
pinMode(NINA_CTS, INPUT);
#endif
if (!HCI.begin()) {
end();
return 0;
}
delay(100);
if (HCI.reset() != 0) {
end();
#if defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(TARGET_NANO_RP2040_CONNECT)
Serial.println("The initialization of the Bluetooth® Low Energy module failed.");
Serial.println("Please ensure your NINA firmware is version 3.0.0 or higher.");
#endif
return 0;
}
uint8_t hciVer;
uint16_t hciRev;
uint8_t lmpVer;
uint16_t manufacturer;
uint16_t lmpSubVer;
if (HCI.readLocalVersion(hciVer, hciRev, lmpVer, manufacturer, lmpSubVer) != 0) {
end();
return 0;
}
if (HCI.setEventMask(0x3FFFFFFFFFFFFFFF) != 0) {
end();
return 0;
}
if (HCI.setLeEventMask(0x00000000000003FF) != 0) {
end();
return 0;
}
uint16_t pktLen;
uint8_t maxPkt;
if (HCI.readLeBufferSize(pktLen, maxPkt) != 0) {
end();
return 0;
}
/// The HCI should allow automatic address resolution.
// // If we have callbacks to remember bonded devices:
// if(HCI._getIRKs!=0){
// uint8_t nIRKs = 0;
// uint8_t** BADDR_Type = new uint8_t*;
// uint8_t*** BADDRs = new uint8_t**;
// uint8_t*** IRKs = new uint8_t**;
// uint8_t* memcheck;
// if(!HCI._getIRKs(&nIRKs, BADDR_Type, BADDRs, IRKs)){
// Serial.println("error");
// }
// for(int i=0; irelease() == 0) {
delete c;
}
}
clear();
}
enum BLEAttributeType BLELocalService::type() const
{
return BLETypeService;
}
void BLELocalService::addCharacteristic(BLECharacteristic& characteristic)
{
BLELocalCharacteristic* localCharacteristic = characteristic.local();
if (localCharacteristic) {
addCharacteristic(localCharacteristic);
}
}
void BLELocalService::setHandles(uint16_t start, uint16_t end)
{
_startHandle = start;
_endHandle = end;
}
uint16_t BLELocalService::startHandle() const
{
return _startHandle;
}
uint16_t BLELocalService::endHandle() const
{
return _endHandle;
}
unsigned int BLELocalService::characteristicCount() const
{
return _characteristics.size();
}
BLELocalCharacteristic* BLELocalService::characteristic(unsigned int index) const
{
return _characteristics.get(index);
}
void BLELocalService::addCharacteristic(BLELocalCharacteristic* characteristic)
{
characteristic->retain();
_characteristics.add(characteristic);
}
================================================
FILE: src/local/BLELocalService.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_LOCAL_SERVICE_H_
#define _BLE_LOCAL_SERVICE_H_
#include "BLECharacteristic.h"
#include "BLELocalAttribute.h"
#include "utility/BLELinkedList.h"
class BLELocalCharacteristic;
class BLELocalService : public BLELocalAttribute {
public:
BLELocalService(const char* uuid);
virtual ~BLELocalService();
virtual enum BLEAttributeType type() const;
void addCharacteristic(BLECharacteristic& characteristic);
void clear();
protected:
friend class ATTClass;
friend class GATTClass;
void setHandles(uint16_t start, uint16_t end);
uint16_t startHandle() const;
uint16_t endHandle() const;
unsigned int characteristicCount() const;
BLELocalCharacteristic* characteristic(unsigned int index) const;
void addCharacteristic(BLELocalCharacteristic* characteristic);
private:
uint16_t _startHandle;
uint16_t _endHandle;
BLELinkedList _characteristics;
};
#endif
================================================
FILE: src/remote/BLERemoteAttribute.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "utility/BLEUuid.h"
#include "BLERemoteAttribute.h"
BLERemoteAttribute::BLERemoteAttribute(const uint8_t uuid[], uint8_t uuidLen) :
_uuid(BLEUuid::uuidToString(uuid, uuidLen)),
_refCount(0)
{
}
BLERemoteAttribute::~BLERemoteAttribute()
{
}
const char* BLERemoteAttribute::uuid() const
{
return _uuid.c_str();
}
int BLERemoteAttribute::retain()
{
_refCount++;
return _refCount;
}
int BLERemoteAttribute::release()
{
_refCount--;
return _refCount;
}
================================================
FILE: src/remote/BLERemoteAttribute.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_REMOTE_ATTRIBUTE_H_
#define _BLE_REMOTE_ATTRIBUTE_H_
#include
class BLERemoteAttribute
{
public:
BLERemoteAttribute(const uint8_t uuid[], uint8_t uuidLen);
virtual ~BLERemoteAttribute();
const char* uuid() const;
int retain();
int release();
private:
String _uuid;
int _refCount;
};
#endif
================================================
FILE: src/remote/BLERemoteCharacteristic.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLEProperty.h"
#include "utility/ATT.h"
#include "BLERemoteCharacteristic.h"
BLERemoteCharacteristic::BLERemoteCharacteristic(const uint8_t uuid[], uint8_t uuidLen, uint16_t connectionHandle,
uint16_t startHandle, uint16_t permissions, uint16_t valueHandle) :
BLERemoteAttribute(uuid, uuidLen),
_connectionHandle(connectionHandle),
_startHandle(startHandle),
_properties((uint8_t)(permissions & 0x00FF)),
_permissions((uint8_t)((permissions & 0xFF00)>>8)),
_valueHandle(valueHandle),
_value(NULL),
_valueLength(0),
_valueUpdated(false),
_updatedValueRead(true),
_valueUpdatedEventHandler(NULL)
{
}
BLERemoteCharacteristic::~BLERemoteCharacteristic()
{
for (unsigned int i = 0; i < descriptorCount(); i++) {
BLERemoteDescriptor* d = descriptor(i);
if (d->release() == 0) {
delete d;
}
}
_descriptors.clear();
if (_value) {
free(_value);
_value = NULL;
}
}
uint16_t BLERemoteCharacteristic::startHandle() const
{
return _startHandle;
}
uint8_t BLERemoteCharacteristic::properties() const
{
return _properties;
}
const uint8_t* BLERemoteCharacteristic::value() const
{
return _value;
}
int BLERemoteCharacteristic::valueLength() const
{
return _valueLength;
}
uint8_t BLERemoteCharacteristic::operator[] (int offset) const
{
if (_value) {
return _value[offset];
}
return 0;
}
int BLERemoteCharacteristic::writeValue(const uint8_t value[], int length, bool withResponse)
{
if (!ATT.connected(_connectionHandle)) {
return false;
}
uint16_t maxLength = ATT.mtu(_connectionHandle) - 3;
if (length > (int)maxLength) {
// cap to MTU max length
length = maxLength;
}
_value = (uint8_t*)realloc(_value, length);
if (_value == NULL) {
// realloc failed
return 0;
}
if ((_properties & BLEWrite) && withResponse) {
uint8_t resp[4];
int respLength = ATT.writeReq(_connectionHandle, _valueHandle, value, length, resp);
if (!respLength) {
return 0;
}
if (resp[0] == 0x01) {
// error
return 0;
}
memcpy(_value, value, length);
_valueLength = length;
return 1;
} else if (_properties & BLEWriteWithoutResponse) {
ATT.writeCmd(_connectionHandle, _valueHandle, value, length);
memcpy(_value, value, length);
_valueLength = length;
return 1;
}
return 0;
}
int BLERemoteCharacteristic::writeValue(const char* value, bool withResponse)
{
return writeValue((uint8_t*)value, strlen(value), withResponse);
}
bool BLERemoteCharacteristic::valueUpdated()
{
ATT.connected(_connectionHandle); // to force a poll
bool result = _valueUpdated;
_valueUpdated = false;
return result;
}
bool BLERemoteCharacteristic::updatedValueRead()
{
bool result = _updatedValueRead;
_updatedValueRead = true;
return result;
}
bool BLERemoteCharacteristic::read()
{
if (!ATT.connected(_connectionHandle)) {
return false;
}
uint8_t resp[256];
int respLength = ATT.readReq(_connectionHandle, _valueHandle, resp);
if (!respLength) {
_valueLength = 0;
return false;
}
if (resp[0] == 0x01) {
// error
_valueLength = 0;
return false;
}
_valueLength = respLength - 1;
_value = (uint8_t*)realloc(_value, _valueLength);
if (_value == NULL) {
_valueLength = 0;
return false;
}
memcpy(_value, &resp[1], _valueLength);
return true;
}
bool BLERemoteCharacteristic::writeCccd(uint16_t value)
{
int numDescriptors = descriptorCount();
for (int i = 0; i < numDescriptors; i++) {
BLERemoteDescriptor* d = descriptor(i);
if (strcmp(d->uuid(), "2902") == 0) {
return d->writeValue((uint8_t*)&value, sizeof(value));
}
}
if (_properties & (BLENotify | BLEIndicate)) {
// no CCCD descriptor found, fallback to _valueHandle + 1
BLERemoteDescriptor cccd(NULL, 0, _connectionHandle, _valueHandle + 1);
return cccd.writeValue((uint8_t*)&value, sizeof(value));
}
return false;
}
uint16_t BLERemoteCharacteristic::valueHandle() const
{
return _valueHandle;
}
unsigned int BLERemoteCharacteristic::descriptorCount() const
{
return _descriptors.size();
}
BLERemoteDescriptor* BLERemoteCharacteristic::descriptor(unsigned int index) const
{
return _descriptors.get(index);
}
void BLERemoteCharacteristic::setEventHandler(BLECharacteristicEvent event, BLECharacteristicEventHandler eventHandler)
{
if (event == BLEUpdated) {
_valueUpdatedEventHandler = eventHandler;
}
}
void BLERemoteCharacteristic::addDescriptor(BLERemoteDescriptor* descriptor)
{
descriptor->retain();
_descriptors.add(descriptor);
}
void BLERemoteCharacteristic::writeValue(BLEDevice device, const uint8_t value[], int length)
{
_valueLength = length;
_value = (uint8_t*)realloc(_value, _valueLength);
if (_value == NULL) {
_valueLength = 0;
return;
}
_valueUpdated = true;
_updatedValueRead = false;
memcpy(_value, value, _valueLength);
if (_valueUpdatedEventHandler) {
_valueUpdatedEventHandler(device, BLECharacteristic(this));
}
}
================================================
FILE: src/remote/BLERemoteCharacteristic.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_REMOTE_CHARACTERISTIC_H_
#define _BLE_REMOTE_CHARACTERISTIC_H_
#include "BLECharacteristic.h"
#include "BLERemoteAttribute.h"
#include "BLERemoteDescriptor.h"
#include "utility/BLELinkedList.h"
class BLERemoteCharacteristic : public BLERemoteAttribute {
public:
BLERemoteCharacteristic(const uint8_t uuid[], uint8_t uuidLen, uint16_t connectionHandle, uint16_t startHandle, uint16_t permissions, uint16_t valueHandle);
virtual ~BLERemoteCharacteristic();
uint8_t properties() const;
uint8_t permissions() const;
const uint8_t* value() const;
int valueLength() const;
uint8_t operator[] (int offset) const;
int writeValue(const uint8_t value[], int length, bool withResponse = true);
int writeValue(const char* value, bool withResponse = true);
bool valueUpdated();
bool updatedValueRead();
bool read();
bool writeCccd(uint16_t value);
unsigned int descriptorCount() const;
BLERemoteDescriptor* descriptor(unsigned int index) const;
void setEventHandler(BLECharacteristicEvent event, BLECharacteristicEventHandler eventHandler);
protected:
friend class ATTClass;
uint16_t startHandle() const;
uint16_t valueHandle() const;
void addDescriptor(BLERemoteDescriptor* descriptor);
void writeValue(BLEDevice device, const uint8_t value[], int length);
private:
uint16_t _connectionHandle;
uint16_t _startHandle;
uint8_t _properties;
uint8_t _permissions;
uint16_t _valueHandle;
uint8_t* _value;
int _valueLength;
bool _valueUpdated;
bool _updatedValueRead;
BLELinkedList _descriptors;
BLECharacteristicEventHandler _valueUpdatedEventHandler;
};
#endif
================================================
FILE: src/remote/BLERemoteDescriptor.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "utility/ATT.h"
#include "BLERemoteDescriptor.h"
BLERemoteDescriptor::BLERemoteDescriptor(const uint8_t uuid[], uint8_t uuidLen, uint16_t connectionHandle, uint16_t handle) :
BLERemoteAttribute(uuid, uuidLen),
_connectionHandle(connectionHandle),
_handle(handle),
_value(NULL),
_valueLength(0)
{
}
BLERemoteDescriptor::~BLERemoteDescriptor()
{
if (_value) {
free(_value);
_value = NULL;
}
}
const uint8_t* BLERemoteDescriptor::value() const
{
return _value;
}
int BLERemoteDescriptor::valueLength() const
{
return _valueLength;
}
uint8_t BLERemoteDescriptor::operator[] (int offset) const
{
if (_value) {
return _value[offset];
}
return 0;
}
int BLERemoteDescriptor::writeValue(const uint8_t value[], int length)
{
if (!ATT.connected(_connectionHandle)) {
return false;
}
uint16_t maxLength = ATT.mtu(_connectionHandle) - 3;
if (length > (int)maxLength) {
// cap to MTU max length
length = maxLength;
}
_value = (uint8_t*)realloc(_value, length);
if (_value == NULL) {
// realloc failed
return 0;
}
uint8_t resp[4];
int respLength = ATT.writeReq(_connectionHandle, _handle, value, length, resp);
if (!respLength) {
return 0;
}
if (resp[0] == 0x01) {
// error
return 0;
}
memcpy(_value, value, length);
_valueLength = length;
return 1;
}
bool BLERemoteDescriptor::read()
{
if (!ATT.connected(_connectionHandle)) {
return false;
}
uint8_t resp[256];
int respLength = ATT.readReq(_connectionHandle, _handle, resp);
if (!respLength) {
_valueLength = 0;
return false;
}
if (resp[0] == 0x01) {
// error
_valueLength = 0;
return false;
}
_valueLength = respLength - 1;
_value = (uint8_t*)realloc(_value, _valueLength);
if (_value == NULL) {
_valueLength = 0;
return false;
}
memcpy(_value, &resp[1], _valueLength);
return true;
}
uint16_t BLERemoteDescriptor::handle() const
{
return _handle;
}
================================================
FILE: src/remote/BLERemoteDescriptor.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_REMOTE_DESCRIPTOR_H_
#define _BLE_REMOTE_DESCRIPTOR_H_
#include "BLERemoteAttribute.h"
class BLERemoteDescriptor : public BLERemoteAttribute {
public:
BLERemoteDescriptor(const uint8_t uuid[], uint8_t uuidLen, uint16_t connectionHandle, uint16_t handle);
virtual ~BLERemoteDescriptor();
const uint8_t* value() const;
int valueLength() const;
uint8_t operator[] (int offset) const;
int writeValue(const uint8_t value[], int length);
bool read();
protected:
friend class ATTClass;
uint16_t handle() const;
private:
uint16_t _connectionHandle;
uint16_t _handle;
uint8_t* _value;
int _valueLength;
};
#endif
================================================
FILE: src/remote/BLERemoteDevice.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLERemoteDevice.h"
BLERemoteDevice::BLERemoteDevice()
{
}
BLERemoteDevice::~BLERemoteDevice()
{
clearServices();
}
void BLERemoteDevice::addService(BLERemoteService* service)
{
service->retain();
_services.add(service);
}
unsigned int BLERemoteDevice::serviceCount() const
{
return _services.size();
}
BLERemoteService* BLERemoteDevice::service(unsigned int index) const
{
return _services.get(index);
}
void BLERemoteDevice::clearServices()
{
for (unsigned int i = 0; i < serviceCount(); i++) {
BLERemoteService* s = service(i);
if (s->release() == 0) {
delete s;
}
}
_services.clear();
}
================================================
FILE: src/remote/BLERemoteDevice.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_REMOTE_DEVICE_H_
#define _BLE_REMOTE_DEVICE_H_
#include "utility/BLELinkedList.h"
#include "BLERemoteService.h"
class BLERemoteDevice /*: public BLEDevice*/ {
public:
BLERemoteDevice();
virtual ~BLERemoteDevice();
void addService(BLERemoteService* service);
unsigned int serviceCount() const;
BLERemoteService* service(unsigned int index) const;
void clearServices();
private:
BLELinkedList _services;
};
#endif
================================================
FILE: src/remote/BLERemoteService.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLERemoteService.h"
BLERemoteService::BLERemoteService(const uint8_t uuid[], uint8_t uuidLen, uint16_t startHandle, uint16_t endHandle) :
BLERemoteAttribute(uuid, uuidLen),
_startHandle(startHandle),
_endHandle(endHandle)
{
}
BLERemoteService::~BLERemoteService()
{
for (unsigned int i = 0; i < characteristicCount(); i++) {
BLERemoteCharacteristic* c = characteristic(i);
if (c->release() == 0) {
delete c;
}
}
_characteristics.clear();
}
uint16_t BLERemoteService::startHandle() const
{
return _startHandle;
}
uint16_t BLERemoteService::endHandle() const
{
return _endHandle;
}
unsigned int BLERemoteService::characteristicCount() const
{
return _characteristics.size();
}
BLERemoteCharacteristic* BLERemoteService::characteristic(unsigned int index) const
{
return _characteristics.get(index);
}
void BLERemoteService::addCharacteristic(BLERemoteCharacteristic* characteristic)
{
characteristic-> retain();
_characteristics.add(characteristic);
}
================================================
FILE: src/remote/BLERemoteService.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_REMOTE_SERVICE_H_
#define _BLE_REMOTE_SERVICE_H_
#include "BLERemoteAttribute.h"
#include "BLERemoteCharacteristic.h"
#include "utility/BLELinkedList.h"
class BLERemoteService : public BLERemoteAttribute {
public:
BLERemoteService(const uint8_t uuid[], uint8_t uuidLen, uint16_t startHandle, uint16_t endHandle);
virtual ~BLERemoteService();
unsigned int characteristicCount() const;
BLERemoteCharacteristic* characteristic(unsigned int index) const;
protected:
friend class ATTClass;
uint16_t startHandle() const;
uint16_t endHandle() const;
void addCharacteristic(BLERemoteCharacteristic* characteristic);
private:
uint16_t _startHandle;
uint16_t _endHandle;
String _uuid;
BLELinkedList _characteristics;
};
#endif
================================================
FILE: src/utility/ATT.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "HCI.h"
#include "GATT.h"
#include "local/BLELocalAttribute.h"
#include "local/BLELocalCharacteristic.h"
#include "local/BLELocalDescriptor.h"
#include "local/BLELocalService.h"
#include "remote/BLERemoteDevice.h"
#include "remote/BLERemoteService.h"
#include "BLEProperty.h"
#include "ATT.h"
extern "C" int strcasecmp(char const *a, char const *b);
#define ATT_OP_ERROR 0x01
#define ATT_OP_MTU_REQ 0x02
#define ATT_OP_MTU_RESP 0x03
#define ATT_OP_FIND_INFO_REQ 0x04
#define ATT_OP_FIND_INFO_RESP 0x05
#define ATT_OP_FIND_BY_TYPE_REQ 0x06
#define ATT_OP_FIND_BY_TYPE_RESP 0x07
#define ATT_OP_READ_BY_TYPE_REQ 0x08
#define ATT_OP_READ_BY_TYPE_RESP 0x09
#define ATT_OP_READ_REQ 0x0a
#define ATT_OP_READ_RESP 0x0b
#define ATT_OP_READ_BLOB_REQ 0x0c
#define ATT_OP_READ_BLOB_RESP 0x0d
#define ATT_OP_READ_MULTI_REQ 0x0e
#define ATT_OP_READ_MULTI_RESP 0x0f
#define ATT_OP_READ_BY_GROUP_REQ 0x10
#define ATT_OP_READ_BY_GROUP_RESP 0x11
#define ATT_OP_WRITE_REQ 0x12
#define ATT_OP_WRITE_RESP 0x13
#define ATT_OP_WRITE_CMD 0x52
#define ATT_OP_PREP_WRITE_REQ 0x16
#define ATT_OP_PREP_WRITE_RESP 0x17
#define ATT_OP_EXEC_WRITE_REQ 0x18
#define ATT_OP_EXEC_WRITE_RESP 0x19
#define ATT_OP_HANDLE_NOTIFY 0x1b
#define ATT_OP_HANDLE_IND 0x1d
#define ATT_OP_HANDLE_CNF 0x1e
#define ATT_OP_SIGNED_WRITE_CMD 0xd2
#define ATT_ECODE_INVALID_HANDLE 0x01
#define ATT_ECODE_READ_NOT_PERM 0x02
#define ATT_ECODE_WRITE_NOT_PERM 0x03
#define ATT_ECODE_INVALID_PDU 0x04
#define ATT_ECODE_AUTHENTICATION 0x05
#define ATT_ECODE_REQ_NOT_SUPP 0x06
#define ATT_ECODE_INVALID_OFFSET 0x07
#define ATT_ECODE_AUTHORIZATION 0x08
#define ATT_ECODE_PREP_QUEUE_FULL 0x09
#define ATT_ECODE_ATTR_NOT_FOUND 0x0a
#define ATT_ECODE_ATTR_NOT_LONG 0x0b
#define ATT_ECODE_INSUFF_ENCR_KEY_SIZE 0x0c
#define ATT_ECODE_INVAL_ATTR_VALUE_LEN 0x0d
#define ATT_ECODE_UNLIKELY 0x0e
#define ATT_ECODE_INSUFF_ENC 0x0f
#define ATT_ECODE_UNSUPP_GRP_TYPE 0x10
#define ATT_ECODE_INSUFF_RESOURCES 0x11
// #define _BLE_TRACE_
ATTClass::ATTClass() :
_maxMtu(23),
_timeout(5000),
_longWriteHandle(0x0000),
_longWriteValue(NULL),
_longWriteValueLength(0)
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
_peers[i].connectionHandle = 0xffff;
_peers[i].role = 0x00;
_peers[i].addressType = 0x00;
memset(_peers[i].address, 0x00, sizeof(_peers[i].address));
_peers[i].mtu = 23;
_peers[i].device = NULL;
_peers[i].encryption = 0x0;
}
memset(_eventHandlers, 0x00, sizeof(_eventHandlers));
}
ATTClass::~ATTClass()
{
if (_longWriteValue) {
free(_longWriteValue);
}
}
bool ATTClass::connect(uint8_t peerBdaddrType, uint8_t peerBdaddr[6])
{
if (HCI.leCreateConn(0x0060, 0x0030, 0x00, peerBdaddrType, peerBdaddr, 0x00,
0x0006, 0x000c, 0x0000, 0x00c8, 0x0004, 0x0006) != 0) {
return false;
}
bool isConnected = false;
for (unsigned long start = millis(); (millis() - start) < _timeout;) {
HCI.poll();
isConnected = connected(peerBdaddrType, peerBdaddr);
if (isConnected) {
break;
}
}
if (!isConnected) {
HCI.leCancelConn();
}
return isConnected;
}
bool ATTClass::disconnect(uint8_t peerBdaddrType, uint8_t peerBdaddr[6])
{
uint16_t connHandle = connectionHandle(peerBdaddrType, peerBdaddr);
if (connHandle == 0xffff) {
return false;
}
HCI.disconnect(connHandle);
for (unsigned long start = millis(); (millis() - start) < _timeout;) {
HCI.poll();
if (!connected(connHandle)) {
return true;
}
}
return false;
}
bool ATTClass::discoverAttributes(uint8_t peerBdaddrType, uint8_t peerBdaddr[6], const char* serviceUuidFilter)
{
uint16_t connHandle = connectionHandle(peerBdaddrType, peerBdaddr);
if (connHandle == 0xffff) {
return false;
}
// send MTU request
if (!exchangeMtu(connHandle)) {
return false;
}
// find the device entry for the peeer
BLERemoteDevice* device = NULL;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connHandle) {
if (_peers[i].device == NULL) {
_peers[i].device = new BLERemoteDevice();
}
device = _peers[i].device;
break;
}
}
if (device == NULL) {
return false;
}
if (serviceUuidFilter == NULL) {
// clear existing services
device->clearServices();
} else {
int serviceCount = device->serviceCount();
for (int i = 0; i < serviceCount; i++) {
BLERemoteService* service = device->service(i);
if (strcasecmp(service->uuid(), serviceUuidFilter) == 0) {
// found an existing service with same UUID
return true;
}
}
}
// discover services
if (!discoverServices(connHandle, device, serviceUuidFilter)) {
return false;
}
// discover characteristics
if (!discoverCharacteristics(connHandle, device)) {
return false;
}
// discover descriptors
if (!discoverDescriptors(connHandle, device)) {
return false;
}
return true;
}
void ATTClass::setMaxMtu(uint16_t maxMtu)
{
_maxMtu = maxMtu;
}
void ATTClass::setTimeout(unsigned long timeout)
{
_timeout = timeout;
}
void ATTClass::addConnection(uint16_t handle, uint8_t role, uint8_t peerBdaddrType,
uint8_t peerBdaddr[6], uint16_t /*interval*/,
uint16_t /*latency*/, uint16_t /*supervisionTimeout*/,
uint8_t /*masterClockAccuracy*/)
{
int peerIndex = -1;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == 0xffff) {
peerIndex = i;
break;
}
}
if (peerIndex == -1) {
// bail, no space
return;
}
_peers[peerIndex].connectionHandle = handle;
_peers[peerIndex].role = role;
_peers[peerIndex].mtu = 23;
_peers[peerIndex].addressType = peerBdaddrType;
memcpy(_peers[peerIndex].address, peerBdaddr, sizeof(_peers[peerIndex].address));
uint8_t BDADDr[6];
for(int i=0; i<6; i++) BDADDr[5-i] = peerBdaddr[i];
if(HCI.tryResolveAddress(BDADDr,_peers[peerIndex].resolvedAddress)){
#ifdef _BLE_TRACE_
Serial.println("Found match.");
#endif
}else{
#ifdef _BLE_TRACE_
Serial.println("No matching MAC");
#endif
memset(&_peers[peerIndex].resolvedAddress, 0, 6);
}
if (_eventHandlers[BLEConnected]) {
_eventHandlers[BLEConnected](BLEDevice(peerBdaddrType, peerBdaddr));
}
}
void ATTClass::handleData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
uint8_t opcode = data[0];
dlen--;
data++;
uint16_t mtu = this->mtu(connectionHandle);
#ifdef _BLE_TRACE_
Serial.print("data opcode: 0x");
Serial.println(opcode, HEX);
#endif
switch (opcode) {
case ATT_OP_ERROR:
#ifdef _BLE_TRACE_
Serial.println("[Info] data error");
// Serial.print("Error: ");
// btct.printBytes(data, dlen);
#endif
error(connectionHandle, dlen, data);
break;
case ATT_OP_MTU_REQ:
#ifdef _BLE_TRACE_
Serial.println("MTU");
#endif
mtuReq(connectionHandle, dlen, data);
break;
case ATT_OP_MTU_RESP:
mtuResp(connectionHandle, dlen, data);
break;
case ATT_OP_FIND_INFO_REQ:
#ifdef _BLE_TRACE_
Serial.println("Find info");
#endif
findInfoReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_FIND_INFO_RESP:
findInfoResp(connectionHandle, dlen, data);
break;
case ATT_OP_FIND_BY_TYPE_REQ:
findByTypeReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_READ_BY_TYPE_REQ:
#ifdef _BLE_TRACE_
Serial.println("By type");
#endif
readByTypeReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_READ_BY_TYPE_RESP:
readByTypeResp(connectionHandle, dlen, data);
break;
case ATT_OP_READ_BY_GROUP_REQ:
readByGroupReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_READ_BY_GROUP_RESP:
readByGroupResp(connectionHandle, dlen, data);
break;
case ATT_OP_READ_REQ:
case ATT_OP_READ_BLOB_REQ:
readOrReadBlobReq(connectionHandle, mtu, opcode, dlen, data);
break;
case ATT_OP_READ_RESP:
readResp(connectionHandle, dlen, data);
break;
case ATT_OP_WRITE_REQ:
case ATT_OP_WRITE_CMD:
#ifdef _BLE_TRACE_
Serial.println("Write req");
#endif
writeReqOrCmd(connectionHandle, mtu, opcode, dlen, data);
break;
case ATT_OP_WRITE_RESP:
writeResp(connectionHandle, dlen, data);
break;
case ATT_OP_PREP_WRITE_REQ:
prepWriteReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_EXEC_WRITE_REQ:
execWriteReq(connectionHandle, mtu, dlen, data);
break;
case ATT_OP_HANDLE_NOTIFY:
case ATT_OP_HANDLE_IND:
handleNotifyOrInd(connectionHandle, opcode, dlen, data);
break;
case ATT_OP_HANDLE_CNF:
handleCnf(connectionHandle, dlen, data);
break;
case ATT_OP_READ_MULTI_REQ:
case ATT_OP_SIGNED_WRITE_CMD:
default:
#ifdef _BLE_TRACE_
Serial.println("[Info] Unhandled dara");
#endif
sendError(connectionHandle, opcode, 0x00, ATT_ECODE_REQ_NOT_SUPP);
break;
}
}
void ATTClass::removeConnection(uint16_t handle, uint8_t /*reason*/)
{
int peerIndex = -1;
int peerCount = 0;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == handle) {
peerIndex = i;
}
if (_peers[i].connectionHandle != 0xffff) {
peerCount++;
}
}
if (peerIndex == -1) {
// bail not found
return;
}
BLEDevice bleDevice(_peers[peerIndex].addressType, _peers[peerIndex].address);
if (peerCount == 1) {
// clear CCCD values on disconnect
for (uint16_t i = 0; i < GATT.attributeCount(); i++) {
BLELocalAttribute* attribute = GATT.attribute(i);
if (attribute->type() == BLETypeCharacteristic) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
characteristic->writeCccdValue(bleDevice, 0x0000);
}
}
_longWriteHandle = 0x0000;
_longWriteValueLength = 0;
}
if (_eventHandlers[BLEDisconnected]) {
_eventHandlers[BLEDisconnected](bleDevice);
}
_peers[peerIndex].connectionHandle = 0xffff;
_peers[peerIndex].role = 0x00;
_peers[peerIndex].addressType = 0x00;
memset(_peers[peerIndex].address, 0x00, sizeof(_peers[peerIndex].address));
_peers[peerIndex].mtu = 23;
_peers[peerIndex].encryption = PEER_ENCRYPTION::NO_ENCRYPTION;
_peers[peerIndex].IOCap[0] = 0;
_peers[peerIndex].IOCap[1] = 0;
_peers[peerIndex].IOCap[2] = 0;
if (_peers[peerIndex].device) {
delete _peers[peerIndex].device;
}
_peers[peerIndex].device = NULL;
}
uint16_t ATTClass::connectionHandle(uint8_t addressType, const uint8_t address[6]) const
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].addressType == addressType && memcmp(_peers[i].address, address, 6) == 0) {
return _peers[i].connectionHandle;
}
}
return 0xffff;
}
BLERemoteDevice* ATTClass::device(uint8_t addressType, const uint8_t address[6]) const
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].addressType == addressType && memcmp(_peers[i].address, address, 6) == 0) {
return _peers[i].device;
}
}
return NULL;
}
bool ATTClass::connected() const
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle != 0xffff) {
return true;
}
}
return false;
}
bool ATTClass::connected(uint8_t addressType, const uint8_t address[6]) const
{
return (connectionHandle(addressType, address) != 0xffff);
}
bool ATTClass::connected(uint16_t handle) const
{
HCI.poll();
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == handle) {
return true;
}
}
return false;
}
/*
* Return true if any of the known devices is paired (peer encrypted)
* Does not check if the paired device is also connected
*/
bool ATTClass::paired() const
{
for(int i=0; i 0){
return true;
}
}
return false;
}
/*
* Return true if the specified device is paired (peer encrypted)
*/
bool ATTClass::paired(uint16_t handle) const
{
for(int i=0; i 0;
}
return false; // unknown handle
}
uint16_t ATTClass::mtu(uint16_t handle) const
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == handle) {
return _peers[i].mtu;
}
}
return 23;
}
bool ATTClass::disconnect()
{
int numDisconnects = 0;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == 0xffff) {
continue;
}
if (HCI.disconnect(_peers[i].connectionHandle) != 0) {
continue;
}
numDisconnects++;
BLEDevice bleDevice(_peers[i].addressType, _peers[i].address);
// clear CCCD values on disconnect
for (uint16_t att = 0; att < GATT.attributeCount(); att++) {
BLELocalAttribute* attribute = GATT.attribute(att);
if (attribute->type() == BLETypeCharacteristic) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
characteristic->writeCccdValue(bleDevice, 0x0000);
}
}
_longWriteHandle = 0x0000;
_longWriteValueLength = 0;
_peers[i].connectionHandle = 0xffff;
_peers[i].role = 0x00;
_peers[i].addressType = 0x00;
memset(_peers[i].address, 0x00, sizeof(_peers[i].address));
memset(_peers[i].resolvedAddress, 0x00, sizeof(_peers[i].resolvedAddress));
_peers[i].mtu = 23;
if (_peers[i].device) {
delete _peers[i].device;
}
_peers[i].device = NULL;
}
return (numDisconnects > 0);
}
BLEDevice ATTClass::central()
{
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == 0xffff || _peers[i].role != 0x01) {
continue;
}
return BLEDevice(_peers[i].addressType, _peers[i].address);
}
return BLEDevice();
}
int ATTClass::handleNotify(uint16_t handle, const uint8_t* value, int length)
{
int numNotifications = 0;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == 0xffff) {
continue;
}
uint8_t notification[_peers[i].mtu];
uint16_t notificationLength = 0;
notification[0] = ATT_OP_HANDLE_NOTIFY;
notificationLength++;
memcpy(¬ification[1], &handle, sizeof(handle));
notificationLength += sizeof(handle);
length = min((uint16_t)(_peers[i].mtu - notificationLength), (uint16_t)length);
memcpy(¬ification[notificationLength], value, length);
notificationLength += length;
/// TODO: Set encryption requirement on notify.
HCI.sendAclPkt(_peers[i].connectionHandle, ATT_CID, notificationLength, notification);
numNotifications++;
}
return (numNotifications > 0) ? length : 0;
}
int ATTClass::handleInd(uint16_t handle, const uint8_t* value, int length)
{
int numIndications = 0;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == 0xffff) {
continue;
}
uint8_t indication[_peers[i].mtu];
uint16_t indicationLength = 0;
indication[0] = ATT_OP_HANDLE_IND;
indicationLength++;
memcpy(&indication[1], &handle, sizeof(handle));
indicationLength += sizeof(handle);
length = min((uint16_t)(_peers[i].mtu - indicationLength), (uint16_t)length);
memcpy(&indication[indicationLength], value, length);
indicationLength += length;
_cnf = false;
HCI.sendAclPkt(_peers[i].connectionHandle, ATT_CID, indicationLength, indication);
while (!_cnf) {
HCI.poll();
if (!connected(_peers[i].addressType, _peers[i].address)) {
break;
}
}
numIndications++;
}
return (numIndications > 0) ? length : 0;
}
void ATTClass::error(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (dlen != 4) {
// drop
return;
}
struct __attribute__ ((packed)) AttError {
uint8_t opcode;
uint16_t handle;
uint8_t code;
} *attError = (AttError*)data;
if (_pendingResp.connectionHandle == connectionHandle && (_pendingResp.op - 1) == attError->opcode) {
_pendingResp.buffer[0] = ATT_OP_ERROR;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::mtuReq(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
uint16_t mtu = *(uint16_t*)data;
if (dlen != 2) {
sendError(connectionHandle, ATT_OP_MTU_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
return;
}
if (mtu > _maxMtu) {
mtu = _maxMtu;
}
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
_peers[i].mtu = mtu;
break;
}
}
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t mtu;
} mtuResp = { ATT_OP_MTU_RESP, mtu };
HCI.sendAclPkt(connectionHandle, ATT_CID, sizeof(mtuResp), &mtuResp);
}
int ATTClass::mtuReq(uint16_t connectionHandle, uint16_t mtu, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t mtu;
} mtuReq = { ATT_OP_MTU_REQ, mtu };
return sendReq(connectionHandle, &mtuReq, sizeof(mtuReq), responseBuffer);
}
void ATTClass::mtuResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
uint16_t mtu = *(uint16_t*)data;
if (dlen != 2) {
return;
}
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
_peers[i].mtu = mtu;
break;
}
}
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_MTU_RESP) {
_pendingResp.buffer[0] = ATT_OP_MTU_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::findInfoReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) FindInfoReq {
uint16_t startHandle;
uint16_t endHandle;
} *findInfoReq = (FindInfoReq*)data;
if (dlen != sizeof(FindInfoReq)) {
sendError(connectionHandle, ATT_OP_FIND_INFO_REQ, findInfoReq->startHandle, ATT_ECODE_INVALID_PDU);
return;
}
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_FIND_INFO_RESP;
response[1] = 0x00;
responseLength = 2;
for (uint16_t i = (findInfoReq->startHandle - 1); i < GATT.attributeCount() && i <= (findInfoReq->endHandle - 1); i++) {
BLELocalAttribute* attribute = GATT.attribute(i);
uint16_t handle = (i + 1);
bool isValueHandle = (attribute->type() == BLETypeCharacteristic) && (((BLELocalCharacteristic*)attribute)->valueHandle() == handle);
bool isDescriptor = attribute->type() == BLETypeDescriptor;
int uuidLen = (isValueHandle || isDescriptor) ? attribute->uuidLength() : BLE_ATTRIBUTE_TYPE_SIZE;
int infoType = (uuidLen == 2) ? 0x01 : 0x02;
if (response[1] == 0) {
response[1] = infoType;
}
if (response[1] != infoType) {
// different type
break;
}
// add the handle
memcpy(&response[responseLength], &handle, sizeof(handle));
responseLength += sizeof(handle);
if (isValueHandle || isDescriptor) {
// add the UUID
memcpy(&response[responseLength], attribute->uuidData(), uuidLen);
responseLength += uuidLen;
} else {
// add the type
uint16_t type = attribute->type();
memcpy(&response[responseLength], &type, sizeof(type));
responseLength += sizeof(type);
}
if ((responseLength + (2 + uuidLen)) > mtu) {
break;
}
}
if (responseLength == 2) {
sendError(connectionHandle, ATT_OP_FIND_INFO_REQ, findInfoReq->startHandle, ATT_ECODE_ATTR_NOT_FOUND);
} else {
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
int ATTClass::findInfoReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t startHandle;
uint16_t endHandle;
} findInfoReq = { ATT_OP_FIND_INFO_REQ, startHandle, endHandle };
return sendReq(connectionHandle, &findInfoReq, sizeof(findInfoReq), responseBuffer);
}
void ATTClass::findInfoResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (dlen < 2) {
return; // invalid, drop
}
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_FIND_INFO_RESP) {
_pendingResp.buffer[0] = ATT_OP_FIND_INFO_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::findByTypeReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) FindByTypeReq {
uint16_t startHandle;
uint16_t endHandle;
uint16_t type;
} *findByTypeReq = (FindByTypeReq*)data;
if (dlen < sizeof(FindByTypeReq)) {
sendError(connectionHandle, ATT_OP_FIND_BY_TYPE_REQ, findByTypeReq->startHandle, ATT_ECODE_INVALID_PDU);
return;
}
uint16_t valueLength = dlen - sizeof(*findByTypeReq);
uint8_t* value = &data[sizeof(*findByTypeReq)];
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_FIND_BY_TYPE_RESP;
responseLength = 1;
if (findByTypeReq->type == BLETypeService) {
for (uint16_t i = (findByTypeReq->startHandle - 1); i < GATT.attributeCount() && i <= (findByTypeReq->endHandle - 1); i++) {
BLELocalAttribute* attribute = GATT.attribute(i);
if ((attribute->type() == findByTypeReq->type) && (attribute->uuidLength() == valueLength) && memcmp(attribute->uuidData(), value, valueLength) == 0) {
BLELocalService* service = (BLELocalService*)attribute;
// add the start handle
uint16_t startHandle = service->startHandle();
memcpy(&response[responseLength], &startHandle, sizeof(startHandle));
responseLength += sizeof(startHandle);
// add the end handle
uint16_t endHandle = service->endHandle();
memcpy(&response[responseLength], &endHandle, sizeof(endHandle));
responseLength += sizeof(endHandle);
}
if ((responseLength + 4) > mtu) {
break;
}
}
}
if (responseLength == 1) {
sendError(connectionHandle, ATT_OP_FIND_BY_TYPE_REQ, findByTypeReq->startHandle, ATT_ECODE_ATTR_NOT_FOUND);
} else {
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
void ATTClass::readByGroupReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) ReadByGroupReq {
uint16_t startHandle;
uint16_t endHandle;
uint16_t uuid;
} *readByGroupReq = (ReadByGroupReq*)data;
#ifdef _BLE_TRACE_
Serial.print("readByGroupReq: start: 0x");
Serial.println(readByGroupReq->startHandle,HEX);
Serial.print("readByGroupReq: end: 0x");
Serial.println(readByGroupReq->endHandle,HEX);
Serial.print("readByGroupReq: UUID: 0x");
Serial.println(readByGroupReq->uuid,HEX);
#endif
if (dlen != sizeof(ReadByGroupReq) || (readByGroupReq->uuid != BLETypeService && readByGroupReq->uuid != 0x2801)) {
sendError(connectionHandle, ATT_OP_READ_BY_GROUP_REQ, readByGroupReq->startHandle, ATT_ECODE_UNSUPP_GRP_TYPE);
return;
}
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_READ_BY_GROUP_RESP;
response[1] = 0x00;
responseLength = 2;
#ifdef _BLE_TRACE_
Serial.print("readByGroupReq: attrcount: ");
Serial.println(GATT.attributeCount());
#endif
for (uint16_t i = (readByGroupReq->startHandle - 1); i < GATT.attributeCount() && i <= (readByGroupReq->endHandle - 1); i++) {
BLELocalAttribute* attribute = GATT.attribute(i);
if (readByGroupReq->uuid != attribute->type()) {
// not the type
continue;
}
int uuidLen = attribute->uuidLength();
int infoSize = (uuidLen == 2) ? 6 : 20;
if (response[1] == 0) {
response[1] = infoSize;
}
if (response[1] != infoSize) {
// different size
break;
}
BLELocalService* service = (BLELocalService*)attribute;
// add the start handle
uint16_t startHandle = service->startHandle();
memcpy(&response[responseLength], &startHandle, sizeof(startHandle));
responseLength += sizeof(startHandle);
// add the end handle
uint16_t endHandle = service->endHandle();
memcpy(&response[responseLength], &endHandle, sizeof(endHandle));
responseLength += sizeof(endHandle);
// add the UUID
memcpy(&response[responseLength], service->uuidData(), uuidLen);
responseLength += uuidLen;
if ((responseLength + infoSize) > mtu) {
break;
}
}
if (responseLength == 2) {
sendError(connectionHandle, ATT_OP_READ_BY_GROUP_REQ, readByGroupReq->startHandle, ATT_ECODE_ATTR_NOT_FOUND);
} else {
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
int ATTClass::readByGroupReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint16_t uuid, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t startHandle;
uint16_t endHandle;
uint16_t uuid;
} readByGroupReq = { ATT_OP_READ_BY_GROUP_REQ, startHandle, endHandle, uuid };
return sendReq(connectionHandle, &readByGroupReq, sizeof(readByGroupReq), responseBuffer);
}
void ATTClass::readByGroupResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (dlen < 2) {
return; // invalid, drop
}
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_READ_BY_GROUP_RESP) {
_pendingResp.buffer[0] = ATT_OP_READ_BY_GROUP_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::readOrReadBlobReq(uint16_t connectionHandle, uint16_t mtu, uint8_t opcode, uint8_t dlen, uint8_t data[])
{
if (opcode == ATT_OP_READ_REQ) {
if (dlen != sizeof(uint16_t)) {
sendError(connectionHandle, ATT_OP_READ_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
return;
}
} else {
if (dlen != (sizeof(uint16_t) + sizeof(uint16_t))) {
sendError(connectionHandle, ATT_OP_READ_BLOB_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
return;
}
}
/// if auth error, hold the response in a buffer.
bool holdResponse = false;
uint16_t handle;
memcpy(&handle, data, sizeof(handle));
uint16_t offset = (opcode == ATT_OP_READ_REQ) ? 0 : *(uint16_t*)&data[sizeof(handle)];
if ((uint16_t)(handle - 1) > GATT.attributeCount()) {
sendError(connectionHandle, opcode, handle, ATT_ECODE_ATTR_NOT_FOUND);
return;
}
uint8_t response[mtu];
uint16_t responseLength;
response[0] = (opcode == ATT_OP_READ_REQ) ? ATT_OP_READ_RESP : ATT_OP_READ_BLOB_RESP;
responseLength = 1;
BLELocalAttribute* attribute = GATT.attribute(handle - 1);
enum BLEAttributeType attributeType = attribute->type();
if (attributeType == BLETypeService) {
if (offset) {
sendError(connectionHandle, ATT_ECODE_ATTR_NOT_LONG, handle, ATT_ECODE_INVALID_PDU);
return;
}
BLELocalService* service = (BLELocalService*)attribute;
// add the UUID
uint8_t uuidLen = service->uuidLength();
memcpy(&response[responseLength], service->uuidData(), uuidLen);
responseLength += uuidLen;
} else if (attributeType == BLETypeCharacteristic) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
if (characteristic->handle() == handle) {
if (offset) {
sendError(connectionHandle, opcode, handle, ATT_ECODE_ATTR_NOT_LONG);
return;
}
// add the properties
response[responseLength++] = characteristic->properties();
// add the value handle
uint16_t valueHandle = characteristic->valueHandle();
memcpy(&response[responseLength], &valueHandle, sizeof(valueHandle));
responseLength += sizeof(valueHandle);
// add the UUID
uint8_t uuidLen = characteristic->uuidLength();
memcpy(&response[responseLength], characteristic->uuidData(), uuidLen);
responseLength += uuidLen;
} else {
if ((characteristic->properties() & BLERead) == 0) {
sendError(connectionHandle, opcode, handle, ATT_ECODE_READ_NOT_PERM);
return;
}
// If characteristic requires encryption send error & hold response until encrypted
if ((characteristic->permissions() & (BLEPermission::BLEEncryption >> 8)) > 0 &&
(getPeerEncryption(connectionHandle) & PEER_ENCRYPTION::ENCRYPTED_AES)==0 ) {
holdResponse = true;
sendError(connectionHandle, opcode, handle, ATT_ECODE_INSUFF_ENC);
}
uint16_t valueLength = characteristic->valueLength();
if (offset >= valueLength) {
sendError(connectionHandle, opcode, handle, ATT_ECODE_INVALID_OFFSET);
return;
}
valueLength = min(mtu - responseLength, valueLength - offset);
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
characteristic->readValue(BLEDevice(_peers[i].addressType, _peers[i].address), offset, &response[responseLength], valueLength);
responseLength += valueLength;
}
}
}
} else if (attributeType == BLETypeDescriptor) {
BLELocalDescriptor* descriptor = (BLELocalDescriptor*)attribute;
uint16_t valueLength = descriptor->valueSize();
if (offset >= valueLength) {
sendError(connectionHandle, opcode, handle, ATT_ECODE_INVALID_OFFSET);
return;
}
valueLength = min(mtu - responseLength, valueLength - offset);
memcpy(&response[responseLength], descriptor->value() + offset, valueLength);
responseLength += valueLength;
}
if(holdResponse){
memcpy(holdBuffer, response, responseLength);
holdBufferSize = responseLength;
}else{
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
void ATTClass::readResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_READ_RESP) {
_pendingResp.buffer[0] = ATT_OP_READ_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::readByTypeReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) ReadByTypeReq {
uint16_t startHandle;
uint16_t endHandle;
uint16_t uuid;
} *readByTypeReq = (ReadByTypeReq*)data;
if (dlen != sizeof(ReadByTypeReq)) {
sendError(connectionHandle, ATT_OP_READ_BY_TYPE_REQ, readByTypeReq->startHandle, ATT_ECODE_INVALID_PDU);
return;
}
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_READ_BY_TYPE_RESP;
response[1] = 0x00;
responseLength = 2;
for (uint16_t i = (readByTypeReq->startHandle - 1); i < GATT.attributeCount() && i <= (readByTypeReq->endHandle - 1); i++) {
BLELocalAttribute* attribute = GATT.attribute(i);
uint16_t handle = (i + 1);
if (attribute->type() == readByTypeReq->uuid) {
if (attribute->type() == BLETypeCharacteristic) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
if (characteristic->valueHandle() == handle) {
// value handle, skip
continue;
}
int uuidLen = attribute->uuidLength();
int typeSize = (uuidLen == 2) ? 7 : 21;
if (response[1] == 0) {
response[1] = typeSize;
}
if (response[1] != typeSize) {
// all done, wrong size
break;
}
// add the handle
memcpy(&response[responseLength], &handle, sizeof(handle));
responseLength += sizeof(handle);
// add the properties
response[responseLength++] = characteristic->properties();
// add the value handle
uint16_t valueHandle = (handle + 1);
memcpy(&response[responseLength], &valueHandle, sizeof(valueHandle));
responseLength += sizeof(valueHandle);
// add the UUID
memcpy(&response[responseLength], characteristic->uuidData(), uuidLen);
responseLength += uuidLen;
// skip the next handle, it's a value handle
i++;
if ((responseLength + typeSize) > mtu) {
break;
}
} else if (attribute->type() == 0x2902) {
BLELocalDescriptor* descriptor = (BLELocalDescriptor*)attribute;
// add the handle
memcpy(&response[responseLength], &handle, sizeof(handle));
responseLength += sizeof(handle);
// add the value
int valueSize = min((uint16_t)(mtu - responseLength), (uint16_t)descriptor->valueSize());
memcpy(&response[responseLength], descriptor->value(), valueSize);
responseLength += valueSize;
response[1] = 2 + valueSize;
break; // all done
}
} else if (attribute->type() == BLETypeCharacteristic && attribute->uuidLength() == 2 && memcmp(&readByTypeReq->uuid, attribute->uuidData(), 2) == 0) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
// add the handle
memcpy(&response[responseLength], &handle, sizeof(handle));
responseLength += sizeof(handle);
// add the value
int valueLength = min((uint16_t)(mtu - responseLength), (uint16_t)characteristic->valueLength());
memcpy(&response[responseLength], characteristic->value(), valueLength);
responseLength += valueLength;
response[1] = 2 + valueLength;
break; // all done
}
}
if (responseLength == 2) {
sendError(connectionHandle, ATT_OP_READ_BY_TYPE_REQ, readByTypeReq->startHandle, ATT_ECODE_ATTR_NOT_FOUND);
} else {
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
int ATTClass::readByTypeReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint16_t type, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t startHandle;
uint16_t endHandle;
uint16_t type;
} readByTypeReq = { ATT_OP_READ_BY_TYPE_REQ, startHandle, endHandle, type };
return sendReq(connectionHandle, &readByTypeReq, sizeof(readByTypeReq), responseBuffer);
}
void ATTClass::readByTypeResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (dlen < 1) {
return; // invalid, drop
}
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_READ_BY_TYPE_RESP) {
_pendingResp.buffer[0] = ATT_OP_READ_BY_TYPE_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::writeReqOrCmd(uint16_t connectionHandle, uint16_t mtu, uint8_t op, uint8_t dlen, uint8_t data[])
{
bool withResponse = (op == ATT_OP_WRITE_REQ);
if (dlen < sizeof(uint16_t)) {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
}
return;
}
uint16_t handle;
memcpy(&handle, data, sizeof(handle));
if ((uint16_t)(handle - 1) > GATT.attributeCount()) {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_ATTR_NOT_FOUND);
}
return;
}
uint8_t valueLength = dlen - sizeof(handle);
uint8_t* value = &data[sizeof(handle)];
BLELocalAttribute* attribute = GATT.attribute(handle - 1);
bool holdResponse = false;
if (attribute->type() == BLETypeCharacteristic) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
if (handle != characteristic->valueHandle() ||
withResponse ? ((characteristic->properties() & BLEWrite) == 0) :
((characteristic->properties() & BLEWriteWithoutResponse) == 0)) {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_WRITE_NOT_PERM);
}
return;
}
// Check permission
if((characteristic->permissions() &( BLEPermission::BLEEncryption >> 8)) > 0 &&
(getPeerEncryption(connectionHandle) & PEER_ENCRYPTION::ENCRYPTED_AES) == 0){
holdResponse = true;
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_INSUFF_ENC);
}
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
if(holdResponse){
writeBufferSize = 0;
memcpy(writeBuffer, &handle, 2);
writeBufferSize+=2;
writeBuffer[writeBufferSize++] = _peers[i].addressType;
memcpy(&writeBuffer[writeBufferSize], _peers[i].address, sizeof(_peers[i].address));
writeBufferSize += sizeof(_peers[i].address);
writeBuffer[writeBufferSize] = valueLength;
writeBufferSize += sizeof(valueLength);
memcpy(&writeBuffer[writeBufferSize], value, valueLength);
writeBufferSize += valueLength;
}else{
characteristic->writeValue(BLEDevice(_peers[i].addressType, _peers[i].address), value, valueLength);
}
break;
}
}
} else if (attribute->type() == BLETypeDescriptor) {
BLELocalDescriptor* descriptor = (BLELocalDescriptor*)attribute;
// only CCCD's are writable
if (descriptor->uuidLength() != 2 || *((uint16_t*)(descriptor->uuidData())) != 0x2902) {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_WRITE_NOT_PERM);
}
return;
}
// get the previous handle, should be the characteristic for the CCCD
attribute = GATT.attribute(handle - 2);
if (attribute->type() != BLETypeCharacteristic) {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_WRITE_NOT_PERM);
}
return;
}
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
characteristic->writeCccdValue(BLEDevice(_peers[i].addressType, _peers[i].address), *((uint16_t*)value));
break;
}
}
} else {
if (withResponse) {
sendError(connectionHandle, ATT_OP_WRITE_REQ, handle, ATT_ECODE_WRITE_NOT_PERM);
}
return;
}
if (withResponse) {
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_WRITE_RESP;
responseLength = 1;
if(holdResponse){
memcpy(holdBuffer, response, responseLength);
holdBufferSize = responseLength;
}else{
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
}
}
int ATTClass::processWriteBuffer(){
if(writeBufferSize==0){
return 0;
}
struct __attribute__ ((packed)) WriteBuffer {
uint16_t handle;
uint8_t addressType;
uint8_t address[6];
uint8_t valueLength;
uint8_t value[];
} *writeBufferStruct = (WriteBuffer*)&ATT.writeBuffer;
// uint8_t value[writeBufferStruct->valueLength];
// memcpy(value, writeBufferStruct->value, writeBufferStruct->valueLength);
BLELocalAttribute* attribute = GATT.attribute(writeBufferStruct->handle-1);
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
#ifdef _BLE_TRACE_
Serial.println("Writing value");
#endif
characteristic->writeValue(BLEDevice(writeBufferStruct->addressType, writeBufferStruct->address), writeBufferStruct->value, writeBufferStruct->valueLength);
writeBufferSize = 0;
return 1;
}
void ATTClass::writeResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
if (dlen != 0) {
return; // drop
}
if (connectionHandle == _pendingResp.connectionHandle && _pendingResp.op == ATT_OP_WRITE_RESP) {
_pendingResp.buffer[0] = ATT_OP_WRITE_RESP;
memcpy(&_pendingResp.buffer[1], data, dlen);
_pendingResp.length = dlen + 1;
}
}
void ATTClass::prepWriteReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) PrepWriteReq {
uint16_t handle;
uint16_t offset;
} *prepWriteReq = (PrepWriteReq*)data;
if (dlen < sizeof(PrepWriteReq)) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
return;
}
uint16_t handle = prepWriteReq->handle;
uint16_t offset = prepWriteReq->offset;
if ((uint16_t)(handle - 1) > GATT.attributeCount()) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_ATTR_NOT_FOUND);
return;
}
BLELocalAttribute* attribute = GATT.attribute(handle - 1);
if (attribute->type() != BLETypeCharacteristic) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_ATTR_NOT_LONG);
return;
}
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)attribute;
if (handle != characteristic->valueHandle()) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_ATTR_NOT_LONG);
return;
}
if ((characteristic->properties() & BLEWrite) == 0) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_WRITE_NOT_PERM);
return;
}
if (_longWriteHandle == 0) {
int valueSize = characteristic->valueSize();
_longWriteValue = (uint8_t*)realloc(_longWriteValue, valueSize);
_longWriteValueLength = 0;
_longWriteHandle = handle;
memset(_longWriteValue, 0x00, valueSize);
} else if (_longWriteHandle != handle) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_UNLIKELY);
return;
}
uint8_t valueLength = dlen - sizeof(PrepWriteReq);
uint8_t* value = &data[sizeof(PrepWriteReq)];
if ((offset != _longWriteValueLength) || ((offset + valueLength) > (uint16_t)characteristic->valueSize())) {
sendError(connectionHandle, ATT_OP_PREP_WRITE_REQ, handle, ATT_ECODE_INVALID_OFFSET);
return;
}
memcpy(_longWriteValue + offset, value, valueLength);
_longWriteValueLength += valueLength;
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_PREP_WRITE_RESP;
memcpy(&response[1], data, dlen);
responseLength = dlen + 1;
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
void ATTClass::execWriteReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[])
{
if (dlen != sizeof(uint8_t)) {
sendError(connectionHandle, ATT_OP_EXEC_WRITE_REQ, 0x0000, ATT_ECODE_INVALID_PDU);
return;
}
uint8_t flag = data[0];
if (_longWriteHandle && (flag & 0x01)) {
BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)GATT.attribute(_longWriteHandle - 1);
for (int i = 0; i < ATT_MAX_PEERS; i++) {
if (_peers[i].connectionHandle == connectionHandle) {
characteristic->writeValue(BLEDevice(_peers[i].addressType, _peers[i].address), _longWriteValue, _longWriteValueLength);
break;
}
}
}
_longWriteHandle = 0x0000;
_longWriteValueLength = 0;
uint8_t response[mtu];
uint16_t responseLength;
response[0] = ATT_OP_EXEC_WRITE_RESP;
responseLength = 1;
HCI.sendAclPkt(connectionHandle, ATT_CID, responseLength, response);
}
void ATTClass::handleNotifyOrInd(uint16_t connectionHandle, uint8_t opcode, uint8_t dlen, uint8_t data[])
{
if (dlen < 2) {
return; // drop
}
struct __attribute__ ((packed)) HandleNotifyOrInd {
uint16_t handle;
} *handleNotifyOrInd = (HandleNotifyOrInd*)data;
uint16_t handle = handleNotifyOrInd->handle;
for (int peer = 0; peer < ATT_MAX_PEERS; peer++) {
if (_peers[peer].connectionHandle != connectionHandle) {
continue;
}
BLERemoteDevice* device = _peers[peer].device;
if (!device) {
break;
}
int serviceCount = device->serviceCount();
for (int i = 0; i < serviceCount; i++) {
BLERemoteService* s = device->service(i);
if (s->startHandle() < handle && s->endHandle() >= handle) {
int characteristicCount = s->characteristicCount();
for (int j = 0; j < characteristicCount; j++) {
BLERemoteCharacteristic* c = s->characteristic(j);
if (c->valueHandle() == handle) {
c->writeValue(BLEDevice(_peers[peer].addressType, _peers[peer].address), &data[2], dlen - 2);
}
}
break;
}
}
}
if (opcode == ATT_OP_HANDLE_IND) {
// send CNF for IND
uint8_t cnf = ATT_OP_HANDLE_CNF;
HCI.sendAclPkt(connectionHandle, ATT_CID, sizeof(cnf), &cnf);
}
}
void ATTClass::handleCnf(uint16_t /*connectionHandle*/, uint8_t /*dlen*/, uint8_t /*data*/[])
{
_cnf = true;
}
void ATTClass::sendError(uint16_t connectionHandle, uint8_t opcode, uint16_t handle, uint8_t code)
{
struct __attribute__ ((packed)) {
uint8_t op;
uint8_t opcode;
uint16_t handle;
uint8_t code;
} attError = { ATT_OP_ERROR, opcode, handle, code };
HCI.sendAclPkt(connectionHandle, ATT_CID, sizeof(attError), &attError);
}
bool ATTClass::exchangeMtu(uint16_t connectionHandle)
{
uint8_t responseBuffer[_maxMtu];
if (!mtuReq(connectionHandle, _maxMtu, responseBuffer)) {
return false;
}
return true;
}
bool ATTClass::discoverServices(uint16_t connectionHandle, BLERemoteDevice* device, const char* serviceUuidFilter)
{
uint16_t reqStartHandle = 0x0001;
uint16_t reqEndHandle = 0xffff;
uint8_t responseBuffer[_maxMtu];
BLEUuid serviceUuid(serviceUuidFilter);
while (reqEndHandle == 0xffff) {
int respLength = readByGroupReq(connectionHandle, reqStartHandle, reqEndHandle, BLETypeService, responseBuffer);
if (respLength == 0) {
return false;
}
if (responseBuffer[0] == ATT_OP_READ_BY_GROUP_RESP) {
uint16_t lengthPerService = responseBuffer[1];
uint8_t uuidLen = lengthPerService - 4;
for (int i = 2; i < respLength; i += lengthPerService) {
struct __attribute__ ((packed)) RawService {
uint16_t startHandle;
uint16_t endHandle;
uint8_t uuid[16];
} *rawService = (RawService*)&responseBuffer[i];
if (serviceUuidFilter == NULL ||
(uuidLen == serviceUuid.length() && memcmp(rawService->uuid, serviceUuid.data(), uuidLen) == 0)) {
BLERemoteService* service = new BLERemoteService(rawService->uuid, uuidLen,
rawService->startHandle,
rawService->endHandle);
if (service == NULL) {
return false;
}
device->addService(service);
}
reqStartHandle = rawService->endHandle + 1;
if (reqStartHandle == 0x0000) {
reqEndHandle = 0x0000;
}
}
} else {
reqEndHandle = 0x0000;
}
}
return true;
}
bool ATTClass::discoverCharacteristics(uint16_t connectionHandle, BLERemoteDevice* device)
{
uint16_t reqStartHandle = 0x0001;
uint16_t reqEndHandle = 0xffff;
uint8_t responseBuffer[_maxMtu];
int serviceCount = device->serviceCount();
for (int i = 0; i < serviceCount; i++) {
BLERemoteService* service = device->service(i);
reqStartHandle = service->startHandle();
reqEndHandle = service->endHandle();
while (1) {
int respLength = readByTypeReq(connectionHandle, reqStartHandle, reqEndHandle, BLETypeCharacteristic, responseBuffer);
if (respLength == 0) {
return false;
}
if (responseBuffer[0] == ATT_OP_READ_BY_TYPE_RESP) {
uint16_t lengthPerCharacteristic = responseBuffer[1];
uint8_t uuidLen = lengthPerCharacteristic - 5;
for (int i = 2; i < respLength; i += lengthPerCharacteristic) {
struct __attribute__ ((packed)) RawCharacteristic {
uint16_t startHandle;
uint8_t properties;
uint16_t valueHandle;
uint8_t uuid[16];
} *rawCharacteristic = (RawCharacteristic*)&responseBuffer[i];
BLERemoteCharacteristic* characteristic = new BLERemoteCharacteristic(rawCharacteristic->uuid, uuidLen,
connectionHandle,
rawCharacteristic->startHandle,
rawCharacteristic->properties,
rawCharacteristic->valueHandle);
if (characteristic == NULL) {
return false;
}
service->addCharacteristic(characteristic);
reqStartHandle = rawCharacteristic->valueHandle + 1;
}
} else {
break;
}
}
}
return true;
}
bool ATTClass::discoverDescriptors(uint16_t connectionHandle, BLERemoteDevice* device)
{
uint16_t reqStartHandle = 0x0001;
uint16_t reqEndHandle = 0xffff;
uint8_t responseBuffer[_maxMtu];
int serviceCount = device->serviceCount();
for (int i = 0; i < serviceCount; i++) {
BLERemoteService* service = device->service(i);
uint16_t serviceEndHandle = service->endHandle();
int characteristicCount = service->characteristicCount();
for (int j = 0; j < characteristicCount; j++) {
BLERemoteCharacteristic* characteristic = service->characteristic(j);
BLERemoteCharacteristic* nextCharacteristic = (j == (characteristicCount - 1)) ? NULL : service->characteristic(j + 1);
reqStartHandle = characteristic->valueHandle() + 1;
reqEndHandle = nextCharacteristic ? nextCharacteristic->valueHandle() : serviceEndHandle;
if (reqStartHandle > reqEndHandle) {
continue;
}
while (1) {
int respLength = findInfoReq(connectionHandle, reqStartHandle, reqEndHandle, responseBuffer);
if (respLength == 0) {
return false;
}
if (responseBuffer[0] == ATT_OP_FIND_INFO_RESP) {
uint16_t lengthPerDescriptor = responseBuffer[1] * 4;
uint8_t uuidLen = 2;
for (int i = 2; i < respLength; i += lengthPerDescriptor) {
struct __attribute__ ((packed)) RawDescriptor {
uint16_t handle;
uint8_t uuid[16];
} *rawDescriptor = (RawDescriptor*)&responseBuffer[i];
BLERemoteDescriptor* descriptor = new BLERemoteDescriptor(rawDescriptor->uuid, uuidLen,
connectionHandle,
rawDescriptor->handle);
if (descriptor == NULL) {
return false;
}
characteristic->addDescriptor(descriptor);
reqStartHandle = rawDescriptor->handle + 1;
}
} else {
break;
}
}
}
}
return true;
}
int ATTClass::sendReq(uint16_t connectionHandle, void* requestBuffer, int requestLength, uint8_t responseBuffer[])
{
_pendingResp.connectionHandle = connectionHandle;
_pendingResp.op = ((uint8_t*)requestBuffer)[0] + 1;
_pendingResp.buffer = responseBuffer;
_pendingResp.length = 0;
HCI.sendAclPkt(connectionHandle, ATT_CID, requestLength, requestBuffer);
if (responseBuffer == NULL) {
// not waiting response
return 0;
}
for (unsigned long start = millis(); (millis() - start) < _timeout;) {
HCI.poll();
if (!connected(connectionHandle)) {
break;
}
if (_pendingResp.length != 0) {
_pendingResp.connectionHandle = 0xffff;
return _pendingResp.length;
}
}
_pendingResp.connectionHandle = 0xffff;
return 0;
}
void ATTClass::setEventHandler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler)
{
if (event < (sizeof(_eventHandlers) / (sizeof(_eventHandlers[0])))) {
_eventHandlers[event] = eventHandler;
}
}
int ATTClass::readReq(uint16_t connectionHandle, uint16_t handle, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t handle;
} readReq = { ATT_OP_READ_REQ, handle };
return sendReq(connectionHandle, &readReq, sizeof(readReq), responseBuffer);
}
int ATTClass::writeReq(uint16_t connectionHandle, uint16_t handle, const uint8_t* data, uint8_t dataLen, uint8_t responseBuffer[])
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t handle;
uint8_t data[255];
} writeReq;
writeReq.op = ATT_OP_WRITE_REQ;
writeReq.handle = handle;
memcpy(writeReq.data, data, dataLen);
return sendReq(connectionHandle, &writeReq, 3 + dataLen, responseBuffer);
}
void ATTClass::writeCmd(uint16_t connectionHandle, uint16_t handle, const uint8_t* data, uint8_t dataLen)
{
struct __attribute__ ((packed)) {
uint8_t op;
uint16_t handle;
uint8_t data[255];
} writeReq;
writeReq.op = ATT_OP_WRITE_CMD;
writeReq.handle = handle;
memcpy(writeReq.data, data, dataLen);
sendReq(connectionHandle, &writeReq, 3 + dataLen, NULL);
}
// Set encryption state for a peer
int ATTClass::setPeerEncryption(uint16_t connectionHandle, uint8_t encryption){
for(int i=0; i 0){
return _peers[i].connectionHandle;
}
}
return ATT_MAX_PEERS + 1;
}
// Get the encryption state for a particular peer / connection handle
uint8_t ATTClass::getPeerEncryption(uint16_t connectionHandle) {
for(int i=0; i
#include "BLEDevice.h"
#include "keyDistribution.h"
#define ATT_CID 0x0004
#define BLE_CTL 0x0008
#if DM_CONN_MAX
#define ATT_MAX_PEERS DM_CONN_MAX // Mbed + Cordio
#elif __AVR__
#define ATT_MAX_PEERS 3
#else
#define ATT_MAX_PEERS 8
#endif
enum PEER_ENCRYPTION {
NO_ENCRYPTION = 0,
PAIRING_REQUEST = 1 << 0,
REQUESTED_ENCRYPTION = 1 << 1,
SENT_PUBKEY = 1 << 2,
DH_KEY_CALULATED = 1 << 3,
RECEIVED_DH_CHECK = 1 << 4,
SENT_DH_CHECK = 1 << 5,
ENCRYPTED_AES = 1 << 7
};
class BLERemoteDevice;
class ATTClass {
public:
ATTClass();
virtual ~ATTClass();
virtual void setMaxMtu(uint16_t maxMtu);
virtual void setTimeout(unsigned long timeout);
virtual bool connect(uint8_t peerBdaddrType, uint8_t peerBdaddr[6]);
virtual bool disconnect(uint8_t peerBdaddrType, uint8_t peerBdaddr[6]);
virtual bool discoverAttributes(uint8_t peerBdaddrType, uint8_t peerBdaddr[6], const char* serviceUuidFilter);
virtual void addConnection(uint16_t handle, uint8_t role, uint8_t peerBdaddrType,
uint8_t peerBdaddr[6], uint16_t interval,
uint16_t latency, uint16_t supervisionTimeout,
uint8_t masterClockAccuracy);
virtual void handleData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void removeConnection(uint16_t handle, uint8_t reason);
virtual uint16_t connectionHandle(uint8_t addressType, const uint8_t address[6]) const;
virtual BLERemoteDevice* device(uint8_t addressType, const uint8_t address[6]) const;
virtual bool connected() const;
virtual bool connected(uint8_t addressType, const uint8_t address[6]) const;
virtual bool connected(uint16_t handle) const;
virtual bool paired() const;
virtual bool paired(uint16_t handle) const;
virtual uint16_t mtu(uint16_t handle) const;
virtual bool disconnect();
virtual BLEDevice central();
virtual int handleNotify(uint16_t handle, const uint8_t* value, int length);
virtual int handleInd(uint16_t handle, const uint8_t* value, int length);
virtual void setEventHandler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler);
virtual int readReq(uint16_t connectionHandle, uint16_t handle, uint8_t responseBuffer[]);
virtual int writeReq(uint16_t connectionHandle, uint16_t handle, const uint8_t* data, uint8_t dataLen, uint8_t responseBuffer[]);
virtual void writeCmd(uint16_t connectionHandle, uint16_t handle, const uint8_t* data, uint8_t dataLen);
virtual int setPeerEncryption(uint16_t connectionHandle, uint8_t encryption);
uint8_t getPeerEncryption(uint16_t connectionHandle);
uint16_t getPeerEncrptingConnectionHandle();
virtual int getPeerAddr(uint16_t connectionHandle, uint8_t peerAddr[]);
virtual int getPeerAddrWithType(uint16_t connectionHandle, uint8_t peerAddr[]);
virtual int setPeerIOCap(uint16_t connectionHandle, uint8_t IOCap[]);
virtual int getPeerIOCap(uint16_t connectionHandle, uint8_t IOCap[]);
virtual int getPeerResolvedAddress(uint16_t connectionHandle, uint8_t* resolvedAddress);
uint8_t holdBuffer[64];
uint8_t writeBuffer[64];
uint8_t holdBufferSize;
uint8_t writeBufferSize;
virtual int processWriteBuffer();
KeyDistribution remoteKeyDistribution;
KeyDistribution localKeyDistribution;
uint8_t peerIRK[16];
/// This is just a random number... Not sure it has use unless privacy mode is active.
uint8_t localIRK[16] = {0x54,0x83,0x63,0x7c,0xc5,0x1e,0xf7,0xec,0x32,0xdd,0xad,0x51,0x89,0x4b,0x9e,0x07};
private:
virtual void error(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void mtuReq(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual int mtuReq(uint16_t connectionHandle, uint16_t mtu, uint8_t responseBuffer[]);
virtual void mtuResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void findInfoReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual int findInfoReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint8_t responseBuffer[]);
virtual void findInfoResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void findByTypeReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual void readByTypeReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual int readByTypeReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint16_t type, uint8_t responseBuffer[]);
virtual void readByTypeResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void readOrReadBlobReq(uint16_t connectionHandle, uint16_t mtu, uint8_t opcode, uint8_t dlen, uint8_t data[]);
virtual void readResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void readByGroupReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual int readByGroupReq(uint16_t connectionHandle, uint16_t startHandle, uint16_t endHandle, uint16_t uuid, uint8_t responseBuffer[]);
virtual void readByGroupResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void writeReqOrCmd(uint16_t connectionHandle, uint16_t mtu, uint8_t op, uint8_t dlen, uint8_t data[]);
virtual void writeResp(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void prepWriteReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual void execWriteReq(uint16_t connectionHandle, uint16_t mtu, uint8_t dlen, uint8_t data[]);
virtual void handleNotifyOrInd(uint16_t connectionHandle, uint8_t opcode, uint8_t dlen, uint8_t data[]);
virtual void handleCnf(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void sendError(uint16_t connectionHandle, uint8_t opcode, uint16_t handle, uint8_t code);
virtual bool exchangeMtu(uint16_t connectionHandle);
virtual bool discoverServices(uint16_t connectionHandle, BLERemoteDevice* device, const char* serviceUuidFilter);
virtual bool discoverCharacteristics(uint16_t connectionHandle, BLERemoteDevice* device);
virtual bool discoverDescriptors(uint16_t connectionHandle, BLERemoteDevice* device);
virtual int sendReq(uint16_t connectionHandle, void* requestBuffer, int requestLength, uint8_t responseBuffer[]);
private:
uint16_t _maxMtu;
unsigned long _timeout;
struct {
uint16_t connectionHandle;
uint8_t role;
uint8_t addressType;
uint8_t address[6];
uint8_t resolvedAddress[6];
uint16_t mtu;
BLERemoteDevice* device;
uint8_t encryption;
uint8_t IOCap[3];
} _peers[ATT_MAX_PEERS];
volatile bool _cnf;
uint16_t _longWriteHandle;
uint8_t* _longWriteValue;
uint16_t _longWriteValueLength;
struct {
uint16_t connectionHandle;
uint8_t op;
uint8_t* buffer;
uint8_t length;
} _pendingResp;
BLEDeviceEventHandler _eventHandlers[2];
};
extern ATTClass& ATT;
#endif
================================================
FILE: src/utility/BLELinkedList.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_LINKED_LIST_
#define _BLE_LINKED_LIST_
#include
template struct BLELinkedListNode
{
T data;
BLELinkedListNode* next;
};
template class BLELinkedList {
public:
BLELinkedList();
~BLELinkedList();
void add(T);
T get(unsigned int index) const;
void clear();
T remove(unsigned int index);
unsigned int size() const;
private:
unsigned int _size;
BLELinkedListNode* _root;
BLELinkedListNode* _last;
};
template BLELinkedList::BLELinkedList() :
_size(0),
_root(NULL),
_last(NULL)
{
}
template BLELinkedList::~BLELinkedList()
{
clear();
}
template void BLELinkedList::add(T item)
{
BLELinkedListNode* itemNode = new BLELinkedListNode();
itemNode->data = item;
itemNode->next = NULL;
if (_root == NULL) {
_root = itemNode;
} else {
_last->next = itemNode;
}
_last = itemNode;
_size++;
}
template T BLELinkedList::get(unsigned int index) const
{
if (index >= _size) {
return T();
}
BLELinkedListNode* itemNode = _root;
for (unsigned int i = 0; i < index; i++) {
itemNode = itemNode->next;
}
return itemNode->data;
}
template void BLELinkedList::clear()
{
BLELinkedListNode* itemNode = _root;
for (unsigned int i = 0; i < _size; i++) {
BLELinkedListNode* n = itemNode;
itemNode = itemNode->next;
delete n;
}
_size = 0;
_root = NULL;
_last = NULL;
}
template unsigned int BLELinkedList::size() const
{
return _size;
}
template T BLELinkedList::remove(unsigned int index)
{
if (index >= _size) {
return T();
}
BLELinkedListNode* previousItemNode = NULL;
BLELinkedListNode* itemNode = _root;
for (unsigned int i = 0; i < index; i++) {
previousItemNode = itemNode;
itemNode = itemNode->next;
}
T result = itemNode->data;
if (previousItemNode == NULL) {
_root = itemNode->next;
} else {
previousItemNode->next = itemNode->next;
}
if (_last == itemNode) {
_last = previousItemNode;
}
delete itemNode;
_size--;
return result;
}
#endif
================================================
FILE: src/utility/BLEUuid.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include
#include "BLEUuid.h"
BLEUuid::BLEUuid(const char * str) :
_str(str)
{
char temp[] = {0, 0, 0};
memset(_data, 0x00, sizeof(_data));
_length = 0;
if (str == NULL) {
return;
}
for (int i = strlen(str) - 1; i >= 0 && _length < BLE_UUID_MAX_LENGTH; i -= 2) {
if (str[i] == '-') {
i++;
continue;
}
temp[0] = str[i - 1];
temp[1] = str[i];
_data[_length] = strtoul(temp, NULL, 16);
_length++;
}
if (_length <= 2) {
_length = 2;
} else {
_length = 16;
}
}
const char* BLEUuid::str() const
{
return _str;
}
const uint8_t* BLEUuid::data() const
{
return _data;
}
uint8_t BLEUuid::length() const
{
return _length;
}
const char* BLEUuid::uuidToString(const uint8_t* data, uint8_t length)
{
static char uuid[36 + 1];
char* c = uuid;
for (int i = length - 1; i >= 0; i--) {
uint8_t b = data[i];
utoa(b >> 4, c++, 16);
utoa(b & 0x0f, c++, 16);
if (i == 6 || i == 8 || i == 10 || i == 12) {
*c++ = '-';
}
}
*c = '\0';
return uuid;
}
================================================
FILE: src/utility/BLEUuid.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _BLE_UUID_H_
#define _BLE_UUID_H_
#include
#define BLE_UUID_MAX_LENGTH 16
class BLEUuid
{
public:
BLEUuid(const char * str);
const char* str() const;
const uint8_t * data() const;
uint8_t length() const;
static const char* uuidToString(const uint8_t* data, uint8_t length);
private:
const char* _str;
uint8_t _data[BLE_UUID_MAX_LENGTH];
uint8_t _length;
};
#endif
================================================
FILE: src/utility/CordioHCICustomDriver.h
================================================
#if defined(CORE_CM4)
#include "CyH4TransportDriver.h"
ble::vendor::cypress_ble::CyH4TransportDriver& ble_cordio_get_h4_transport_driver()
{
static ble::vendor::cypress_ble::CyH4TransportDriver s_transport_driver(
/* TX */ CYBSP_BT_UART_TX, /* RX */ CYBSP_BT_UART_RX,
/* cts */ CYBSP_BT_UART_CTS, /* rts */ CYBSP_BT_UART_RTS, NC, DEF_BT_BAUD_RATE,
CYBSP_BT_HOST_WAKE, CYBSP_BT_DEVICE_WAKE
);
return s_transport_driver;
}
#define CUSTOM_HCI_DRIVER
#endif
================================================
FILE: src/utility/GAP.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "BLEUuid.h"
#include "HCI.h"
#include "GAP.h"
#define GAP_MAX_DISCOVERED_QUEUE_SIZE 32
#define GAP_ADV_IND (0x00)
#define GAP_ADV_SCAN_IND (0x02)
#define GAP_ADV_NONCONN_IND (0x03)
GAPClass::GAPClass() :
_advertising(false),
_scanning(false),
_advertisingInterval(160),
_connectable(true),
_discoverEventHandler(NULL)
{
}
GAPClass::~GAPClass()
{
}
bool GAPClass::advertising()
{
return _advertising;
}
int GAPClass::advertise(uint8_t* advData, uint8_t advDataLen, uint8_t* scanData, uint8_t scanDataLen)
{
uint8_t directBdaddr[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t type = (_connectable) ? GAP_ADV_IND : (scanDataLen ? GAP_ADV_SCAN_IND : GAP_ADV_NONCONN_IND);
stopAdvertise();
if (HCI.leSetAdvertisingParameters(_advertisingInterval, _advertisingInterval, type, 0x00, 0x00, directBdaddr, 0x07, 0) != 0) {
return 0;
}
if (HCI.leSetAdvertisingData(advDataLen, advData) != 0) {
return 0;
}
if (HCI.leSetScanResponseData(scanDataLen, scanData) != 0) {
return 0;
}
if (HCI.leSetAdvertiseEnable(0x01) != 0) {
return 0;
}
_advertising = true;
return 1;
}
void GAPClass::stopAdvertise()
{
_advertising = false;
HCI.leSetAdvertiseEnable(0x00);
}
int GAPClass::scan(bool withDuplicates)
{
HCI.leSetScanEnable(false, true);
// active scan, 20 ms scan interval (N * 0.625), 20 ms scan window (N * 0.625), public own address type, no filter
/*
Warning (from BLUETOOTH SPECIFICATION 5.x):
- scan interval: mandatory range from 0x0012 to 0x1000; only even values are valid
- scan window: mandatory range from 0x0011 to 0x1000
- The scan window can only be less than or equal to the scan interval
*/
if (HCI.leSetScanParameters(0x01, 0x0020, 0x0020, 0x00, 0x00) != 0) {
return false;
}
_scanning = true;
if (HCI.leSetScanEnable(true, !withDuplicates) != 0) {
return 0;
}
return 1;
}
int GAPClass::scanForName(String name, bool withDuplicates)
{
_scanNameFilter = name;
_scanUuidFilter = "";
_scanAddressFilter = "";
return scan(withDuplicates);
}
int GAPClass::scanForUuid(String uuid, bool withDuplicates)
{
_scanNameFilter = "";
_scanUuidFilter = uuid;
_scanAddressFilter = "";
return scan(withDuplicates);
}
int GAPClass::scanForAddress(String address, bool withDuplicates)
{
_scanNameFilter = "";
_scanUuidFilter = "";
_scanAddressFilter = address;
return scan(withDuplicates);
}
void GAPClass::stopScan()
{
HCI.leSetScanEnable(false, false);
_scanning = false;
for (unsigned int i = 0; i < _discoveredDevices.size(); i++) {
BLEDevice* device = _discoveredDevices.get(i);
delete device;
}
_discoveredDevices.clear();
}
BLEDevice GAPClass::available()
{
for (unsigned int i = 0; i < _discoveredDevices.size(); i++) {
BLEDevice* device = _discoveredDevices.get(i);
if (device->discovered()) {
BLEDevice result = *device;
_discoveredDevices.remove(i);
delete device;
if (matchesScanFilter(result)) {
return result;
} else {
continue;
}
}
}
return BLEDevice();
}
void GAPClass::setAdvertisingInterval(uint16_t advertisingInterval)
{
_advertisingInterval = advertisingInterval;
}
void GAPClass::setConnectable(bool connectable)
{
_connectable = connectable;
}
void GAPClass::setEventHandler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler)
{
if (event == BLEDiscovered) {
_discoverEventHandler = eventHandler;
}
}
void GAPClass::handleLeAdvertisingReport(uint8_t type, uint8_t addressType, uint8_t address[6],
uint8_t eirLength, uint8_t eirData[], int8_t rssi)
{
if (!_scanning) {
return;
}
if (_discoverEventHandler && type == 0x03) {
// call event handler and skip adding to discover list
BLEDevice device(addressType, address);
device.setAdvertisementData(type, eirLength, eirData, rssi);
if (matchesScanFilter(device)) {
_discoverEventHandler(device);
}
return;
}
BLEDevice* discoveredDevice = NULL;
int discoveredIndex = -1;
for (unsigned int i = 0; i < _discoveredDevices.size(); i++) {
BLEDevice* device = _discoveredDevices.get(i);
if (device->hasAddress(addressType, address)) {
discoveredDevice = device;
discoveredIndex = i;
break;
}
}
if (discoveredDevice == NULL) {
if (_discoveredDevices.size() >= GAP_MAX_DISCOVERED_QUEUE_SIZE) {
BLEDevice* device_first = _discoveredDevices.remove(0);
if (device_first != NULL) {
delete device_first;
}
}
discoveredDevice = new BLEDevice(addressType, address);
_discoveredDevices.add(discoveredDevice);
discoveredIndex = _discoveredDevices.size() - 1;
}
if (type != 0x04) {
discoveredDevice->setAdvertisementData(type, eirLength, eirData, rssi);
} else {
discoveredDevice->setScanResponseData(eirLength, eirData, rssi);
}
if (discoveredDevice->discovered() && _discoverEventHandler) {
// remove from list and report as discovered
BLEDevice device = *discoveredDevice;
_discoveredDevices.remove(discoveredIndex);
delete discoveredDevice;
if (matchesScanFilter(device)) {
_discoverEventHandler(device);
}
}
}
bool GAPClass::matchesScanFilter(const BLEDevice& device)
{
if (_scanAddressFilter.length() > 0 && !(_scanAddressFilter.equalsIgnoreCase(device.address()))) {
return false; // drop doesn't match
} else if (_scanNameFilter.length() > 0 && _scanNameFilter != device.localName()) {
return false; // drop doesn't match
} else if (_scanUuidFilter.length() > 0 && !(_scanUuidFilter.equalsIgnoreCase(device.advertisedServiceUuid()))) {
return false; // drop doesn't match
}
return true;
}
#if !defined(FAKE_GAP)
GAPClass GAPObj;
GAPClass& GAP = GAPObj;
#endif
================================================
FILE: src/utility/GAP.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _GAP_H_
#define _GAP_H_
#include "utility/BLELinkedList.h"
#include "BLEDevice.h"
class GAPClass {
public:
GAPClass();
virtual ~GAPClass();
virtual bool advertising();
virtual int advertise(uint8_t* advData, uint8_t advDataLength, uint8_t* scanData, uint8_t scanDataLength);
virtual void stopAdvertise();
virtual int scan(bool withDuplicates);
virtual int scanForName(String name, bool withDuplicates);
virtual int scanForUuid(String uuid, bool withDuplicates);
virtual int scanForAddress(String address, bool withDuplicates);
virtual void stopScan();
virtual BLEDevice available();
virtual void setAdvertisingInterval(uint16_t advertisingInterval);
virtual void setConnectable(bool connectable);
virtual void setEventHandler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler);
protected:
friend class HCIClass;
virtual void handleLeAdvertisingReport(uint8_t type, uint8_t addressType, uint8_t address[6],
uint8_t eirLength, uint8_t eirData[], int8_t rssi);
private:
virtual bool matchesScanFilter(const BLEDevice& device);
private:
bool _advertising;
bool _scanning;
uint16_t _advertisingInterval;
bool _connectable;
BLEDeviceEventHandler _discoverEventHandler;
BLELinkedList _discoveredDevices;
String _scanNameFilter;
String _scanUuidFilter;
String _scanAddressFilter;
};
extern GAPClass& GAP;
#endif
================================================
FILE: src/utility/GATT.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include
#include "local/BLELocalCharacteristic.h"
#include "local/BLELocalDescriptor.h"
#include "local/BLELocalService.h"
#include "BLEProperty.h"
#include "GATT.h"
GATTClass::GATTClass() :
_genericAccessService(NULL),
_deviceNameCharacteristic(NULL),
_appearanceCharacteristic(NULL),
_genericAttributeService(NULL),
_servicesChangedCharacteristic(NULL)
{
}
GATTClass::~GATTClass()
{
end();
}
void GATTClass::begin()
{
_genericAccessService = new BLELocalService("1800");
_deviceNameCharacteristic = new BLELocalCharacteristic("2a00", BLERead, 20);
_appearanceCharacteristic = new BLELocalCharacteristic("2a01", BLERead, 2);
_genericAttributeService = new BLELocalService("1801");
_servicesChangedCharacteristic = new BLELocalCharacteristic("2a05", BLEIndicate, 4);
_genericAccessService->retain();
_deviceNameCharacteristic->retain();
_appearanceCharacteristic->retain();
_genericAttributeService->retain();
_servicesChangedCharacteristic->retain();
_genericAccessService->addCharacteristic(_deviceNameCharacteristic);
_genericAccessService->addCharacteristic(_appearanceCharacteristic);
_genericAttributeService->addCharacteristic(_servicesChangedCharacteristic);
setDeviceName("Arduino");
setAppearance(0x000);
clearAttributes();
addService(_genericAccessService);
addService(_genericAttributeService);
}
void GATTClass::end()
{
if (_genericAccessService && _genericAccessService->release() == 0) {
delete(_genericAccessService);
_genericAccessService = NULL;
}
if (_deviceNameCharacteristic && _deviceNameCharacteristic->release() == 0) {
delete(_deviceNameCharacteristic);
_deviceNameCharacteristic = NULL;
}
if (_appearanceCharacteristic && _appearanceCharacteristic->release() == 0) {
delete(_appearanceCharacteristic);
_appearanceCharacteristic = NULL;
}
if (_genericAttributeService && _genericAttributeService->release() == 0) {
delete(_genericAttributeService);
_genericAttributeService = NULL;
}
if (_servicesChangedCharacteristic && _servicesChangedCharacteristic->release() == 0) {
delete(_servicesChangedCharacteristic);
_servicesChangedCharacteristic = NULL;
}
clearAttributes();
}
void GATTClass::setDeviceName(const char* deviceName)
{
_deviceNameCharacteristic->writeValue(deviceName);
}
void GATTClass::setAppearance(uint16_t appearance)
{
_appearanceCharacteristic->writeValue((uint8_t*)&appearance, sizeof(appearance));
}
void GATTClass::addService(BLEService& service)
{
BLELocalService* localService = service.local();
if (localService) {
addService(localService);
}
}
unsigned int GATTClass::attributeCount() const
{
return _attributes.size();
}
BLELocalAttribute* GATTClass::attribute(unsigned int index) const
{
return _attributes.get(index);
}
uint16_t GATTClass::serviceUuidForCharacteristic(BLELocalCharacteristic* characteristic) const
{
uint16_t serviceUuid = 0x0000;
BLELocalService* lastService = NULL;
for (unsigned int i = 0; i < attributeCount(); i++) {
BLELocalAttribute* a = attribute(i);
uint16_t attributeType = a->type();
if (attributeType == BLETypeService) {
lastService = (BLELocalService*)a;
} else if (a == characteristic) {
break;
}
}
if (lastService) {
if (lastService->uuidLength() == 2) {
serviceUuid = *(uint16_t*)(lastService->uuidData());
} else {
serviceUuid = *(uint16_t*)(lastService->uuidData() + 10);
}
}
return serviceUuid;
}
void GATTClass::addService(BLELocalService* service)
{
service->retain();
_attributes.add(service);
_services.add(service);
uint16_t startHandle = attributeCount();
for (unsigned int i = 0; i < service->characteristicCount(); i++) {
BLELocalCharacteristic* characteristic = service->characteristic(i);
characteristic->retain();
_attributes.add(characteristic);
characteristic->setHandle(attributeCount());
// add the characteristic again to make space of the characteristic value handle
characteristic->retain();
_attributes.add(characteristic);
for (unsigned int j = 0; j < characteristic->descriptorCount(); j++) {
BLELocalDescriptor* descriptor = characteristic->descriptor(j);
descriptor->retain();
_attributes.add(descriptor);
descriptor->setHandle(attributeCount());
}
}
service->setHandles(startHandle, attributeCount());
}
void GATTClass::clearAttributes()
{
for (unsigned int i = 0; i < attributeCount(); i++) {
BLELocalAttribute* a = attribute(i);
if (a->release() == 0) {
delete a;
}
}
_attributes.clear();
for (unsigned int i = 0; i < _services.size(); i++) {
_services.get(i)->clear();
}
_services.clear();
}
#if !defined(FAKE_GATT)
GATTClass GATTObj;
GATTClass& GATT = GATTObj;
#endif
================================================
FILE: src/utility/GATT.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _GATT_H_
#define _GATT_H_
#include "utility/BLELinkedList.h"
#include "local/BLELocalAttribute.h"
#include "local/BLELocalCharacteristic.h"
#include "local/BLELocalService.h"
#include "BLEService.h"
class GATTClass {
public:
GATTClass();
virtual ~GATTClass();
virtual void begin();
virtual void end();
virtual void setDeviceName(const char* deviceName);
virtual void setAppearance(uint16_t appearance);
virtual void addService(BLEService& service);
protected:
friend class ATTClass;
virtual unsigned int attributeCount() const;
virtual BLELocalAttribute* attribute(unsigned int index) const;
protected:
friend class BLELocalCharacteristic;
virtual uint16_t serviceUuidForCharacteristic(BLELocalCharacteristic* characteristic) const;
private:
virtual void addService(BLELocalService* service);
virtual void clearAttributes();
private:
BLELinkedList _attributes;
BLELinkedList _services;
BLELocalService* _genericAccessService;
BLELocalCharacteristic* _deviceNameCharacteristic;
BLELocalCharacteristic* _appearanceCharacteristic;
BLELocalService* _genericAttributeService;
BLELocalCharacteristic* _servicesChangedCharacteristic;
};
extern GATTClass& GATT;
#endif
================================================
FILE: src/utility/HCI.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "ATT.h"
#include "GAP.h"
#include "HCITransport.h"
#include "L2CAPSignaling.h"
#include "btct.h"
#include "HCI.h"
#include "bitDescriptions.h"
// #define _BLE_TRACE_
#define HCI_COMMAND_PKT 0x01
#define HCI_ACLDATA_PKT 0x02
#define HCI_EVENT_PKT 0x04
#define HCI_SECURITY_PKT 0x06
#define EVT_DISCONN_COMPLETE 0x05
#define EVT_ENCRYPTION_CHANGE 0x08
#define EVT_CMD_COMPLETE 0x0e
#define EVT_CMD_STATUS 0x0f
#define EVT_NUM_COMP_PKTS 0x13
#define EVT_RETURN_LINK_KEYS 0x15
#define EVT_UNKNOWN 0x10
#define EVT_LE_META_EVENT 0x3e
#define EVT_LE_CONN_COMPLETE 0x01
#define EVT_LE_ADVERTISING_REPORT 0x02
// OGF_LINK_CTL
#define OCF_DISCONNECT 0x0006
// OGF_HOST_CTL
#define OCF_SET_EVENT_MASK 0x0001
#define OCF_RESET 0x0003
// OGF_INFO_PARAM
#define OCF_READ_LOCAL_VERSION 0x0001
#define OCF_READ_BD_ADDR 0x0009
// OGF_STATUS_PARAM
#define OCF_READ_RSSI 0x0005
// OGF_LE_CTL
#define OCF_LE_READ_BUFFER_SIZE 0x0002
#define OCF_LE_SET_RANDOM_ADDRESS 0x0005
#define OCF_LE_SET_ADVERTISING_PARAMETERS 0x0006
#define OCF_LE_SET_ADVERTISING_DATA 0x0008
#define OCF_LE_SET_SCAN_RESPONSE_DATA 0x0009
#define OCF_LE_SET_ADVERTISE_ENABLE 0x000a
#define OCF_LE_SET_SCAN_PARAMETERS 0x000b
#define OCF_LE_SET_SCAN_ENABLE 0x000c
#define OCF_LE_CREATE_CONN 0x000d
#define OCF_LE_CANCEL_CONN 0x000e
#define OCF_LE_CONN_UPDATE 0x0013
#define HCI_OE_USER_ENDED_CONNECTION 0x13
String metaEventToString(LE_META_EVENT event)
{
switch(event){
case CONN_COMPLETE: return F("CONN_COMPLETE");
case ADVERTISING_REPORT: return F("ADVERTISING_REPORT");
case LONG_TERM_KEY_REQUEST: return F("LE_LONG_TERM_KEY_REQUEST");
case READ_LOCAL_P256_COMPLETE: return F("READ_LOCAL_P256_COMPLETE");
case GENERATE_DH_KEY_COMPLETE: return F("GENERATE_DH_KEY_COMPLETE");
case ENHANCED_CONN_COMPLETE: return F("ENHANCED_CONN_COMPLETE");
default: return "event unknown";
}
}
String commandToString(LE_COMMAND command){
switch (command)
{
case ENCRYPT: return F("ENCRYPT");
case LONG_TERM_KEY_REPLY: return F("LONG_TERM_KEY_REPLY");
case READ_LOCAL_P256: return F("READ_LOCAL_P256");
case GENERATE_DH_KEY_V1: return F("GENERATE_DH_KEY_V1");
case GENERATE_DH_KEY_V2: return F("GENERATE_DH_KEY_V2");
default: return "UNKNOWN";
}
}
HCIClass::HCIClass() :
_debug(NULL),
_recvIndex(0),
_pendingPkt(0),
_l2CapPduBufferSize(0)
{
}
HCIClass::~HCIClass()
{
}
int HCIClass::begin()
{
_recvIndex = 0;
return HCITransport.begin();
}
void HCIClass::end()
{
HCITransport.end();
}
void HCIClass::poll()
{
poll(0);
}
void HCIClass::poll(unsigned long timeout)
{
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, LOW);
#endif
if (timeout) {
HCITransport.wait(timeout);
}
HCITransport.lockForRead();
while (HCITransport.available()) {
byte b = HCITransport.read();
if (_recvIndex >= (int)sizeof(_recvBuffer)) {
_recvIndex = 0;
if (_debug) {
HCITransport.unlockForRead();
_debug->println("_recvBuffer overflow");
HCITransport.lockForRead();
}
}
_recvBuffer[_recvIndex++] = b;
if (_recvBuffer[0] == HCI_ACLDATA_PKT) {
if (_recvIndex > 5 && _recvIndex >= (5 + (_recvBuffer[3] + (_recvBuffer[4] << 8)))) {
HCITransport.unlockForRead();
if (_debug) {
dumpPkt("HCI ACLDATA RX <- ", _recvIndex, _recvBuffer);
}
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, HIGH);
#endif
int pktLen = _recvIndex - 1;
_recvIndex = 0;
handleAclDataPkt(pktLen, &_recvBuffer[1]);
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, LOW);
#endif
HCITransport.lockForRead();
}
} else if (_recvBuffer[0] == HCI_EVENT_PKT) {
if (_recvIndex > 3 && _recvIndex >= (3 + _recvBuffer[2])) {
HCITransport.unlockForRead();
if (_debug) {
dumpPkt("HCI EVENT RX <- ", _recvIndex, _recvBuffer);
}
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, HIGH);
#endif
// received full event
int pktLen = _recvIndex - 1;
_recvIndex = 0;
handleEventPkt(pktLen, &_recvBuffer[1]);
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, LOW);
#endif
HCITransport.lockForRead();
}
} else {
_recvIndex = 0;
if (_debug) {
HCITransport.unlockForRead();
_debug->println(b, HEX);
HCITransport.lockForRead();
}
}
}
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
digitalWrite(NINA_RTS, HIGH);
#endif
HCITransport.unlockForRead();
}
int HCIClass::reset()
{
return sendCommand(OGF_HOST_CTL << 10 | OCF_RESET);
}
int HCIClass::readLocalVersion(uint8_t& hciVer, uint16_t& hciRev, uint8_t& lmpVer, uint16_t& manufacturer, uint16_t& lmpSubVer)
{
int result = sendCommand(OGF_INFO_PARAM << 10 | OCF_READ_LOCAL_VERSION);
if (result == 0) {
struct __attribute__ ((packed)) HCILocalVersion {
uint8_t hciVer;
uint16_t hciRev;
uint8_t lmpVer;
uint16_t manufacturer;
uint16_t lmpSubVer;
} *localVersion = (HCILocalVersion*)_cmdResponse;
hciVer = localVersion->hciVer;
hciRev = localVersion->hciRev;
lmpVer = localVersion->lmpVer;
manufacturer = localVersion->manufacturer;
lmpSubVer = localVersion->lmpSubVer;
}
return result;
}
int HCIClass::readBdAddr(uint8_t addr[6])
{
int result = sendCommand(OGF_INFO_PARAM << 10 | OCF_READ_BD_ADDR);
if (result == 0) {
memcpy(addr, _cmdResponse, 6);
}
return result;
}
int HCIClass::readBdAddr(){
uint8_t response[6];
int result = readBdAddr(response);
if(result==0){
for(int i=0; i<6; i++){
localAddr[5-i] = _cmdResponse[i];
}
}
return result;
}
int HCIClass::readRssi(uint16_t handle)
{
int result = sendCommand(OGF_STATUS_PARAM << 10 | OCF_READ_RSSI, sizeof(handle), &handle);
int rssi = 127;
if (result == 0) {
struct __attribute__ ((packed)) HCIReadRssi {
uint16_t handle;
int8_t rssi;
} *readRssi = (HCIReadRssi*)_cmdResponse;
if (readRssi->handle == handle) {
rssi = readRssi->rssi;
}
}
return rssi;
}
int HCIClass::setEventMask(uint64_t eventMask)
{
return sendCommand(OGF_HOST_CTL << 10 | OCF_SET_EVENT_MASK, sizeof(eventMask), &eventMask);
}
// Set LE Event mask
int HCIClass::setLeEventMask(uint64_t leEventMask)
{
return sendCommand(OGF_LE_CTL << 10 | 0x01, sizeof(leEventMask), &leEventMask);
}
int HCIClass::readLeBufferSize(uint16_t& pktLen, uint8_t& maxPkt)
{
int result = sendCommand(OGF_LE_CTL << 10 | OCF_LE_READ_BUFFER_SIZE);
if (result == 0) {
struct __attribute__ ((packed)) HCILeBufferSize {
uint16_t pktLen;
uint8_t maxPkt;
} *leBufferSize = (HCILeBufferSize*)_cmdResponse;
pktLen = leBufferSize->pktLen;
_maxPkt = maxPkt = leBufferSize->maxPkt;
#ifndef __AVR__
ATT.setMaxMtu(pktLen - 9); // max pkt len - ACL header size
#endif
}
return result;
}
int HCIClass::leSetRandomAddress(uint8_t addr[6])
{
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_RANDOM_ADDRESS, 6, addr);
}
int HCIClass::leSetAdvertisingParameters(uint16_t minInterval, uint16_t maxInterval,
uint8_t advType, uint8_t ownBdaddrType,
uint8_t directBdaddrType, uint8_t directBdaddr[6],
uint8_t chanMap,
uint8_t filter)
{
struct __attribute__ ((packed)) HCILeAdvertisingParameters {
uint16_t minInterval;
uint16_t maxInterval;
uint8_t advType;
uint8_t ownBdaddrType;
uint8_t directBdaddrType;
uint8_t directBdaddr[6];
uint8_t chanMap;
uint8_t filter;
} leAdvertisingParamters;
leAdvertisingParamters.minInterval = minInterval;
leAdvertisingParamters.maxInterval = maxInterval;
leAdvertisingParamters.advType = advType;
leAdvertisingParamters.ownBdaddrType = ownBdaddrType;
leAdvertisingParamters.directBdaddrType = directBdaddrType;
memcpy(leAdvertisingParamters.directBdaddr, directBdaddr, 6);
leAdvertisingParamters.chanMap = chanMap;
leAdvertisingParamters.filter = filter;
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_ADVERTISING_PARAMETERS, sizeof(leAdvertisingParamters), &leAdvertisingParamters);
}
int HCIClass::leSetAdvertisingData(uint8_t length, uint8_t data[])
{
struct __attribute__ ((packed)) HCILeAdvertisingData {
uint8_t length;
uint8_t data[31];
} leAdvertisingData;
memset(&leAdvertisingData, 0, sizeof(leAdvertisingData));
leAdvertisingData.length = length;
memcpy(leAdvertisingData.data, data, length);
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_ADVERTISING_DATA, sizeof(leAdvertisingData), &leAdvertisingData);
}
int HCIClass::leSetScanResponseData(uint8_t length, uint8_t data[])
{
struct __attribute__ ((packed)) HCILeScanResponseData {
uint8_t length;
uint8_t data[31];
} leScanResponseData;
memset(&leScanResponseData, 0, sizeof(leScanResponseData));
leScanResponseData.length = length;
memcpy(leScanResponseData.data, data, length);
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_SCAN_RESPONSE_DATA, sizeof(leScanResponseData), &leScanResponseData);
}
int HCIClass::leSetAdvertiseEnable(uint8_t enable)
{
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_ADVERTISE_ENABLE, sizeof(enable), &enable);
}
int HCIClass::leSetScanParameters(uint8_t type, uint16_t interval, uint16_t window,
uint8_t ownBdaddrType, uint8_t filter)
{
struct __attribute__ ((packed)) HCILeSetScanParameters {
uint8_t type;
uint16_t interval;
uint16_t window;
uint8_t ownBdaddrType;
uint8_t filter;
} leScanParameters;
leScanParameters.type = type;
leScanParameters.interval = interval;
leScanParameters.window = window;
leScanParameters.ownBdaddrType = ownBdaddrType;
leScanParameters.filter = filter;
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_SCAN_PARAMETERS, sizeof(leScanParameters), &leScanParameters);
}
int HCIClass::leSetScanEnable(uint8_t enabled, uint8_t duplicates)
{
struct __attribute__ ((packed)) HCILeSetScanEnableData {
uint8_t enabled;
uint8_t duplicates;
} leScanEnableData;
leScanEnableData.enabled = enabled;
leScanEnableData.duplicates = duplicates;
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_SET_SCAN_ENABLE, sizeof(leScanEnableData), &leScanEnableData);
}
int HCIClass::leCreateConn(uint16_t interval, uint16_t window, uint8_t initiatorFilter,
uint8_t peerBdaddrType, uint8_t peerBdaddr[6], uint8_t ownBdaddrType,
uint16_t minInterval, uint16_t maxInterval, uint16_t latency,
uint16_t supervisionTimeout, uint16_t minCeLength, uint16_t maxCeLength)
{
struct __attribute__ ((packed)) HCILeCreateConnData {
uint16_t interval;
uint16_t window;
uint8_t initiatorFilter;
uint8_t peerBdaddrType;
uint8_t peerBdaddr[6];
uint8_t ownBdaddrType;
uint16_t minInterval;
uint16_t maxInterval;
uint16_t latency;
uint16_t supervisionTimeout;
uint16_t minCeLength;
uint16_t maxCeLength;
} leCreateConnData;
leCreateConnData.interval = interval;
leCreateConnData.window = window;
leCreateConnData.initiatorFilter = initiatorFilter;
leCreateConnData.peerBdaddrType = peerBdaddrType;
memcpy(leCreateConnData.peerBdaddr, peerBdaddr, sizeof(leCreateConnData.peerBdaddr));
leCreateConnData.ownBdaddrType = ownBdaddrType;
leCreateConnData.minInterval = minInterval;
leCreateConnData.maxInterval = maxInterval;
leCreateConnData.latency = latency;
leCreateConnData.supervisionTimeout = supervisionTimeout;
leCreateConnData.minCeLength = minCeLength;
leCreateConnData.maxCeLength = maxCeLength;
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_CREATE_CONN, sizeof(leCreateConnData), &leCreateConnData);
}
int HCIClass::leCancelConn()
{
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_CANCEL_CONN, 0, NULL);
}
int HCIClass::leConnUpdate(uint16_t handle, uint16_t minInterval, uint16_t maxInterval,
uint16_t latency, uint16_t supervisionTimeout)
{
struct __attribute__ ((packed)) HCILeConnUpdateData {
uint16_t handle;
uint16_t minInterval;
uint16_t maxInterval;
uint16_t latency;
uint16_t supervisionTimeout;
uint16_t minCeLength;
uint16_t maxCeLength;
} leConnUpdateData;
leConnUpdateData.handle = handle;
leConnUpdateData.minInterval = minInterval;
leConnUpdateData.maxInterval = maxInterval;
leConnUpdateData.latency = latency;
leConnUpdateData.supervisionTimeout = supervisionTimeout;
leConnUpdateData.minCeLength = 0x0004;
leConnUpdateData.maxCeLength = 0x0006;
return sendCommand(OGF_LE_CTL << 10 | OCF_LE_CONN_UPDATE, sizeof(leConnUpdateData), &leConnUpdateData);
}
void HCIClass::saveNewAddress(uint8_t addressType, uint8_t* address, uint8_t* peerIrk, uint8_t* localIrk){
(void)addressType;
(void)localIrk;
if(_storeIRK!=0){
_storeIRK(address, peerIrk);
}
// Again... this should work
// leAddResolvingAddress(addressType, address, peerIrk, localIrk);
}
void HCIClass::leAddResolvingAddress(uint8_t addressType, uint8_t* peerAddress, uint8_t* peerIrk, uint8_t* localIrk){
leStopResolvingAddresses();
struct __attribute__ ((packed)) AddDevice {
uint8_t peerAddressType;
uint8_t peerAddress[6];
uint8_t peerIRK[16];
uint8_t localIRK[16];
} addDevice;
addDevice.peerAddressType = addressType;
for(int i=0; i<6; i++) addDevice.peerAddress[5-i] = peerAddress[i];
for(int i=0; i<16; i++) {
addDevice.peerIRK[15-i] = peerIrk[i];
addDevice.localIRK[15-i] = localIrk[i];
}
#ifdef _BLE_TRACE_
Serial.print("ADDTYPE :");
btct.printBytes(&addDevice.peerAddressType,1);
Serial.print("adddddd :");
btct.printBytes(addDevice.peerAddress,6);
Serial.print("Peer IRK :");
btct.printBytes(addDevice.peerIRK,16);
Serial.print("localIRK :");
btct.printBytes(addDevice.localIRK,16);
#endif
sendCommand(OGF_LE_CTL << 10 | 0x27, sizeof(addDevice), &addDevice);
leStartResolvingAddresses();
}
int HCIClass::leStopResolvingAddresses(){
uint8_t enable = 0;
return HCI.sendCommand(OGF_LE_CTL << 10 | 0x2D, 1,&enable); // Disable address resolution
}
int HCIClass::leStartResolvingAddresses(){
uint8_t enable = 1;
return HCI.sendCommand(OGF_LE_CTL << 10 | 0x2D, 1,&enable); // Disable address resolution
}
int HCIClass::leReadPeerResolvableAddress(uint8_t peerAddressType, uint8_t* peerIdentityAddress, uint8_t* peerResolvableAddress){
(void)peerResolvableAddress;
struct __attribute__ ((packed)) Request {
uint8_t addressType;
uint8_t identityAddress[6];
} request;
request.addressType = peerAddressType;
for(int i=0; i<6; i++) request.identityAddress[5-i] = peerIdentityAddress[i];
int res = sendCommand(OGF_LE_CTL << 10 | 0x2B, sizeof(request), &request);
#ifdef _BLE_TRACE_
Serial.print("res: 0x");
Serial.println(res, HEX);
if(res==0){
struct __attribute__ ((packed)) Response {
uint8_t status;
uint8_t peerResolvableAddress[6];
} *response = (Response*)_cmdResponse;
Serial.print("Address resolution status: 0x");
Serial.println(response->status, HEX);
Serial.print("peer resolvable address: ");
btct.printBytes(response->peerResolvableAddress,6);
}
#endif
return res;
}
void HCIClass::writeLK(uint8_t peerAddress[], uint8_t LK[]){
struct __attribute__ ((packed)) StoreLK {
uint8_t nKeys;
uint8_t BD_ADDR[6];
uint8_t LTK[16];
} storeLK;
storeLK.nKeys = 1;
memcpy(storeLK.BD_ADDR, peerAddress, 6);
for(int i=0; i<16; i++) storeLK.LTK[15-i] = LK[i];
HCI.sendCommand(OGF_HOST_CTL << 10 | 0x11, sizeof(storeLK), &storeLK);
}
void HCIClass::readStoredLKs(){
uint8_t BD_ADDR[6];
readStoredLK(BD_ADDR, 1);
}
int HCIClass::readStoredLK(uint8_t BD_ADDR[], uint8_t read_all ){
struct __attribute__ ((packed)) Request {
uint8_t BD_ADDR[6];
uint8_t read_a;
} request = {{0},0};
for(int i=0; i<6; i++) request.BD_ADDR[5-i] = BD_ADDR[i];
request.read_a = read_all;
return sendCommand(OGF_HOST_CTL << 10 | 0xD, sizeof(request), &request);
}
int HCIClass::tryResolveAddress(uint8_t* BDAddr, uint8_t* address){
bool foundMatch = false;
if(HCI._getIRKs!=0){
uint8_t nIRKs = 0;
uint8_t** BDAddrType = new uint8_t*;
uint8_t*** BADDRs = new uint8_t**;
uint8_t*** IRKs = new uint8_t**;
if(!HCI._getIRKs(&nIRKs, BDAddrType, BADDRs, IRKs)){
#ifdef _BLE_TRACE_
Serial.println("error getting IRKs.");
#endif
}
for(int i=0; i= _maxPkt) {
poll();
}
struct __attribute__ ((packed)) HCIACLHdr {
uint8_t pktType;
uint16_t handle;
uint16_t dlen;
uint16_t plen;
uint16_t cid;
} aclHdr = { HCI_ACLDATA_PKT, handle, uint8_t(plen + 4), plen, cid };
uint8_t txBuffer[sizeof(aclHdr) + plen];
memcpy(txBuffer, &aclHdr, sizeof(aclHdr));
memcpy(&txBuffer[sizeof(aclHdr)], data, plen);
if (_debug) {
dumpPkt("HCI ACLDATA TX -> ", sizeof(aclHdr) + plen, txBuffer);
}
#ifdef _BLE_TRACE_
Serial.print("Data tx -> ");
for(int i=0; i< sizeof(aclHdr) + plen;i++){
Serial.print(" 0x");
Serial.print(txBuffer[i],HEX);
}
Serial.println(".");
#endif
_pendingPkt++;
HCITransport.write(txBuffer, sizeof(aclHdr) + plen);
return 0;
}
int HCIClass::disconnect(uint16_t handle)
{
struct __attribute__ ((packed)) HCIDisconnectData {
uint16_t handle;
uint8_t reason;
} disconnectData = { handle, HCI_OE_USER_ENDED_CONNECTION };
return sendCommand(OGF_LINK_CTL << 10 | OCF_DISCONNECT, sizeof(disconnectData), &disconnectData);
}
void HCIClass::debug(Stream& stream)
{
_debug = &stream;
}
void HCIClass::noDebug()
{
_debug = NULL;
}
int HCIClass::sendCommand(uint16_t opcode, uint8_t plen, void* parameters)
{
struct __attribute__ ((packed)) {
uint8_t pktType;
uint16_t opcode;
uint8_t plen;
} pktHdr = {HCI_COMMAND_PKT, opcode, plen};
uint8_t txBuffer[sizeof(pktHdr) + plen];
memcpy(txBuffer, &pktHdr, sizeof(pktHdr));
memcpy(&txBuffer[sizeof(pktHdr)], parameters, plen);
if (_debug) {
dumpPkt("HCI COMMAND TX -> ", sizeof(pktHdr) + plen, txBuffer);
}
#ifdef _BLE_TRACE_
Serial.print("Command tx -> ");
for(int i=0; i< sizeof(pktHdr) + plen;i++){
Serial.print(" 0x");
Serial.print(txBuffer[i],HEX);
}
Serial.println("");
#endif
HCITransport.write(txBuffer, sizeof(pktHdr) + plen);
_cmdCompleteOpcode = 0xffff;
_cmdCompleteStatus = -1;
for (unsigned long start = millis(); _cmdCompleteOpcode != opcode && millis() < (start + 1000);) {
poll();
}
return _cmdCompleteStatus;
}
void HCIClass::handleAclDataPkt(uint8_t /*plen*/, uint8_t pdata[])
{
struct __attribute__ ((packed)) HCIACLHdr {
uint16_t connectionHandleWithFlags;
uint16_t dlen; // dlen + 4 = plen (dlen is the size of the ACL SDU)
} *aclHeader = (HCIACLHdr*)pdata;
uint8_t pbFlag = (aclHeader->connectionHandleWithFlags & 0x3000) >> 12;
uint16_t connectionHandle = aclHeader->connectionHandleWithFlags & 0x0fff;
uint8_t *aclSdu = &pdata[sizeof(HCIACLHdr)];
#ifdef _BLE_TRACE_
uint8_t bcFlag = (aclHeader->connectionHandleWithFlags & 0xc000) >> 14;
Serial.print("Acl packet bcFlag = ");
Serial.print(bcFlag, BIN);
Serial.print(" pbFlag = ");
Serial.print(pbFlag, BIN);
Serial.print(" connectionHandle = ");
Serial.print(connectionHandle, HEX);
Serial.print(" dlen = ");
Serial.println(aclHeader->dlen, DEC);
#endif
// Pointer to the L2CAP PDU (might be reconstructed from multiple fragments)
uint8_t *l2CapPdu;
uint8_t l2CapPduSize;
if (pbFlag == 0b10) {
// "First automatically flushable packet" = Start of our L2CAP PDU
l2CapPdu = aclSdu;
l2CapPduSize = aclHeader->dlen;
} else if (pbFlag == 0b01) {
// "Continuing Fragment" = Continued L2CAP PDU
#ifdef _BLE_TRACE_
Serial.print("Continued packet. Appending to L2CAP PDU buffer (previously ");
Serial.print(_l2CapPduBufferSize, DEC);
Serial.println(" bytes in buffer)");
#endif
// If we receive a fragment, we always need to append it to the L2CAP PDU buffer
memcpy(&_l2CapPduBuffer[_l2CapPduBufferSize], aclSdu, aclHeader->dlen);
_l2CapPduBufferSize += aclHeader->dlen;
l2CapPdu = _l2CapPduBuffer;
l2CapPduSize = _l2CapPduBufferSize;
} else {
// I don't think other values are allowed for BLE
#ifdef _BLE_TRACE_
Serial.println("Invalid pbFlag, discarding packet");
#endif
return;
}
// We now have a valid L2CAP header in l2CapPdu and can parse the headers
struct __attribute__ ((packed)) HCIL2CapHdr {
uint16_t len; // size of the L2CAP SDU
uint16_t cid;
} *l2CapHeader = (HCIL2CapHdr*)l2CapPdu;
#ifdef _BLE_TRACE_
Serial.print("Received ");
Serial.print(l2CapPduSize - 4, DEC);
Serial.print("B/");
Serial.print(l2CapHeader->len, DEC);
Serial.print("B of the L2CAP SDU. CID = ");
Serial.println(l2CapHeader->cid, HEX);
#endif
// -4 because the buffer is the L2CAP PDU (with L2CAP header). The len field is only the L2CAP SDU (without L2CAP header).
if (l2CapPduSize - 4 != l2CapHeader->len) {
#ifdef _BLE_TRACE_
Serial.println("L2CAP SDU incomplete");
#endif
// If this is a first packet, we have not copied it into the buffer yet
if (pbFlag == 0b10) {
#ifdef _BLE_TRACE_
Serial.println("Storing first packet to L2CAP PDU buffer");
if (_l2CapPduBufferSize != 0) {
Serial.print("Warning: Discarding ");
Serial.print(_l2CapPduBufferSize, DEC);
Serial.println(" bytes from buffer");
}
#endif
memcpy(_l2CapPduBuffer, l2CapPdu, l2CapPduSize);
_l2CapPduBufferSize = l2CapPduSize;
}
// We need to wait for the missing parts of the L2CAP SDU
return;
}
#ifdef _BLE_TRACE_
Serial.println("L2CAP SDU complete");
#endif
if (l2CapHeader->cid == ATT_CID) {
#ifdef _BLE_TRACE_
Serial.println("CID: ATT");
#endif
ATT.handleData(connectionHandle, l2CapHeader->len, &l2CapPdu[sizeof(HCIL2CapHdr)]);
} else if (l2CapHeader->cid == SIGNALING_CID) {
#ifdef _BLE_TRACE_
Serial.println("CID: SIGNALING");
#endif
L2CAPSignaling.handleData(connectionHandle, l2CapHeader->len, &l2CapPdu[sizeof(HCIL2CapHdr)]);
} else if (l2CapHeader->cid == SECURITY_CID) {
// Security manager
#ifdef _BLE_TRACE_
Serial.println("CID: SECURITY");
#endif
L2CAPSignaling.handleSecurityData(connectionHandle, l2CapHeader->len, &l2CapPdu[sizeof(HCIL2CapHdr)]);
} else {
struct __attribute__ ((packed)) {
uint8_t op;
uint8_t id;
uint16_t length;
uint16_t reason;
uint16_t localCid;
uint16_t remoteCid;
} l2capRejectCid= { 0x01, 0x00, 0x006, 0x0002, l2CapHeader->cid, 0x0000 };
#ifdef _BLE_TRACE_
Serial.println("Rejecting packet cid");
#endif
sendAclPkt(connectionHandle, 0x0005, sizeof(l2capRejectCid), &l2capRejectCid);
}
// We have processed everything in the buffer. Discard the contents.
_l2CapPduBufferSize = 0;
}
void HCIClass::handleNumCompPkts(uint16_t /*handle*/, uint16_t numPkts)
{
if (numPkts && _pendingPkt > numPkts) {
_pendingPkt -= numPkts;
} else {
_pendingPkt = 0;
}
}
void HCIClass::handleEventPkt(uint8_t /*plen*/, uint8_t pdata[])
{
struct __attribute__ ((packed)) HCIEventHdr {
uint8_t evt;
uint8_t plen;
} *eventHdr = (HCIEventHdr*)pdata;
#ifdef _BLE_TRACE_
Serial.print("HCI event: ");
Serial.println(eventHdr->evt, HEX);
#endif
if (eventHdr->evt == EVT_DISCONN_COMPLETE)
{
struct __attribute__ ((packed)) DisconnComplete {
uint8_t status;
uint16_t handle;
uint8_t reason;
} *disconnComplete = (DisconnComplete*)&pdata[sizeof(HCIEventHdr)];
ATT.removeConnection(disconnComplete->handle, disconnComplete->reason);
L2CAPSignaling.removeConnection(disconnComplete->handle, disconnComplete->reason);
if (GAP.advertising())
{
HCI.leSetAdvertiseEnable(0x01);
}
}
else if (eventHdr->evt == EVT_ENCRYPTION_CHANGE)
{
struct __attribute__ ((packed)) EncryptionChange {
uint8_t status;
uint16_t connectionHandle;
uint8_t enabled;
} *encryptionChange = (EncryptionChange*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.println("[Info] Encryption changed");
Serial.print("status : ");
btct.printBytes(&encryptionChange->status,1);
Serial.print("handle : ");
btct.printBytes((uint8_t*)&encryptionChange->connectionHandle,2);
Serial.print("enabled: ");
btct.printBytes(&encryptionChange->enabled,1);
#endif
if(encryptionChange->enabled>0){
// 0001 1110
if((ATT.getPeerEncryption(encryptionChange->connectionHandle)&PEER_ENCRYPTION::PAIRING_REQUEST)>0){
if(ATT.localKeyDistribution.EncKey()){
#ifdef _BLE_TRACE_
Serial.println("Enc key set but should be ignored");
#endif
}else{
#ifdef _BLE_TRACE_
Serial.println("No enc key distribution");
#endif
}
// From page 1681 bluetooth standard - order matters
if(ATT.localKeyDistribution.IdKey()){
/// We shall distribute IRK and address using identity information
{
uint8_t response[17];
response[0] = CONNECTION_IDENTITY_INFORMATION; // Identity information.
for(int i=0; i<16; i++) response[16-i] = ATT.localIRK[i];
HCI.sendAclPkt(encryptionChange->connectionHandle, SECURITY_CID, sizeof(response), response);
#ifdef _BLE_TRACE_
Serial.println("Distribute ID Key");
#endif
}
{
uint8_t response[8];
response[0] = CONNECTION_IDENTITY_ADDRESS; // Identity address information
response[1] = 0x00; // Static local address
for(int i=0; i<6; i++) response[7-i] = HCI.localAddr[i];
HCI.sendAclPkt(encryptionChange->connectionHandle, SECURITY_CID, sizeof(response), response);
}
}
if(ATT.localKeyDistribution.SignKey()){
/// We shall distribut CSRK
#ifdef _BLE_TRACE_
Serial.println("We shall distribute CSRK // not implemented");
#endif
}else{
// Serial.println("We don't want to distribute CSRK");
}
if(ATT.localKeyDistribution.LinkKey()){
#ifdef _BLE_TRACE_
Serial.println("We would like to use LTK to generate BR/EDR // not implemented");
#endif
}
}else{
#ifdef _BLE_TRACE_
Serial.println("Reconnection, not pairing so no keys");
Serial.println(ATT.getPeerEncryption(encryptionChange->connectionHandle),HEX);
#endif
}
ATT.setPeerEncryption(encryptionChange->connectionHandle, PEER_ENCRYPTION::ENCRYPTED_AES);
if(ATT.writeBufferSize > 0){
ATT.processWriteBuffer();
}
if(ATT.holdBufferSize>0){
#ifdef _BLE_TRACE_
Serial.print("Sending queued response size: ");
Serial.println(ATT.holdBufferSize);
#endif
HCI.sendAclPkt(encryptionChange->connectionHandle, ATT_CID, ATT.holdBufferSize, ATT.holdBuffer);
ATT.holdBufferSize = 0;
}
}else{
ATT.setPeerEncryption(encryptionChange->connectionHandle, PEER_ENCRYPTION::NO_ENCRYPTION);
}
}
else if (eventHdr->evt == EVT_CMD_COMPLETE)
{
struct __attribute__ ((packed)) CmdComplete {
uint8_t ncmd;
uint16_t opcode;
uint8_t status;
} *cmdCompleteHeader = (CmdComplete*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.print("E ncmd: 0x");
Serial.println(cmdCompleteHeader->ncmd,HEX);
Serial.print("E opcode: 0x");
Serial.println(cmdCompleteHeader->opcode, HEX);
Serial.print("E status: 0x");
Serial.println(cmdCompleteHeader->status, HEX);
#endif
_cmdCompleteOpcode = cmdCompleteHeader->opcode;
_cmdCompleteStatus = cmdCompleteHeader->status;
_cmdResponseLen = pdata[1] - sizeof(CmdComplete);
_cmdResponse = &pdata[sizeof(HCIEventHdr) + sizeof(CmdComplete)];
}
else if (eventHdr->evt == EVT_CMD_STATUS)
{
struct __attribute__ ((packed)) CmdStatus {
uint8_t status;
uint8_t ncmd;
uint16_t opcode;
} *cmdStatusHeader = (CmdStatus*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.print("F n cmd: 0x");
Serial.println(cmdStatusHeader->ncmd, HEX);
Serial.print("F status: 0x");
Serial.println(cmdStatusHeader->status, HEX);
Serial.print("F opcode: 0x");
Serial.println(cmdStatusHeader->opcode, HEX);
#endif
_cmdCompleteOpcode = cmdStatusHeader->opcode;
_cmdCompleteStatus = cmdStatusHeader->status;
_cmdResponseLen = 0;
}
else if (eventHdr->evt == EVT_NUM_COMP_PKTS)
{
uint8_t numHandles = pdata[sizeof(HCIEventHdr)];
uint16_t* data = (uint16_t*)&pdata[sizeof(HCIEventHdr) + sizeof(numHandles)];
for (uint8_t i = 0; i < numHandles; i++) {
handleNumCompPkts(data[0], data[1]);
#ifdef _BLE_TRACE_
Serial.print("Outstanding packets: ");
Serial.println(_pendingPkt);
Serial.print("Data[0]: 0x");
Serial.println(data[0]);
Serial.print("Data[1]: 0x");
Serial.println(data[1]);
#endif
data += 2;
}
}
else if(eventHdr->evt == 0x10)
{
#ifdef _BLE_TRACE_
struct __attribute__ ((packed)) CmdHardwareError {
uint8_t hardwareCode;
} *cmdHardwareError = (CmdHardwareError*)&pdata[sizeof(HCIEventHdr)];
Serial.print("Bluetooth hardware error.");
Serial.print(" Code: 0x");
Serial.println(cmdHardwareError->hardwareCode, HEX);
#endif
}
else if (eventHdr->evt == EVT_LE_META_EVENT)
{
struct __attribute__ ((packed)) LeMetaEventHeader {
uint8_t subevent;
} *leMetaHeader = (LeMetaEventHeader*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.print("\tSubEvent: 0x");
Serial.println(leMetaHeader->subevent,HEX);
#endif
switch((LE_META_EVENT)leMetaHeader->subevent){
case ENHANCED_CONN_COMPLETE:{
struct __attribute__ ((packed)) EvtLeConnectionComplete {
uint8_t status;
uint16_t handle;
uint8_t role;
uint8_t peerBdaddrType;
uint8_t peerBdaddr[6];
uint8_t localResolvablePrivateAddress[6];
uint8_t peerResolvablePrivateAddress[6];
uint16_t interval;
uint16_t latency;
uint16_t supervisionTimeout;
uint8_t masterClockAccuracy;
} *leConnectionComplete = (EvtLeConnectionComplete*)&pdata[sizeof(HCIEventHdr) + sizeof(LeMetaEventHeader)];
if (leConnectionComplete->status == 0x00) {
ATT.addConnection(leConnectionComplete->handle,
leConnectionComplete->role,
leConnectionComplete->peerBdaddrType,
leConnectionComplete->peerBdaddr,
leConnectionComplete->interval,
leConnectionComplete->latency,
leConnectionComplete->supervisionTimeout,
leConnectionComplete->masterClockAccuracy);
L2CAPSignaling.addConnection(leConnectionComplete->handle,
leConnectionComplete->role,
leConnectionComplete->peerBdaddrType,
leConnectionComplete->peerBdaddr,
leConnectionComplete->interval,
leConnectionComplete->latency,
leConnectionComplete->supervisionTimeout,
leConnectionComplete->masterClockAccuracy);
}
// uint8_t address[6];
// uint8_t BDAddr[6];
// for(int i=0; i<6; i++) BDAddr[5-i] = leConnectionComplete->peerBdaddr[i];
// leReadPeerResolvableAddress(leConnectionComplete->peerBdaddrType,BDAddr,address);
// Serial.print("Resolving address: ");
// btct.printBytes(BDAddr, 6);
// Serial.print("BT answer : ");
// btct.printBytes(address, 6);
#ifdef _BLE_TRACE_
Serial.print("Resolved peer : ");
btct.printBytes(leConnectionComplete->peerResolvablePrivateAddress,6);
Serial.print("Resolved local : ");
btct.printBytes(leConnectionComplete->localResolvablePrivateAddress,6);
#endif
break;
}
case CONN_COMPLETE:{
struct __attribute__ ((packed)) EvtLeConnectionComplete {
uint8_t status;
uint16_t handle;
uint8_t role;
uint8_t peerBdaddrType;
uint8_t peerBdaddr[6];
uint16_t interval;
uint16_t latency;
uint16_t supervisionTimeout;
uint8_t masterClockAccuracy;
} *leConnectionComplete = (EvtLeConnectionComplete*)&pdata[sizeof(HCIEventHdr) + sizeof(LeMetaEventHeader)];
if (leConnectionComplete->status == 0x00) {
ATT.addConnection(leConnectionComplete->handle,
leConnectionComplete->role,
leConnectionComplete->peerBdaddrType,
leConnectionComplete->peerBdaddr,
leConnectionComplete->interval,
leConnectionComplete->latency,
leConnectionComplete->supervisionTimeout,
leConnectionComplete->masterClockAccuracy);
L2CAPSignaling.addConnection(leConnectionComplete->handle,
leConnectionComplete->role,
leConnectionComplete->peerBdaddrType,
leConnectionComplete->peerBdaddr,
leConnectionComplete->interval,
leConnectionComplete->latency,
leConnectionComplete->supervisionTimeout,
leConnectionComplete->masterClockAccuracy);
}
// leReadPeerResolvableAddress(leConnectionComplete->peerBdaddrType,BDAddr,address);
// Serial.print("Resolving address: ");
// btct.printBytes(BDAddr, 6);
// Serial.print("BT answer : ");
// btct.printBytes(address, 6);
break;
}
case ADVERTISING_REPORT:{
struct __attribute__ ((packed)) EvtLeAdvertisingReport {
uint8_t status;
uint8_t type;
uint8_t peerBdaddrType;
uint8_t peerBdaddr[6];
uint8_t eirLength;
uint8_t eirData[31];
} *leAdvertisingReport = (EvtLeAdvertisingReport*)&pdata[sizeof(HCIEventHdr) + sizeof(LeMetaEventHeader)];
if(leAdvertisingReport->eirLength > sizeof(leAdvertisingReport->eirData)){
return ;
}
if (leAdvertisingReport->status == 0x01) {
// last byte is RSSI
int8_t rssi = leAdvertisingReport->eirData[leAdvertisingReport->eirLength];
GAP.handleLeAdvertisingReport(leAdvertisingReport->type,
leAdvertisingReport->peerBdaddrType,
leAdvertisingReport->peerBdaddr,
leAdvertisingReport->eirLength,
leAdvertisingReport->eirData,
rssi);
}
break;
}
case LONG_TERM_KEY_REQUEST:{
struct __attribute__ ((packed)) LTKRequest
{
uint8_t subEventCode;
uint16_t connectionHandle;
uint8_t randomNumber[8];
uint8_t encryptedDiversifier[2];
} *ltkRequest = (LTKRequest*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.println("LTK request received");
Serial.print("Connection Handle: ");
btct.printBytes((uint8_t*)<kRequest->connectionHandle,2);
Serial.print("Random Number : ");
btct.printBytes(ltkRequest->randomNumber,8);
Serial.print("EDIV : ");
btct.printBytes(ltkRequest->encryptedDiversifier,2);
#endif
// Load our LTK for this connection.
uint8_t peerAddr[7];
uint8_t resolvableAddr[6];
uint8_t foundLTK;
ATT.getPeerAddrWithType(ltkRequest->connectionHandle, peerAddr);
if((ATT.getPeerEncryption(ltkRequest->connectionHandle) & PEER_ENCRYPTION::PAIRING_REQUEST)>0){
// Pairing request - LTK is one in buffer already
foundLTK = 1;
}else{
if(ATT.getPeerResolvedAddress(ltkRequest->connectionHandle, resolvableAddr)){
foundLTK = getLTK(resolvableAddr, HCI.LTK);
}else{
foundLTK = getLTK(&peerAddr[1], HCI.LTK);
}
}
// } //2d
// Send our LTK back
if(foundLTK){
struct __attribute__ ((packed)) LTKReply
{
uint16_t connectionHandle;
uint8_t LTK[16];
} ltkReply = {0,0};
ltkReply.connectionHandle = ltkRequest->connectionHandle;
for(int i=0; i<16; i++) ltkReply.LTK[15-i] = HCI.LTK[i];
int result = sendCommand(OGF_LE_CTL << 10 | LE_COMMAND::LONG_TERM_KEY_REPLY,sizeof(ltkReply), <kReply);
#ifdef _BLE_TRACE_
Serial.println("Sending LTK as: ");
btct.printBytes(ltkReply.LTK,16);
#endif
if(result == 0){
struct __attribute__ ((packed)) LTKReplyResult
{
uint8_t status;
uint16_t connectionHandle;
} ltkReplyResult = {0,0};
memcpy(<kReplyResult, _cmdResponse, 3);
#ifdef _BLE_TRACE_
Serial.println("LTK send success");
Serial.print("status : ");
btct.printBytes(<kReplyResult.status,1);
Serial.print("Conn Handle: ");
btct.printBytes((uint8_t*)<kReplyResult.connectionHandle,2);
#endif
}else{
#ifdef _BLE_TRACE_
Serial.print("Failed to send LTK...: ");
btct.printBytes((uint8_t*)&result,2);
#endif
}
}else{
/// do LTK rejection
#ifdef _BLE_TRACE_
Serial.println("LTK not found, rejecting");
#endif
sendCommand(OGF_LE_CTL << 10 | LE_COMMAND::LONG_TERM_KEY_NEGATIVE_REPLY,2, <kRequest->connectionHandle);
}
break;
}
case REMOTE_CONN_PARAM_REQ:{
struct __attribute__ ((packed)) RemoteConnParamReq {
uint8_t subEventCode;
uint16_t connectionHandle;
uint16_t intervalMin;
uint16_t intervalMax;
uint16_t latency;
uint16_t timeOut;
} *remoteConnParamReq = (RemoteConnParamReq*)&pdata[sizeof(HCIEventHdr)];
#ifdef _BLE_TRACE_
Serial.println("--- Remtoe conn param req");
Serial.print("Handle : ");
btct.printBytes((uint8_t*)&remoteConnParamReq->connectionHandle,2);
Serial.print("Interval min: ");
btct.printBytes((uint8_t*)&remoteConnParamReq->intervalMin,2);
Serial.print("Interval max: ");
btct.printBytes((uint8_t*)&remoteConnParamReq->intervalMax,2);
Serial.print("Latency : ");
btct.printBytes((uint8_t*)&remoteConnParamReq->latency,2);
Serial.print("Timeout : ");
btct.printBytes((uint8_t*)&remoteConnParamReq->timeOut,2);
#endif
struct __attribute__ ((packed)) RemoteConnParamReqReply {
uint16_t connectionHandle;
uint16_t intervalMin;
uint16_t intervalMax;
uint16_t latency;
uint16_t timeOut;
uint16_t minLength;
uint16_t maxLength;
} remoteConnParamReqReply;
memcpy(&remoteConnParamReqReply, &remoteConnParamReq->connectionHandle, sizeof(RemoteConnParamReq)-1);
remoteConnParamReqReply.minLength = 0x000F;
remoteConnParamReqReply.maxLength = 0x0FFF;
sendCommand(OGF_LE_CTL << 10 | 0x20, sizeof(RemoteConnParamReqReply), &remoteConnParamReqReply);
break;
}
case READ_LOCAL_P256_COMPLETE:{
struct __attribute__ ((packed)) EvtReadLocalP256Complete{
uint8_t subEventCode;
uint8_t status;
uint8_t localPublicKey[64];
} *evtReadLocalP256Complete = (EvtReadLocalP256Complete*)&pdata[sizeof(HCIEventHdr)];
if(evtReadLocalP256Complete->status == 0x0){
#ifdef _BLE_TRACE_
Serial.println("Key read success");
#endif
struct __attribute__ ((packed)) PairingPublicKey
{
uint8_t code;
uint8_t publicKey[64];
} pairingPublicKey = {CONNECTION_PAIRING_PUBLIC_KEY,0};
memcpy(pairingPublicKey.publicKey,evtReadLocalP256Complete->localPublicKey,64);
memcpy(localPublicKeyBuffer, evtReadLocalP256Complete->localPublicKey,64);
// Send the local public key to the remote
uint16_t connectionHandle = ATT.getPeerEncrptingConnectionHandle();
if(connectionHandle>ATT_MAX_PEERS){
#ifdef _BLE_TRACE_
Serial.println("failed to find connection handle");
#endif
break;
}
HCI.sendAclPkt(connectionHandle,SECURITY_CID,sizeof(PairingPublicKey),&pairingPublicKey);
uint8_t encryption = ATT.getPeerEncryption(connectionHandle) | PEER_ENCRYPTION::SENT_PUBKEY;
ATT.setPeerEncryption(connectionHandle, encryption);
uint8_t Z = 0;
HCI.leRand(Nb);
HCI.leRand(&Nb[8]);
#ifdef _BLE_TRACE_
Serial.print("nb: ");
btct.printBytes(Nb, 16);
#endif
struct __attribute__ ((packed)) F4Params
{
uint8_t U[32];
uint8_t V[32];
uint8_t Z;
} f4Params = {{0},{0},Z};
for(int i=0; i<32; i++){
f4Params.U[31-i] = pairingPublicKey.publicKey[i];
f4Params.V[31-i] = HCI.remotePublicKeyBuffer[i];
}
struct __attribute__ ((packed)) PairingConfirm
{
uint8_t code;
uint8_t cb[16];
} pairingConfirm = {CONNECTION_PAIRING_CONFIRM,0};
btct.AES_CMAC(Nb,(unsigned char *)&f4Params,sizeof(f4Params),pairingConfirm.cb);
#ifdef _BLE_TRACE_
Serial.print("cb: ");
btct.printBytes(pairingConfirm.cb, 16);
#endif
uint8_t cb_temp[sizeof(pairingConfirm.cb)];
for(unsigned int i=0; istatus,HEX);
for(int i=0; i<64; i++){
Serial.print(" 0x");
Serial.print(evtReadLocalP256Complete->localPublicKey[i],HEX);
}
Serial.println(".");
#endif
}
break;
}
case GENERATE_DH_KEY_COMPLETE:{
struct __attribute__ ((packed)) EvtLeDHKeyComplete{
uint8_t subEventCode;
uint8_t status;
uint8_t DHKey[32];
} *evtLeDHKeyComplete = (EvtLeDHKeyComplete*)&pdata[sizeof(HCIEventHdr)];
if(evtLeDHKeyComplete->status == 0x0){
#ifdef _BLE_TRACE_
Serial.println("DH key generated");
#endif
uint16_t connectionHandle = ATT.getPeerEncrptingConnectionHandle();
if(connectionHandle>ATT_MAX_PEERS){
#ifdef _BLE_TRACE_
Serial.println("Failed to find connection handle DH key check");
#endif
break;
}
for(int i=0; i<32; i++) DHKey[31-i] = evtLeDHKeyComplete->DHKey[i];
#ifdef _BLE_TRACE_
Serial.println("Stored our DHKey:");
btct.printBytes(DHKey,32);
#endif
uint8_t encryption = ATT.getPeerEncryption(connectionHandle) | PEER_ENCRYPTION::DH_KEY_CALULATED;
ATT.setPeerEncryption(connectionHandle, encryption);
if((encryption & PEER_ENCRYPTION::RECEIVED_DH_CHECK) > 0){
#ifdef _BLE_TRACE_
Serial.println("Received DHKey check already so calculate f5, f6 now.");
#endif
L2CAPSignaling.smCalculateLTKandConfirm(connectionHandle, HCI.remoteDHKeyCheckBuffer);
}else{
#ifdef _BLE_TRACE_
Serial.println("Waiting on other DHKey check before calculating.");
#endif
}
}else{
#ifdef _BLE_TRACE_
Serial.print("Key generation error: 0x");
Serial.println(evtLeDHKeyComplete->status, HEX);
#endif
}
break;
}
default:
{
#ifdef _BLE_TRACE_
Serial.println("[Info] Unhandled meta event");
#endif
}
}
}else{
#ifdef _BLE_TRACE_
Serial.println("[Info] Unhandled event");
#endif
}
}
int HCIClass::leEncrypt(uint8_t* key, uint8_t* plaintext, uint8_t* status, uint8_t* ciphertext){
(void)status;
struct __attribute__ ((packed)) LeEncryptCommand
{
uint8_t key[16];
uint8_t plaintext[16];
} leEncryptCommand = {{0},{0}};
for(int i=0; i<16; i++){
leEncryptCommand.key[15-i] = key[i];
leEncryptCommand.plaintext[15-i] = plaintext[i];
}
int res = sendCommand(OGF_LE_CTL << 10 | LE_COMMAND::ENCRYPT, 32, &leEncryptCommand);
if(res == 0){
#ifdef _BLE_TRACE_
Serial.print("Copying from command Response length: ");
Serial.println(_cmdResponseLen);
Serial.println(".");
for(int i=0; i<20; i++){
Serial.print(" 0x");
Serial.print(_cmdResponse[i],HEX);
}
Serial.println(".");
#endif
for(int i=0; i<16; i++){
ciphertext[15-i] = _cmdResponse[i];
}
return 1;
}
#ifdef _BLE_TRACE_
Serial.print("Error with AES: 0x");
Serial.println(res, HEX);
#endif
return res;
}
int HCIClass::leRand(uint8_t rand[]){
int res = sendCommand(OGF_LE_CTL << 10 | LE_COMMAND::RANDOM);
if(res == 0){
memcpy(rand,_cmdResponse, 8); /// backwards but it's a random number
}
return res;
}
int HCIClass::getLTK(uint8_t* address, uint8_t* LTK){
if(_getLTK!=0){
return _getLTK(address, LTK);
}else{
return 0;
}
}
int HCIClass::storeIRK(uint8_t* address, uint8_t* IRK){
if(_storeIRK!=0){
return _storeIRK(address, IRK);
}else{
return 0;
}
}
int HCIClass::storeLTK(uint8_t* address, uint8_t* LTK){
if(_storeLTK!=0){
return _storeLTK(address, LTK);
}else{
return 0;
}
}
uint8_t HCIClass::localIOCap(){
if(_displayCode!=0){
/// We have a display
if(_binaryConfirmPairing!=0){
return IOCAP_DISPLAY_YES_NO;
}else{
return IOCAP_DISPLAY_ONLY;
}
}else{
// We have no display
return IOCAP_NO_INPUT_NO_OUTPUT;
}
}
/// Stub function to generate parameters for local authreq
AuthReq HCIClass::localAuthreq(){
// If get, set, IRK, LTK all set then we can bond.
AuthReq local = AuthReq();
if(_storeIRK!=0 && _storeLTK!=0 && _getLTK!=0 && _getIRKs!=0){
local.setBonding(true);
}
local.setSC(true);
local.setMITM(true);
local.setCT2(true);
return LOCAL_AUTHREQ;
}
void HCIClass::dumpPkt(const char* prefix, uint8_t plen, uint8_t pdata[])
{
if (_debug) {
_debug->print(prefix);
for (uint8_t i = 0; i < plen; i++) {
byte b = pdata[i];
if (b < 16) {
_debug->print("0");
}
_debug->print(b, HEX);
}
_debug->println();
_debug->flush();
}
}
#if !defined(FAKE_HCI)
HCIClass HCIObj;
HCIClass& HCI = HCIObj;
#endif
================================================
FILE: src/utility/HCI.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_H_
#define _HCI_H_
#include
#include "bitDescriptions.h"
#include "L2CAPSignaling.h"
#define OGF_LINK_CTL 0x01
#define OGF_HOST_CTL 0x03
#define OGF_INFO_PARAM 0x04
#define OGF_STATUS_PARAM 0x05
#define OGF_LE_CTL 0x08
enum LE_COMMAND {
ENCRYPT = 0x0017,
RANDOM = 0x0018,
LONG_TERM_KEY_REPLY = 0x001A,
LONG_TERM_KEY_NEGATIVE_REPLY = 0x001B,
READ_LOCAL_P256 = 0x0025,
GENERATE_DH_KEY_V1 = 0x0026,
GENERATE_DH_KEY_V2 = 0x005E
};
enum LE_META_EVENT {
CONN_COMPLETE = 0x01,
ADVERTISING_REPORT = 0x02,
LONG_TERM_KEY_REQUEST = 0x05,
REMOTE_CONN_PARAM_REQ = 0x06,
READ_LOCAL_P256_COMPLETE = 0x08,
GENERATE_DH_KEY_COMPLETE = 0x09,
ENHANCED_CONN_COMPLETE = 0x0A,
};
String metaEventToString(LE_META_EVENT event);
String commandToString(LE_COMMAND command);
class HCIClass {
public:
HCIClass();
virtual ~HCIClass();
virtual int begin();
virtual void end();
virtual void poll();
virtual void poll(unsigned long timeout);
virtual int reset();
virtual int readLocalVersion(uint8_t& hciVer, uint16_t& hciRev, uint8_t& lmpVer,
uint16_t& manufacturer, uint16_t& lmpSubVer);
virtual int readBdAddr(uint8_t addr[6]);
virtual int readBdAddr();
virtual int readRssi(uint16_t handle);
virtual int setEventMask(uint64_t eventMask);
virtual int setLeEventMask(uint64_t leEventMask);
virtual int readLeBufferSize(uint16_t& pktLen, uint8_t& maxPkt);
virtual int leSetRandomAddress(uint8_t addr[6]);
virtual int leSetAdvertisingParameters(uint16_t minInterval, uint16_t maxInterval,
uint8_t advType, uint8_t ownBdaddrType,
uint8_t directBdaddrType, uint8_t directBdaddr[6],
uint8_t chanMap,
uint8_t filter);
virtual int leSetAdvertisingData(uint8_t length, uint8_t data[]);
virtual int leSetScanResponseData(uint8_t length, uint8_t data[]);
virtual int leSetAdvertiseEnable(uint8_t enable);
virtual int leSetScanParameters(uint8_t type, uint16_t interval, uint16_t window,
uint8_t ownBdaddrType, uint8_t filter);
virtual int leSetScanEnable(uint8_t enabled, uint8_t duplicates);
virtual int leCreateConn(uint16_t interval, uint16_t window, uint8_t initiatorFilter,
uint8_t peerBdaddrType, uint8_t peerBdaddr[6], uint8_t ownBdaddrType,
uint16_t minInterval, uint16_t maxInterval, uint16_t latency,
uint16_t supervisionTimeout, uint16_t minCeLength, uint16_t maxCeLength);
virtual int leConnUpdate(uint16_t handle, uint16_t minInterval, uint16_t maxInterval,
uint16_t latency, uint16_t supervisionTimeout);
virtual int leCancelConn();
virtual int leEncrypt(uint8_t* Key, uint8_t* plaintext, uint8_t* status, uint8_t* ciphertext);
// Generate a 64 bit random number
virtual int leRand(uint8_t rand[]);
virtual AuthReq localAuthreq();
virtual uint8_t localIOCap();
virtual void saveNewAddress(uint8_t addressType, uint8_t* address, uint8_t* peerIrk, uint8_t* remoteIrk);
virtual void leAddResolvingAddress(uint8_t addressType, uint8_t* address, uint8_t* peerIrk, uint8_t* remoteIrk);
virtual int leStopResolvingAddresses();
virtual int leStartResolvingAddresses();
virtual int leReadPeerResolvableAddress(uint8_t peerAddressType, uint8_t* peerIdentityAddress, uint8_t* peerResolvableAddress);
virtual void readStoredLKs();
virtual int readStoredLK(uint8_t BD_ADDR[], uint8_t read_all = 0);
virtual void writeLK(uint8_t peerAddress[], uint8_t LK[]);
virtual int tryResolveAddress(uint8_t* BDAddr, uint8_t* address);
virtual int sendAclPkt(uint16_t handle, uint8_t cid, uint8_t plen, void* data);
virtual int disconnect(uint16_t handle);
virtual void debug(Stream& stream);
virtual void noDebug();
// TODO: Send command be private again & use ATT implementation of send command within ATT.
virtual int sendCommand(uint16_t opcode, uint8_t plen = 0, void* parameters = NULL);
uint8_t remotePublicKeyBuffer[64];
uint8_t localPublicKeyBuffer[64];
uint8_t remoteDHKeyCheckBuffer[16];
uint8_t Na[16];
uint8_t Nb[16];
uint8_t DHKey[32];
uint8_t localAddr[6];
uint8_t LTK[16];
virtual int getLTK(uint8_t* address, uint8_t* LTK);
virtual int storeLTK(uint8_t* address, uint8_t* LTK);
virtual int storeIRK(uint8_t* address, uint8_t* IRK);
int (*_storeIRK)(uint8_t* address, uint8_t* peerIrk) = 0;
int (*_getIRKs)(uint8_t* nIRKs,uint8_t** BADDR_type, uint8_t*** BADDRs, uint8_t*** IRKs) = 0;
int (*_storeLTK)(uint8_t*, uint8_t*) = 0;
int (*_getLTK)(uint8_t*, uint8_t*) = 0;
void (*_displayCode)(uint32_t confirmationCode) = 0;
bool (*_binaryConfirmPairing)() = 0;
private:
virtual void handleAclDataPkt(uint8_t plen, uint8_t pdata[]);
virtual void handleNumCompPkts(uint16_t handle, uint16_t numPkts);
virtual void handleEventPkt(uint8_t plen, uint8_t pdata[]);
virtual void dumpPkt(const char* prefix, uint8_t plen, uint8_t pdata[]);
Stream* _debug;
int _recvIndex;
uint8_t _recvBuffer[3 + 255];
uint16_t _cmdCompleteOpcode;
int _cmdCompleteStatus;
uint8_t _cmdResponseLen;
uint8_t* _cmdResponse;
uint8_t _maxPkt;
uint8_t _pendingPkt;
uint8_t _l2CapPduBuffer[255];
uint8_t _l2CapPduBufferSize;
};
extern HCIClass& HCI;
#endif
================================================
FILE: src/utility/HCICordioTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ARDUINO_ARCH_MBED) && !defined(TARGET_NANO_RP2040_CONNECT) // && !defined(CORE_CM4)
#include
#include
#include
#include
#if defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)
#include "ble/BLE.h"
#include
#endif
// Parts of this file are based on: https://github.com/ARMmbed/mbed-os-cordio-hci-passthrough/pull/2
// With permission from the Arm Mbed team to re-license
#if CORDIO_ZERO_COPY_HCI
#include
#include
#include
#include
#include
#include
/* avoid many small allocs (and WSF doesn't have smaller buffers) */
#define MIN_WSF_ALLOC (16)
#endif //CORDIO_ZERO_COPY_HCI
#include "HCICordioTransport.h"
#if (MBED_VERSION > MBED_ENCODE_VERSION(6, 2, 0))
#define BLE_NAMESPACE ble
#else
#define BLE_NAMESPACE ble::vendor::cordio
#endif
#include "CordioHCICustomDriver.h"
extern BLE_NAMESPACE::CordioHCIDriver& ble_cordio_get_hci_driver();
extern "C" void hciTrSerialRxIncoming(uint8_t *pBuf, uint8_t len);
namespace BLE_NAMESPACE {
struct CordioHCIHook {
static CordioHCIDriver& getDriver() {
return ble_cordio_get_hci_driver();
}
static CordioHCITransportDriver& getTransportDriver() {
return getDriver()._transport_driver;
}
static void setDataReceivedHandler(void (*handler)(uint8_t*, uint8_t)) {
getTransportDriver().set_data_received_handler(handler);
}
};
}
using BLE_NAMESPACE::CordioHCIHook;
#if CORDIO_ZERO_COPY_HCI
extern uint8_t *SystemHeapStart;
extern uint32_t SystemHeapSize;
void init_wsf(BLE_NAMESPACE::buf_pool_desc_t& buf_pool_desc) {
static bool init = false;
if (init) {
return;
}
init = true;
// use the buffer for the WSF heap
SystemHeapStart = buf_pool_desc.buffer_memory;
SystemHeapSize = buf_pool_desc.buffer_size;
// Initialize buffers with the ones provided by the HCI driver
uint16_t bytes_used = WsfBufInit(
buf_pool_desc.pool_count,
(wsfBufPoolDesc_t*)buf_pool_desc.pool_description
);
// Raise assert if not enough memory was allocated
MBED_ASSERT(bytes_used != 0);
SystemHeapStart += bytes_used;
SystemHeapSize -= bytes_used;
WsfTimerInit();
}
extern "C" void wsf_mbed_ble_signal_event(void)
{
// do nothing
}
#endif //CORDIO_ZERO_COPY_HCI
static void bleLoop()
{
#if CORDIO_ZERO_COPY_HCI
uint64_t last_update_us = 0;
mbed::LowPowerTimer timer;
timer.start();
while (true) {
last_update_us += (uint64_t) timer.read_high_resolution_us();
timer.reset();
uint64_t last_update_ms = (last_update_us / 1000);
wsfTimerTicks_t wsf_ticks = (last_update_ms / WSF_MS_PER_TICK);
if (wsf_ticks > 0) {
WsfTimerUpdate(wsf_ticks);
last_update_us -= (last_update_ms * 1000);
}
wsfOsDispatcher();
bool sleep = false;
{
/* call needs interrupts disabled */
mbed::CriticalSectionLock critical_section;
if (wsfOsReadyToSleep()) {
sleep = true;
}
}
uint64_t time_spent = (uint64_t) timer.read_high_resolution_us();
/* don't bother sleeping if we're already past tick */
if (sleep && (WSF_MS_PER_TICK * 1000 > time_spent)) {
/* sleep to maintain constant tick rate */
uint64_t wait_time_us = WSF_MS_PER_TICK * 1000 - time_spent;
uint64_t wait_time_ms = wait_time_us / 1000;
wait_time_us = wait_time_us % 1000;
if (wait_time_ms) {
rtos::ThisThread::sleep_for(wait_time_ms);
}
if (wait_time_us) {
wait_us(wait_time_us);
}
}
}
#else
while(true) {
rtos::ThisThread::sleep_for(osWaitForever);
}
#endif // CORDIO_ZERO_COPY_HCI
}
static rtos::EventFlags bleEventFlags;
static rtos::Thread* bleLoopThread = NULL;
HCICordioTransportClass::HCICordioTransportClass() :
_begun(false)
{
}
HCICordioTransportClass::~HCICordioTransportClass()
{
}
#if (defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)) && !defined(CUSTOM_HCI_DRIVER)
events::EventQueue eventQueue(10 * EVENTS_EVENT_SIZE);
void scheduleMbedBleEvents(BLE::OnEventsToProcessCallbackContext *context) {
eventQueue.call(mbed::Callback(&context->ble, &BLE::processEvents));
}
void completeCallback(BLE::InitializationCompleteCallbackContext *context) {
eventQueue.break_dispatch();
}
#endif
int HCICordioTransportClass::begin()
{
_rxBuf.clear();
#if CORDIO_ZERO_COPY_HCI
BLE_NAMESPACE::buf_pool_desc_t bufPoolDesc = CordioHCIHook::getDriver().get_buffer_pool_description();
init_wsf(bufPoolDesc);
#endif
#if (defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)) && !defined(CUSTOM_HCI_DRIVER)
BLE &ble = BLE::Instance();
ble.onEventsToProcess(scheduleMbedBleEvents);
ble.init(completeCallback);
eventQueue.dispatch(10000);
if (!ble.hasInitialized()){
return 0;
}
#else
CordioHCIHook::getDriver().initialize();
#endif
if (bleLoopThread == NULL) {
bleLoopThread = new rtos::Thread();
bleLoopThread->start(bleLoop);
}
CordioHCIHook::setDataReceivedHandler(HCICordioTransportClass::onDataReceived);
_begun = true;
return 1;
}
void HCICordioTransportClass::end()
{
if (bleLoopThread != NULL) {
bleLoopThread->terminate();
delete bleLoopThread;
bleLoopThread = NULL;
}
// Reset the callback with the mbed-os default handler to properly handle the following CYW43xxx chip initializations and begins
CordioHCIHook::setDataReceivedHandler(hciTrSerialRxIncoming);
#if (defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)) && !defined(CUSTOM_HCI_DRIVER)
BLE &ble = BLE::Instance();
ble.shutdown();
#endif
#if !defined(TARGET_STM32H7)
CordioHCIHook::getDriver().terminate();
#endif
_begun = false;
}
void HCICordioTransportClass::wait(unsigned long timeout)
{
{
mbed::CriticalSectionLock critical_section;
if (available()) {
return;
}
}
// wait for handleRxData to signal
bleEventFlags.wait_all(0x01, timeout, true);
}
int HCICordioTransportClass::available()
{
return _rxBuf.available();
}
int HCICordioTransportClass::peek()
{
return _rxBuf.peek();
}
int HCICordioTransportClass::read()
{
return _rxBuf.read_char();
}
void HCICordioTransportClass::lockForRead() {
mbed::CriticalSectionLock::enable();
}
void HCICordioTransportClass::unlockForRead() {
mbed::CriticalSectionLock::disable();
}
size_t HCICordioTransportClass::write(const uint8_t* data, size_t length)
{
if (!_begun) {
return 0;
}
uint8_t packetLength = length - 1;
uint8_t packetType = data[0];
#if CORDIO_ZERO_COPY_HCI
uint8_t* packet = (uint8_t*)WsfMsgAlloc(max(packetLength, MIN_WSF_ALLOC));
memcpy(packet, &data[1], packetLength);
return CordioHCIHook::getTransportDriver().write(packetType, packetLength, packet);
#else
return CordioHCIHook::getTransportDriver().write(packetType, packetLength, (uint8_t*)&data[1]);
#endif
}
void HCICordioTransportClass::handleRxData(uint8_t* data, uint8_t len)
{
{
#if defined(ARDUINO_ARCH_NRF52840)
mbed::CriticalSectionLock critical_section;
#endif
if (_rxBuf.availableForStore() < len) {
// drop!
return;
}
for (int i = 0; i < len; i++) {
_rxBuf.store_char(data[i]);
}
}
bleEventFlags.set(0x01);
}
HCICordioTransportClass HCICordioTransport;
HCITransportInterface& HCITransport = HCICordioTransport;
void HCICordioTransportClass::onDataReceived(uint8_t* data, uint8_t len)
{
HCICordioTransport.handleRxData(data, len);
}
#endif
================================================
FILE: src/utility/HCICordioTransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2019 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_CORDIO_TRANSPORT_H_
#define _HCI_CORDIO_TRANSPORT_H_
#include
#include "api/RingBuffer.h"
#include "HCITransport.h"
class HCICordioTransportClass : public HCITransportInterface {
public:
HCICordioTransportClass();
virtual ~HCICordioTransportClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual void lockForRead() override;
virtual void unlockForRead() override;
virtual size_t write(const uint8_t* data, size_t length);
private:
static void onDataReceived(uint8_t* data, uint8_t len);
void handleRxData(uint8_t* data, uint8_t len);
private:
bool _begun;
RingBufferN<256> _rxBuf;
};
#endif
================================================
FILE: src/utility/HCINinaSpiTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2024 Arduino SA
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#if defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(TARGET_NANO_RP2040_CONNECT)
#include "HCINinaSpiTransport.h"
#include
enum {
BLE_BEGIN = 0x4A,
BLE_END = 0x4B,
BLE_AVAILABLE = 0x4C,
BLE_PEEK = 0x4D,
BLE_READ = 0x4E,
BLE_WRITE = 0x4F,
};
int BleDrv::bleBegin() {
WAIT_FOR_SLAVE_SELECT();
SpiDrv::sendCmd(BLE_BEGIN, PARAM_NUMS_0);
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint8_t len = 1;
uint8_t result = 0;
SpiDrv::waitResponseCmd(BLE_BEGIN, PARAM_NUMS_1, (uint8_t*)&result, &len);
SpiDrv::spiSlaveDeselect();
return result == 0;
}
void BleDrv::bleEnd() {
WAIT_FOR_SLAVE_SELECT();
SpiDrv::sendCmd(BLE_END, PARAM_NUMS_0);
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint8_t len = 1;
uint8_t result = 0;
SpiDrv::waitResponseCmd(BLE_END, PARAM_NUMS_1, (uint8_t*)&result, &len);
SpiDrv::spiSlaveDeselect();
}
int BleDrv::bleAvailable() {
WAIT_FOR_SLAVE_SELECT();
uint16_t result = 0;
SpiDrv::sendCmd(BLE_AVAILABLE, PARAM_NUMS_0);
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint8_t len = 2;
SpiDrv::waitResponseCmd(BLE_AVAILABLE, PARAM_NUMS_1, (uint8_t*)&result, &len);
SpiDrv::spiSlaveDeselect();
return result;
}
int BleDrv::bleRead(uint8_t data[], size_t length) {
WAIT_FOR_SLAVE_SELECT();
SpiDrv::sendCmd(BLE_READ, PARAM_NUMS_1);
int commandSize = 7; // 4 for the normal command length + 3 for the parameter
uint16_t param = length; // TODO check length doesn't exceed 2^16
SpiDrv::sendParam((uint8_t*)¶m, sizeof(param), LAST_PARAM);
// pad to multiple of 4
while (commandSize % 4 != 0) {
SpiDrv::readChar();
commandSize++;
}
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint16_t res_len = 0;
SpiDrv::waitResponseData16(BLE_READ, data, (uint16_t*)&res_len);
SpiDrv::spiSlaveDeselect();
return res_len;
}
int BleDrv::blePeek(uint8_t data[], size_t length) {
WAIT_FOR_SLAVE_SELECT();
SpiDrv::sendCmd(BLE_PEEK, PARAM_NUMS_1);
int commandSize = 7; // 4 for the normal command length + 3 for the parameter
uint16_t param = length; // TODO check length doesn't exceed 2^16
SpiDrv::sendParam((uint8_t*)¶m, sizeof(param), LAST_PARAM);
// pad to multiple of 4
while (commandSize % 4 != 0) {
SpiDrv::readChar();
commandSize++;
}
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint16_t res_len = 0;
SpiDrv::waitResponseData16(BLE_READ, data, (uint16_t*)&res_len);
SpiDrv::spiSlaveDeselect();
return res_len;
}
size_t BleDrv::bleWrite(const uint8_t* data, size_t len) {
WAIT_FOR_SLAVE_SELECT();
int commandSize = 4;
SpiDrv::sendCmd(BLE_WRITE, PARAM_NUMS_1);
SpiDrv::sendBuffer((uint8_t*)data, len, LAST_PARAM);
commandSize += len+2;
// pad to multiple of 4
while (commandSize % 4 != 0) {
SpiDrv::readChar();
commandSize++;
}
SpiDrv::spiSlaveDeselect();
//Wait the reply elaboration
SpiDrv::waitForSlaveReady();
SpiDrv::spiSlaveSelect();
uint8_t res_len = 1;
uint16_t res = 0;
SpiDrv::waitResponseCmd(BLE_WRITE, PARAM_NUMS_1, (uint8_t*)&res, &res_len);
SpiDrv::spiSlaveDeselect();
return res;
}
int HCINinaSpiTransportClass::begin()
{
SpiDrv::begin();
return BleDrv::bleBegin();
}
void HCINinaSpiTransportClass::end()
{
BleDrv::bleEnd();
}
void HCINinaSpiTransportClass::wait(unsigned long timeout)
{
for (unsigned long start = millis(); (millis() - start) < timeout;) {
if (available()) {
break;
}
}
}
int HCINinaSpiTransportClass::available()
{
return BleDrv::bleAvailable();
}
int HCINinaSpiTransportClass::peek()
{
int res=-1;
BleDrv::blePeek((uint8_t*)&res, 1); // read a single byte, if nothing is returned we return -1
return res;
}
int HCINinaSpiTransportClass::read()
{
int res=-1;
BleDrv::bleRead((uint8_t*)&res, 1); // read a single byte, if nothing is returned we return -1
return res;
}
size_t HCINinaSpiTransportClass::write(const uint8_t* data, size_t length)
{
return BleDrv::bleWrite(data, length);
}
HCINinaSpiTransportClass HCINinaSpiTransport;
HCITransportInterface& HCITransport = HCINinaSpiTransport;
#endif
================================================
FILE: src/utility/HCINinaSpiTransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2024 Arduino SA
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef _HCI_NINA_SPI_TRANSPORT_H_
#define _HCI_NINA_SPI_TRANSPORT_H_
#include "HCITransport.h"
class BleDrv
{
public:
static int bleBegin();
static void bleEnd();
static int bleAvailable();
static int bleRead(uint8_t data[], size_t length);
static int blePeek(uint8_t data[], size_t length);
static size_t bleWrite(const uint8_t* data, size_t length);
};
class HCINinaSpiTransportClass : public HCITransportInterface {
public:
HCINinaSpiTransportClass() {}
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
};
#endif
================================================
FILE: src/utility/HCISilabsTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2024 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ARDUINO_SILABS)
#include "HCISilabsTransport.h"
#include "sl_string.h"
extern "C" {
#include "sl_btctrl_linklayer.h"
#include "sl_hci_common_transport.h"
}
extern "C" int strcasecmp(char const *a, char const *b) {
return sl_strcasecmp(a, b);
}
static RingBufferN<512> buf;
HCISilabsTransportClass::HCISilabsTransportClass()
{
}
HCISilabsTransportClass::~HCISilabsTransportClass()
{
}
int HCISilabsTransportClass::begin()
{
if(!sl_btctrl_is_initialized()) {
sl_bt_controller_init();
}
/* Initialize adv & scan components */
sl_btctrl_init_adv();
sl_btctrl_init_scan();
sl_btctrl_init_conn();
sl_btctrl_init_adv_ext();
sl_btctrl_init_scan_ext();
/* Initialize HCI controller */
sl_bthci_init_upper();
sl_btctrl_hci_parser_init_default();
sl_btctrl_hci_parser_init_conn();
sl_btctrl_hci_parser_init_adv();
sl_btctrl_hci_parser_init_phy();
return 1;
}
void HCISilabsTransportClass::end()
{
sl_bt_controller_deinit();
}
void HCISilabsTransportClass::wait(unsigned long timeout)
{
for (unsigned long start = millis(); (millis() - start) < timeout;) {
if (available()) {
break;
}
}
}
int HCISilabsTransportClass::available()
{
return buf.available();
}
int HCISilabsTransportClass::peek()
{
return buf.peek();
}
int HCISilabsTransportClass::read()
{
return buf.read_char();
}
size_t HCISilabsTransportClass::write(const uint8_t* data, size_t len)
{
int ret = 0;
ret = hci_common_transport_receive((uint8_t *)data, len, true);
if (ret == 0) return len;
return 0;
}
extern "C" {
/**
* @brief Transmit HCI message using the currently used transport layer.
* The HCI calls this function to transmit a full HCI message.
* @param[in] data Packet type followed by HCI packet data.
* @param[in] len Length of the `data` parameter
* @return 0 - on success, or non-zero on failure.
*/
uint32_t hci_common_transport_transmit(uint8_t *data, int16_t len)
{
for (int i = 0; i < len; i++) {
buf.store_char(data[i]);
if (buf.isFull()) return SL_STATUS_FAIL;
}
sl_btctrl_hci_transmit_complete(0);
return 0;
}
}
HCISilabsTransportClass HCISilabsTransport;
HCITransportInterface& HCITransport = HCISilabsTransport;
#endif
================================================
FILE: src/utility/HCISilabsTransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_SILABS_TRANSPORT_H_
#define _HCI_SILABS_TRANSPORT_H_
#include "HCITransport.h"
class HCISilabsTransportClass : public HCITransportInterface {
public:
HCISilabsTransportClass();
virtual ~HCISilabsTransportClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
};
#endif
================================================
FILE: src/utility/HCITransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_TRANSPORT_INTERFACE_H_
#define _HCI_TRANSPORT_INTERFACE_H_
#include
class HCITransportInterface {
public:
virtual int begin() = 0;
virtual void end() = 0;
virtual void wait(unsigned long timeout) = 0;
virtual int available() = 0;
virtual int peek() = 0;
virtual int read() = 0;
// Some transports require a lock to use available/peek/read
// These methods allow to keep the lock while reading an unknown number of bytes
// These methods might disable interrupts. Only keep the lock as long as necessary.
virtual void lockForRead() {}
virtual void unlockForRead() {}
virtual size_t write(const uint8_t* data, size_t length) = 0;
};
extern HCITransportInterface& HCITransport;
#endif
================================================
FILE: src/utility/HCIUartTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ARDUINO_PORTENTA_C33) && !defined(__ZEPHYR__)
#include "HCIUartTransport.h"
#if defined(ARDUINO_PORTENTA_C33)
#define SerialHCI Serial5
#else
#error "Unsupported board selected!"
#endif
HCIUartTransportClass::HCIUartTransportClass(HardwareSerial& uart, unsigned long baudrate) :
_uart(&uart),
_baudrate(baudrate)
{
}
HCIUartTransportClass::~HCIUartTransportClass()
{
}
int HCIUartTransportClass::begin()
{
_uart->begin(_baudrate);
return 1;
}
void HCIUartTransportClass::end()
{
_uart->end();
}
void HCIUartTransportClass::wait(unsigned long timeout)
{
for (unsigned long start = millis(); (millis() - start) < timeout;) {
if (available()) {
break;
}
}
}
int HCIUartTransportClass::available()
{
return _uart->available();
}
int HCIUartTransportClass::peek()
{
return _uart->peek();
}
int HCIUartTransportClass::read()
{
return _uart->read();
}
size_t HCIUartTransportClass::write(const uint8_t* data, size_t length)
{
#ifdef ARDUINO_AVR_UNO_WIFI_REV2
// wait while the CTS pin is low
while (digitalRead(NINA_CTS) == HIGH);
#endif
size_t result = _uart->write(data, length);
_uart->flush();
return result;
}
HCIUartTransportClass HCIUartTransport(SerialHCI, 912600);
HCITransportInterface& HCITransport = HCIUartTransport;
#endif
================================================
FILE: src/utility/HCIUartTransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_UART_TRANSPORT_H_
#define _HCI_UART_TRANSPORT_H_
#include "HCITransport.h"
class HCIUartTransportClass : public HCITransportInterface {
public:
HCIUartTransportClass(HardwareSerial& uart, unsigned long baudrate);
virtual ~HCIUartTransportClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
private:
HardwareSerial* _uart;
unsigned long _baudrate;
};
#endif
================================================
FILE: src/utility/HCIVirtualTransport.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ESP32)
#include "HCIVirtualTransport.h"
StreamBufferHandle_t rec_buffer;
StreamBufferHandle_t send_buffer;
TaskHandle_t bleHandle;
static void notify_host_send_available(void)
{
}
static int notify_host_recv(uint8_t *data, uint16_t length)
{
xStreamBufferSend(rec_buffer,data,length,portMAX_DELAY); // !!!potentially waiting forever
return 0;
}
static esp_vhci_host_callback_t vhci_host_cb = {
notify_host_send_available,
notify_host_recv
};
void bleTask(void *pvParameters)
{
esp_vhci_host_register_callback(&vhci_host_cb);
size_t length;
uint8_t mybuf[258];
while(true){
length = xStreamBufferReceive(send_buffer,mybuf,258,portMAX_DELAY);
while (!esp_vhci_host_check_send_available()) {}
esp_vhci_host_send_packet(mybuf, length);
}
}
HCIVirtualTransportClass::HCIVirtualTransportClass()
{
}
HCIVirtualTransportClass::~HCIVirtualTransportClass()
{
}
int HCIVirtualTransportClass::begin()
{
btStarted(); // this somehow stops the arduino ide from initializing bluedroid
rec_buffer = xStreamBufferCreate(258, 1);
send_buffer = xStreamBufferCreate(258, 1);
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
#if CONFIG_IDF_TARGET_ESP32
bt_cfg.mode = ESP_BT_MODE_BLE; //original esp32 chip
#else
#if !(CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C5 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2)
bt_cfg.bluetooth_mode = ESP_BT_MODE_BLE; //different api for newer models
#endif
#endif
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE);
xTaskCreatePinnedToCore(&bleTask, "bleTask", 2048, NULL, 5, &bleHandle, 0);
return 1;
}
void HCIVirtualTransportClass::end()
{
vStreamBufferDelete(rec_buffer);
vStreamBufferDelete(send_buffer);
esp_bt_controller_disable();
esp_bt_controller_deinit();
vTaskDelete(bleHandle);
}
void HCIVirtualTransportClass::wait(unsigned long timeout)
{
for (unsigned long start = (esp_timer_get_time() / 1000ULL); ((esp_timer_get_time() / 1000ULL) - start) < timeout;) {
if (available()) {
break;
}
}
}
int HCIVirtualTransportClass::available()
{
size_t bytes = xStreamBufferBytesAvailable(rec_buffer);
return bytes;
}
// never called
int HCIVirtualTransportClass::peek()
{
return -1;
}
int HCIVirtualTransportClass::read()
{
uint8_t c;
if(xStreamBufferReceive(rec_buffer, &c, 1, portMAX_DELAY)) {
return c;
}
return -1;
}
size_t HCIVirtualTransportClass::write(const uint8_t* data, size_t length)
{
size_t result = xStreamBufferSend(send_buffer,data,length,portMAX_DELAY);
return result;
}
HCIVirtualTransportClass HCIVirtualTransport;
HCITransportInterface& HCITransport = HCIVirtualTransport;
#endif
================================================
FILE: src/utility/HCIVirtualTransport.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "HCITransport.h"
#include
#include
#include
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/stream_buffer.h"
#include "esp_bt.h"
#include "nvs_flash.h"
#include "esp32-hal-bt.h" // this is needed to disable bluedroid
class HCIVirtualTransportClass : public HCITransportInterface {
public:
HCIVirtualTransportClass();
virtual ~HCIVirtualTransportClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
};
================================================
FILE: src/utility/HCIVirtualTransportAT.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ARDUINO_UNOR4_WIFI)
#include "HCIVirtualTransportAT.h"
extern ModemClass modem;
HCIVirtualTransportATClass::HCIVirtualTransportATClass()
{
}
HCIVirtualTransportATClass::~HCIVirtualTransportATClass()
{
}
static RingBufferN<258> buf;
int HCIVirtualTransportATClass::begin()
{
// TODO: add this helper
//modem.debug(Serial);
buf.clear();
//modem.debug(true);
std::string res = "";
modem.begin();
if (modem.write(std::string(PROMPT(_HCI_BEGIN)), res, CMD(_HCI_BEGIN))) {
return 1;
}
return 0;
}
void HCIVirtualTransportATClass::end()
{
}
void HCIVirtualTransportATClass::wait(unsigned long timeout)
{
std::string res = "";
modem.write(std::string(PROMPT(_HCI_WAIT)), res, "%d\n\r", CMD_WRITE(_HCI_WAIT), timeout);
}
int HCIVirtualTransportATClass::available()
{
std::string res = "";
if (buf.available()) {
return buf.available();
}
if (modem.write(std::string(PROMPT(_HCI_AVAILABLE)), res, CMD_READ(_HCI_AVAILABLE))) {
return atoi(res.c_str());
}
return 0;
}
// never called
int HCIVirtualTransportATClass::peek()
{
return -1;
}
int HCIVirtualTransportATClass::read()
{
uint8_t c;
std::string res = "";
if (buf.available()) {
return buf.read_char();
}
modem.avoid_trim_results();
modem.read_using_size();
if (modem.write(std::string(PROMPT(_HCI_READ)), res, CMD(_HCI_READ))) {
for(int i = 0; i < res.size(); i++) {
buf.store_char((uint8_t)res[i]);
}
return buf.read_char();
}
return -1;
}
size_t HCIVirtualTransportATClass::write(const uint8_t* data, size_t length)
{
std::string res = "";
modem.write_nowait(std::string(PROMPT(_HCI_WRITE)), res, "%s%d\r\n" , CMD_WRITE(_HCI_WRITE), length);
if(modem.passthrough(data, length)) {
return length;
}
return 0;
}
HCIVirtualTransportATClass HCIVirtualTransportAT;
HCITransportInterface& HCITransport = HCIVirtualTransportAT;
#endif
================================================
FILE: src/utility/HCIVirtualTransportAT.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "HCITransport.h"
#include
#include
#include
#include "WiFiS3.h"
class HCIVirtualTransportATClass : public HCITransportInterface {
public:
HCIVirtualTransportATClass();
virtual ~HCIVirtualTransportATClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
};
================================================
FILE: src/utility/HCIVirtualTransportRPC.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018-2025 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(ARDUINO_UNO_Q)
#include "HCIVirtualTransportRPC.h"
#include
using RouterBridge::HCI;
HCIVirtualTransportRPCClass::HCIVirtualTransportRPCClass() : initialized(false) {
}
HCIVirtualTransportRPCClass::~HCIVirtualTransportRPCClass() {
}
int HCIVirtualTransportRPCClass::begin() {
// Initialize the Bridge if not already started
if (!Bridge) {
if (!Bridge.begin()) {
return 0;
}
}
// Open HCI device through Bridge RPC
if (!HCI.begin("hci0")) {
return 0;
}
rxbuf.clear();
initialized = true;
return 1;
}
void HCIVirtualTransportRPCClass::end() {
if (initialized) {
HCI.end();
initialized = false;
}
}
void HCIVirtualTransportRPCClass::wait(unsigned long timeout) {
delay(timeout);
}
int HCIVirtualTransportRPCClass::available() {
if (!initialized) {
return 0;
}
// Return buffered data if available
if (rxbuf.available()) {
return rxbuf.available();
}
// Check if data is available from Bridge HCI and buffer it
if (HCI.available()) {
uint8_t packet[258];
int received = HCI.recv(packet, sizeof(packet));
if (received > 0) {
// Store received data in ring buffer
for (int i = 0; i < received; i++) {
rxbuf.store_char(packet[i]);
}
}
}
return rxbuf.available();
}
int HCIVirtualTransportRPCClass::peek() {
return -1;
}
int HCIVirtualTransportRPCClass::read() {
if (rxbuf.available()) {
return rxbuf.read_char();
}
return -1;
}
size_t HCIVirtualTransportRPCClass::write(const uint8_t* data, size_t length) {
if (!initialized) {
return 0;
}
int sent = HCI.send(data, length);
if (sent < 0) {
return 0;
}
return sent;
}
HCIVirtualTransportRPCClass HCIVirtualTransportRPC;
HCITransportInterface& HCITransport = HCIVirtualTransportRPC;
#endif
================================================
FILE: src/utility/HCIVirtualTransportRPC.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018-2025 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _HCI_VIRTUAL_TRANSPORT_RPC_H_
#define _HCI_VIRTUAL_TRANSPORT_RPC_H_
#include "HCITransport.h"
#include "api/RingBuffer.h"
#include
#include
#include
class HCIVirtualTransportRPCClass : public HCITransportInterface {
public:
HCIVirtualTransportRPCClass();
virtual ~HCIVirtualTransportRPCClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
private:
RingBufferN<258> rxbuf;
bool initialized;
};
extern HCIVirtualTransportRPCClass HCIVirtualTransportRPC;
#endif
================================================
FILE: src/utility/HCIVirtualTransportZephyr.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018-2025 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#if defined(__ZEPHYR__) && !defined(ARDUINO_UNO_Q)
#include "HCIVirtualTransportZephyr.h"
#include "HCI.h"
#include
#include
#include
#include
#include
#include
static K_FIFO_DEFINE(rx_queue);
struct k_fifo* __rx_queue = &rx_queue;
extern "C" int bt_h4_vnd_setup(const struct device *dev);
#if CONFIG_CYW4343W_MURATA_1DX
// External firmware defines.
extern const uint8_t brcm_patchram_buf[];
extern const int brcm_patch_ram_length;
enum {
HCI_VND_OP_FW_DOWNLOAD = 0xFC2E,
HCI_VND_OP_WRITE_RAM = 0xFC4C,
HCI_VND_OP_LAUNCH_RAM = 0xFC4E,
HCI_VND_OP_SET_BAUDRATE = 0xFC18,
};
static int cyw4343_set_baudrate(const struct device *uart, uint32_t baudrate) {
struct __attribute__ ((packed)) {
uint16_t zero;
uint32_t baud;
} param = { 0, baudrate };
struct uart_config uart_cfg;
if (uart_config_get(uart, &uart_cfg)) {
return -1;
}
if (HCI.sendCommand(HCI_VND_OP_SET_BAUDRATE, sizeof(param), (void *) ¶m)) {
return -1;
}
uart_cfg.baudrate = baudrate;
if (uart_configure(uart, &uart_cfg)) {
return -1;
}
uart_irq_rx_enable(uart);
return 0;
}
static int cyw4343_download_firmware(const struct device *uart) {
#define MURATA_NODE DT_CHILD(DT_CHOSEN(zephyr_bt_hci), murata_1dx)
uint32_t operational_speed = DT_PROP_OR(MURATA_NODE, hci_operation_speed, 115200);
uint32_t fw_download_speed = DT_PROP_OR(MURATA_NODE, fw_download_speed, 115200);
// Reset controller
if (HCI.sendCommand(0x0C03, 0, NULL)) {
return -1;
}
// Switch to fast baudrate
if ((operational_speed != fw_download_speed) &&
cyw4343_set_baudrate(uart, fw_download_speed)) {
return -1;
}
// Start firmware downloader.
if (HCI.sendCommand(HCI_VND_OP_FW_DOWNLOAD, 0, NULL)) {
return -1;
}
// Load the firmware image.
for (int offset=0; offset < brcm_patch_ram_length;) {
uint8_t length = brcm_patchram_buf[offset + 2];
uint16_t opcode = (brcm_patchram_buf[offset + 0]) |
(brcm_patchram_buf[offset + 1] << 8);
// Opcode should be write RAM or launch RAM.
if (opcode != HCI_VND_OP_WRITE_RAM && opcode != HCI_VND_OP_LAUNCH_RAM) {
return -1;
}
if (HCI.sendCommand(opcode, length, (void *) &brcm_patchram_buf[offset + 3])) {
return -1;
}
offset += length + 3;
}
// Delay after firmware loading.
delay(250);
// Switch back to the default baudrate.
if ((operational_speed != fw_download_speed) &&
cyw4343_set_baudrate(uart, operational_speed)) {
return -1;
}
return 0;
}
#endif
HCIVirtualTransportZephyrClass::HCIVirtualTransportZephyrClass() {
}
HCIVirtualTransportZephyrClass::~HCIVirtualTransportZephyrClass() {
}
int HCIVirtualTransportZephyrClass::begin() {
k_fifo_init(&rx_queue);
bt_enable_raw(__rx_queue);
#if CONFIG_BT_HCI_SETUP
const struct device *uart = DEVICE_DT_GET(DT_PARENT(DT_CHOSEN(zephyr_bt_hci)));
if (!uart) {
return 0;
}
if (bt_h4_vnd_setup(uart)) {
return 0;
}
#if CONFIG_CYW4343W_MURATA_1DX
if (cyw4343_download_firmware(uart)) {
return 0;
}
#endif /* CONFIG_CYW4343W_MURATA_1DX */
#endif /* CONFIG_BT_HCI_SETUP */
#if CONFIG_BT_LL_SW_SPLIT
// Use unique device id for BD addr.
uint8_t bd_addr[6] = { 0xFA, 0xFA, 0xFA, 0xFA, 0xFA, 0xFA };
#if CONFIG_HWINFO
hwinfo_get_device_id(bd_addr, sizeof(bd_addr));
#endif /* CONFIG_HWINFO */
// Set public address for controller.
bt_ctlr_set_public_addr(bd_addr);
#endif /* CONFIG_BT_LL_SW_SPLIT */
rxbuf.clear();
return 1;
}
void HCIVirtualTransportZephyrClass::end() {
}
void HCIVirtualTransportZephyrClass::wait(unsigned long timeout) {
delay(timeout);
}
int HCIVirtualTransportZephyrClass::available() {
static struct net_buf *buf = NULL;
if (rxbuf.available()) {
return rxbuf.available();
}
buf = (struct net_buf *) k_fifo_get(__rx_queue, K_MSEC(10));
if (!buf) {
return 0;
}
for (int i=0; ilen; i++) {
rxbuf.store_char((uint8_t)buf->data[i]);
}
net_buf_pull(buf, buf->len);
if (!buf->len) {
net_buf_unref(buf);
buf = NULL;
}
return rxbuf.available();
}
int HCIVirtualTransportZephyrClass::peek() {
return -1;
}
int HCIVirtualTransportZephyrClass::read() {
if (rxbuf.available()) {
return rxbuf.read_char();
}
return -1;
}
size_t HCIVirtualTransportZephyrClass::write(const uint8_t* data, size_t length) {
enum bt_buf_type type = bt_buf_type_from_h4(data[0], BT_BUF_OUT);
struct net_buf *buf = bt_buf_get_tx(type, K_FOREVER, &data[1], length - 1);
if (buf) {
auto err = bt_send(buf);
if (err) {
net_buf_unref(buf);
}
return length;
}
return 0;
}
HCIVirtualTransportZephyrClass HCIVirtualTransportZephyr;
HCITransportInterface& HCITransport = HCIVirtualTransportZephyr;
#endif
================================================
FILE: src/utility/HCIVirtualTransportZephyr.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018-2025 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "HCITransport.h"
#include "api/RingBuffer.h"
#include
#include
#include
class HCIVirtualTransportZephyrClass : public HCITransportInterface {
public:
HCIVirtualTransportZephyrClass();
virtual ~HCIVirtualTransportZephyrClass();
virtual int begin();
virtual void end();
virtual void wait(unsigned long timeout);
virtual int available();
virtual int peek();
virtual int read();
virtual size_t write(const uint8_t* data, size_t length);
private:
RingBufferN<258> rxbuf;
};
================================================
FILE: src/utility/L2CAPSignaling.cpp
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "HCI.h"
#include "ATT.h"
#include "btct.h"
#include "L2CAPSignaling.h"
#include "keyDistribution.h"
#include "bitDescriptions.h"
#define CONNECTION_PARAMETER_UPDATE_REQUEST 0x12
#define CONNECTION_PARAMETER_UPDATE_RESPONSE 0x13
//#define _BLE_TRACE_
L2CAPSignalingClass::L2CAPSignalingClass() :
_minInterval(0),
_maxInterval(0),
_supervisionTimeout(0),
_pairing_enabled(1)
{
}
L2CAPSignalingClass::~L2CAPSignalingClass()
{
}
void L2CAPSignalingClass::addConnection(uint16_t handle, uint8_t role, uint8_t /*peerBdaddrType*/,
uint8_t /*peerBdaddr*/[6], uint16_t interval,
uint16_t /*latency*/, uint16_t supervisionTimeout,
uint8_t /*masterClockAccuracy*/)
{
if (role != 1) {
// ignore
return;
}
bool updateParameters = false;
uint16_t updatedMinInterval = interval;
uint16_t updatedMaxInterval = interval;
uint16_t updatedSupervisionTimeout = supervisionTimeout;
if (_minInterval && _maxInterval) {
if (interval < _minInterval || interval > _maxInterval) {
updatedMinInterval = _minInterval;
updatedMaxInterval = _maxInterval;
updateParameters = true;
}
}
if (_supervisionTimeout && supervisionTimeout != _supervisionTimeout) {
updatedSupervisionTimeout = _supervisionTimeout;
updateParameters = true;
}
if (updateParameters) {
struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateRequest {
uint8_t code;
uint8_t identifier;
uint16_t length;
uint16_t minInterval;
uint16_t maxInterval;
uint16_t latency;
uint16_t supervisionTimeout;
} request = { CONNECTION_PARAMETER_UPDATE_REQUEST, 0x01, 8,
updatedMinInterval, updatedMaxInterval, 0x0000, updatedSupervisionTimeout };
HCI.sendAclPkt(handle, SIGNALING_CID, sizeof(request), &request);
}
}
void L2CAPSignalingClass::handleData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) L2CAPSignalingHdr {
uint8_t code;
uint8_t identifier;
uint16_t length;
} *l2capSignalingHdr = (L2CAPSignalingHdr*)data;
if (dlen < sizeof(L2CAPSignalingHdr)) {
// too short, ignore
return;
}
if (dlen != (sizeof(L2CAPSignalingHdr) + l2capSignalingHdr->length)) {
// invalid length, ignore
return;
}
uint8_t code = l2capSignalingHdr->code;
uint8_t identifier = l2capSignalingHdr->identifier;
uint16_t length = l2capSignalingHdr->length;
data = &data[sizeof(L2CAPSignalingHdr)];
if (code == CONNECTION_PARAMETER_UPDATE_REQUEST) {
connectionParameterUpdateRequest(connectionHandle, identifier, length, data);
} else if (code == CONNECTION_PARAMETER_UPDATE_RESPONSE) {
connectionParameterUpdateResponse(connectionHandle, identifier, length, data);
}
}
void L2CAPSignalingClass::handleSecurityData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) L2CAPSignalingHdr {
uint8_t code;
uint8_t data[64];
} *l2capSignalingHdr = (L2CAPSignalingHdr*)data;
#ifdef _BLE_TRACE_
Serial.print("dlen: ");
Serial.println(dlen);
#else
(void)dlen;
#endif
uint8_t code = l2capSignalingHdr->code;
#ifdef _BLE_TRACE_
Serial.print("handleSecurityData: code: 0x");
Serial.println(code, HEX);
Serial.print("rx security:");
btct.printBytes(data,dlen);
#endif
if (code == CONNECTION_PAIRING_REQUEST) {
if (isPairingEnabled()){
if (_pairing_enabled >= 2) _pairing_enabled = 0; // 2 = pair once only
// 0x1
struct __attribute__ ((packed)) PairingRequest {
uint8_t ioCapability;
uint8_t oobDataFlag;
uint8_t authReq;
uint8_t maxEncSize;
uint8_t initiatorKeyDistribution;
uint8_t responderKeyDistribution;
} *pairingRequest = (PairingRequest*)l2capSignalingHdr->data;
KeyDistribution responseKD = KeyDistribution();
responseKD.setIdKey(true);
ATT.remoteKeyDistribution = responseKD;// KeyDistribution(pairingRequest->initiatorKeyDistribution);
ATT.localKeyDistribution = responseKD; //KeyDistribution(pairingRequest->responderKeyDistribution);
// KeyDistribution rkd(pairingRequest->responderKeyDistribution);
AuthReq req(pairingRequest->authReq);
#ifdef _BLE_TRACE_
Serial.print("Req has properties: ");
Serial.print(req.Bonding()?"bonding, ":"no bonding, ");
Serial.print(req.CT2()?"CT2, ":"no CT2, ");
Serial.print(req.KeyPress()?"KeyPress, ":"no KeyPress, ");
Serial.print(req.MITM()?"MITM, ":"no MITM, ");
Serial.print(req.SC()?"SC, ":"no SC, ");
#endif
uint8_t peerIOCap[3];
peerIOCap[0] = pairingRequest->authReq;
peerIOCap[1] = pairingRequest->oobDataFlag;
peerIOCap[2] = pairingRequest->ioCapability;
ATT.setPeerIOCap(connectionHandle, peerIOCap);
ATT.setPeerEncryption(connectionHandle, ATT.getPeerEncryption(connectionHandle) | PEER_ENCRYPTION::PAIRING_REQUEST);
#ifdef _BLE_TRACE_
Serial.print("Peer encryption : 0b");
Serial.println(ATT.getPeerEncryption(connectionHandle), BIN);
#endif
struct __attribute__ ((packed)) PairingResponse {
uint8_t code;
uint8_t ioCapability;
uint8_t oobDataFlag;
uint8_t authReq;
uint8_t maxEncSize;
uint8_t initiatorKeyDistribution;
uint8_t responderKeyDistribution;
} response = { CONNECTION_PAIRING_RESPONSE, HCI.localIOCap(), 0, HCI.localAuthreq().getOctet(), 0x10, responseKD.getOctet(), responseKD.getOctet()};
HCI.sendAclPkt(connectionHandle, SECURITY_CID, sizeof(response), &response);
} else {
// Pairing not enabled
uint8_t ret[2] = {CONNECTION_PAIRING_FAILED, 0x05}; // reqect pairing
HCI.sendAclPkt(connectionHandle, SECURITY_CID, sizeof(ret), ret);
ATT.setPeerEncryption(connectionHandle, NO_ENCRYPTION);
}
}
else if (code == CONNECTION_PAIRING_RANDOM)
{
struct __attribute__ ((packed)) PairingRandom {
uint8_t Na[16];
} *pairingRandom = (PairingRandom*)l2capSignalingHdr->data;
for(int i=0; i<16; i++){
HCI.Na[15-i] = pairingRandom->Na[i];
}
#ifdef _BLE_TRACE_
Serial.println("[Info] Pairing random.");
#endif
struct __attribute__ ((packed)) PairingResponse {
uint8_t code;
uint8_t Nb[16];
} response = { CONNECTION_PAIRING_RANDOM, 0};
for(int i=0; i< 16; i++) response.Nb[15-i] = HCI.Nb[i];
HCI.sendAclPkt(connectionHandle, SECURITY_CID, sizeof(response), &response);
// We now have all needed for compare value
uint8_t g2Result[4];
uint8_t U[32];
uint8_t V[32];
for(int i=0; i<32; i++){
U[31-i] = HCI.remotePublicKeyBuffer[i];
V[31-i] = HCI.localPublicKeyBuffer[i];
}
btct.g2(U,V,HCI.Na,HCI.Nb, g2Result);
uint32_t result = 0;
for(int i=0; i<4; i++) result += g2Result[3-i] << 8*i;
#ifdef _BLE_TRACE_
Serial.print("U : ");
btct.printBytes(U,32);
Serial.print("V : ");
btct.printBytes(V,32);
Serial.print("X : ");
btct.printBytes(HCI.Na,16);
Serial.print("Y : ");
btct.printBytes(HCI.Nb,16);
Serial.print("g2res : ");
btct.printBytes(g2Result,4);
Serial.print("Result : ");
Serial.println(result);
#endif
if(HCI._displayCode!=0){
HCI._displayCode(result%1000000);
}
if(HCI._binaryConfirmPairing!=0){
if(!HCI._binaryConfirmPairing()){
#ifdef _BLE_TRACE_
Serial.println("User rejection");
#endif
uint8_t rejection[2];
rejection[0] = CONNECTION_PAIRING_FAILED;
rejection[1] = 0x0C; // Numeric comparison failed
HCI.sendAclPkt(connectionHandle, SECURITY_CID, 2, rejection);
ATT.setPeerEncryption(connectionHandle, PEER_ENCRYPTION::NO_ENCRYPTION);
}else{
#ifdef _BLE_TRACE_
Serial.println("User did confirm");
#endif
}
}
}
else if (code == CONNECTION_PAIRING_RESPONSE)
{
}
else if(code == CONNECTION_PAIRING_FAILED)
{
#ifdef _BLE_TRACE_
struct __attribute__ ((packed)) PairingFailed
{
uint8_t code;
uint8_t reason;
} *pairingFailed = (PairingFailed*)data;
Serial.print("Pairing failed with code: 0x");
Serial.println(pairingFailed->reason,HEX);
#endif
ATT.setPeerEncryption(connectionHandle, PEER_ENCRYPTION::NO_ENCRYPTION);
}
else if (code == CONNECTION_IDENTITY_INFORMATION){
struct __attribute__ ((packed)) IdentityInformation {
uint8_t code;
uint8_t PeerIRK[16];
} *identityInformation = (IdentityInformation*)data;
for(int i=0; i<16; i++) ATT.peerIRK[15-i] = identityInformation->PeerIRK[i];
#ifdef _BLE_TRACE_
Serial.println("Saved peer IRK");
#endif
}
else if (code == CONNECTION_IDENTITY_ADDRESS){
struct __attribute__ ((packed)) IdentityAddress {
uint8_t code;
uint8_t addressType;
uint8_t address[6];
} *identityAddress = (IdentityAddress*)data;
// we can save this information now.
uint8_t peerAddress[6];
for(int i=0; i<6; i++) peerAddress[5-i] = identityAddress->address[i];
HCI.saveNewAddress(identityAddress->addressType, peerAddress, ATT.peerIRK, ATT.localIRK);
if(HCI._storeLTK!=0){
HCI._storeLTK(peerAddress, HCI.LTK);
}
}
else if (code == CONNECTION_PAIRING_PUBLIC_KEY){
/// Received a public key
struct __attribute__ ((packed)) ConnectionPairingPublicKey {
uint8_t x[32];
uint8_t y[32];
} *connectionPairingPublicKey = (ConnectionPairingPublicKey*)l2capSignalingHdr->data;
struct __attribute__ ((packed)) GenerateDHKeyCommand {
uint8_t x[32];
uint8_t y[32];
} generateDHKeyCommand = {
{0x00},
{0x00},
};
memcpy(generateDHKeyCommand.x,connectionPairingPublicKey->x,32);
memcpy(generateDHKeyCommand.y,connectionPairingPublicKey->y,32);
if(ATT.setPeerEncryption(connectionHandle, ATT.getPeerEncryption(connectionHandle) | PEER_ENCRYPTION::REQUESTED_ENCRYPTION)){
#ifdef _BLE_TRACE_
Serial.println("[Info] Pairing public key");
Serial.println("Requested encryption stored.");
#endif
}else{
#ifdef _BLE_TRACE_
Serial.println("[Info] Pairing public key");
Serial.print("Failed to store encryption request with handle: 0x");
Serial.println(connectionHandle,HEX);
#endif
}
memcpy(HCI.remotePublicKeyBuffer,&generateDHKeyCommand,sizeof(generateDHKeyCommand));
HCI.sendCommand( (OGF_LE_CTL << 10 )| LE_COMMAND::READ_LOCAL_P256, 0);
}
else if(code == CONNECTION_PAIRING_DHKEY_CHECK)
{
uint8_t RemoteDHKeyCheck[16];
for(int i=0; i<16; i++) RemoteDHKeyCheck[15-i] = l2capSignalingHdr->data[i];
#ifdef _BLE_TRACE_
Serial.println("[Info] DH Key check");
Serial.print("Remote DHKey Check: ");
btct.printBytes(RemoteDHKeyCheck, 16);
#endif
uint8_t encryptionState = ATT.getPeerEncryption(connectionHandle) | PEER_ENCRYPTION::RECEIVED_DH_CHECK;
ATT.setPeerEncryption(connectionHandle, encryptionState);
if((encryptionState & PEER_ENCRYPTION::DH_KEY_CALULATED) == 0){
#ifdef _BLE_TRACE_
Serial.println("DHKey not yet ready, will calculate f5, f6 later");
#endif
// store RemoteDHKeyCheck for later check
memcpy(HCI.remoteDHKeyCheckBuffer,RemoteDHKeyCheck,16);
} else {
// We've already calculated the DHKey so we can calculate our check and send it.
smCalculateLTKandConfirm(connectionHandle, RemoteDHKeyCheck);
}
}
}
void L2CAPSignalingClass::smCalculateLTKandConfirm(uint16_t handle, uint8_t expectedEa[])
{ // Authentication stage 2: LTK Calculation
uint8_t localAddress[7];
uint8_t remoteAddress[7];
ATT.getPeerAddrWithType(handle, remoteAddress);
HCI.readBdAddr();
memcpy(&localAddress[1],HCI.localAddr,6);
localAddress[0] = 0; // IOT 33 uses a static address // TODO: confirm for Nano BLE
// Compute the LTK and MacKey
uint8_t MacKey[16];
btct.f5(HCI.DHKey, HCI.Na, HCI.Nb, remoteAddress, localAddress, MacKey, HCI.LTK);
// Compute Ea and Eb
uint8_t Ea[16];
uint8_t Eb[16];
uint8_t R[16];
uint8_t MasterIOCap[3];
uint8_t SlaveIOCap[3] = {HCI.localAuthreq().getOctet(), 0x0, HCI.localIOCap()};
ATT.getPeerIOCap(handle, MasterIOCap);
for(int i=0; i<16; i++) R[i] = 0;
btct.f6(MacKey, HCI.Na,HCI.Nb,R, MasterIOCap, remoteAddress, localAddress, Ea);
btct.f6(MacKey, HCI.Nb,HCI.Na,R, SlaveIOCap, localAddress, remoteAddress, Eb);
#ifdef _BLE_TRACE_
Serial.println("Calculate and confirm LTK via f5, f6:");
Serial.print("DHKey : "); btct.printBytes(HCI.DHKey,32);
Serial.print("Na : "); btct.printBytes(HCI.Na,16);
Serial.print("Nb : "); btct.printBytes(HCI.Nb,16);
Serial.print("MacKey : "); btct.printBytes(MacKey,16);
Serial.print("LTK : "); btct.printBytes(HCI.LTK,16);
Serial.print("Expected Ea: "); btct.printBytes(expectedEa, 16);
Serial.print("Ea : "); btct.printBytes(Ea, 16);
Serial.print("Eb : "); btct.printBytes(Eb,16);
Serial.print("Local Addr : "); btct.printBytes(localAddress, 7);
Serial.print("LocalIOCap : "); btct.printBytes(SlaveIOCap, 3);
Serial.print("MasterAddr : "); btct.printBytes(remoteAddress, 7);
Serial.print("MasterIOCAP: "); btct.printBytes(MasterIOCap, 3);
#endif
// Check if Ea = expectedEa
if (memcmp(Ea, expectedEa, 16) == 0){
// Check ok
// Send our confirmation value to complete authentication stage 2
uint8_t ret[17];
ret[0] = CONNECTION_PAIRING_DHKEY_CHECK;
for(uint32_t i=0; i 0;
}
void L2CAPSignalingClass::connectionParameterUpdateRequest(uint16_t handle, uint8_t identifier, uint8_t dlen, uint8_t data[])
{
struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateRequest {
uint16_t minInterval;
uint16_t maxInterval;
uint16_t latency;
uint16_t supervisionTimeout;
} *request = (L2CAPConnectionParameterUpdateRequest*)data;
if (dlen < sizeof(L2CAPConnectionParameterUpdateRequest)) {
// too short, ignore
return;
}
struct __attribute__ ((packed)) L2CAPConnectionParameterUpdateResponse {
uint8_t code;
uint8_t identifier;
uint16_t length;
uint16_t value;
} response = { CONNECTION_PARAMETER_UPDATE_RESPONSE, identifier, 2, 0x0000 };
if (_minInterval && _maxInterval) {
if (request->minInterval < _minInterval || request->maxInterval > _maxInterval) {
response.value = 0x0001; // reject
}
}
if (_supervisionTimeout) {
if (request->supervisionTimeout != _supervisionTimeout) {
response.value = 0x0001; // reject
}
}
HCI.sendAclPkt(handle, SIGNALING_CID, sizeof(response), &response);
if (response.value == 0x0000) {
HCI.leConnUpdate(handle, request->minInterval, request->maxInterval, request->latency, request->supervisionTimeout);
}
}
void L2CAPSignalingClass::connectionParameterUpdateResponse(uint16_t /*handle*/, uint8_t /*identifier*/, uint8_t /*dlen*/, uint8_t /*data*/[])
{
}
#if !defined(FAKE_L2CAP)
L2CAPSignalingClass L2CAPSignalingObj;
L2CAPSignalingClass& L2CAPSignaling = L2CAPSignalingObj;
#endif
================================================
FILE: src/utility/L2CAPSignaling.h
================================================
/*
This file is part of the ArduinoBLE library.
Copyright (c) 2018 Arduino SA. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _L2CAP_SIGNALING_H_
#define _L2CAP_SIGNALING_H_
#include
#define SIGNALING_CID 0x0005
#define SECURITY_CID 0x0006
#define CONNECTION_PAIRING_REQUEST 0x01
#define CONNECTION_PAIRING_RESPONSE 0x02
#define CONNECTION_PAIRING_CONFIRM 0x03
#define CONNECTION_PAIRING_RANDOM 0x04
#define CONNECTION_PAIRING_FAILED 0x05
#define CONNECTION_ENCRYPTION_INFORMATION 0x06
#define CONNECTION_MASTER_IDENTIFICATION 0x07
#define CONNECTION_IDENTITY_INFORMATION 0x08
#define CONNECTION_IDENTITY_ADDRESS 0x09
#define CONNECTION_SIGNING_INFORMATION 0x0A
#define CONNECTION_SECURITY_REQUEST 0x0B
#define CONNECTION_PAIRING_PUBLIC_KEY 0x0C
#define CONNECTION_PAIRING_DHKEY_CHECK 0x0D
#define CONNECTION_PAIRING_KEYPRESS 0x0E
#define IOCAP_DISPLAY_ONLY 0x00
#define IOCAP_DISPLAY_YES_NO 0x01
#define IOCAP_KEYBOARD_ONLY 0x02
#define IOCAP_NO_INPUT_NO_OUTPUT 0x03
#define IOCAP_KEYBOARD_DISPLAY 0x04
#define LOCAL_AUTHREQ 0b00101101
// #define LOCAL_IOCAP IOCAP_DISPLAY_ONLY // will use JustWorks pairing
class L2CAPSignalingClass {
public:
L2CAPSignalingClass();
virtual ~L2CAPSignalingClass();
virtual void addConnection(uint16_t handle, uint8_t role, uint8_t peerBdaddrType,
uint8_t peerBdaddr[6], uint16_t interval,
uint16_t latency, uint16_t supervisionTimeout,
uint8_t masterClockAccuracy);
virtual void handleData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void handleSecurityData(uint16_t connectionHandle, uint8_t dlen, uint8_t data[]);
virtual void removeConnection(uint8_t handle, uint16_t reason);
virtual void setConnectionInterval(uint16_t minInterval, uint16_t maxInterval);
virtual void setSupervisionTimeout(uint16_t supervisionTimeout);
virtual void setPairingEnabled(uint8_t enabled);
virtual bool isPairingEnabled();
virtual void smCalculateLTKandConfirm(uint16_t handle, uint8_t expectedEa[]);
private:
virtual void connectionParameterUpdateRequest(uint16_t handle, uint8_t identifier, uint8_t dlen, uint8_t data[]);
virtual void connectionParameterUpdateResponse(uint16_t handle, uint8_t identifier, uint8_t dlen, uint8_t data[]);
private:
uint16_t _minInterval;
uint16_t _maxInterval;
uint16_t _supervisionTimeout;
uint8_t _pairing_enabled;
};
extern L2CAPSignalingClass& L2CAPSignaling;
#endif
================================================
FILE: src/utility/bitDescriptions.cpp
================================================
#include "bitDescriptions.h"
#define BONDING_BIT 0b00000001
#define MITM_BIT 0b00000100
#define SC_BIT 0b00001000
#define KEYPRESS_BIT 0b00010000
#define CT2_BIT 0b00100000
AuthReq::AuthReq(){}
AuthReq::AuthReq(uint8_t octet):_octet(octet){}
bool AuthReq::Bonding(){ return (_octet & BONDING_BIT)>0;}
bool AuthReq::MITM(){ return (_octet & MITM_BIT)>0;}
bool AuthReq::SC(){ return (_octet & SC_BIT)>0;}
bool AuthReq::KeyPress(){ return (_octet & KEYPRESS_BIT)>0;}
bool AuthReq::CT2(){ return (_octet & CT2_BIT)>0;}
void AuthReq::setBonding(bool state) { _octet= state? _octet|BONDING_BIT : _octet&~BONDING_BIT;}
void AuthReq::setMITM(bool state) { _octet= state? _octet|MITM_BIT : _octet&~MITM_BIT;}
void AuthReq::setSC(bool state){ _octet= state? _octet|SC_BIT : _octet&~SC_BIT;}
void AuthReq::setKeyPress(bool state){ _octet= state? _octet|KEYPRESS_BIT : _octet&~KEYPRESS_BIT;}
void AuthReq::setCT2(bool state){ _octet= state? _octet|CT2_BIT : _octet&~CT2_BIT;}
uint8_t _octet;
void AuthReq::setOctet( uint8_t octet){_octet = octet;}
uint8_t AuthReq::getOctet() {return _octet;}
================================================
FILE: src/utility/bitDescriptions.h
================================================
#ifndef _BIT_DESCRIPTIONS_H_
#define _BIT_DESCRIPTIONS_H_
#include
class AuthReq{
public:
AuthReq();
AuthReq(uint8_t octet);
void setOctet( uint8_t octet);
uint8_t getOctet();
// The Bonding_Flags field is a 2-bit field that indicates the type of bonding being requested by the initiating device
bool Bonding();
// The MITM field is a 1-bit flag that is set to one if the device is requesting MITM protection
bool MITM();
// The SC field is a 1 bit flag. If LE Secure Connections pairing is supported by the device, then the SC field shall be set to 1, otherwise it shall be set to 0.
bool SC();
// The keypress field is a 1-bit flag that is used only in the Passkey Entry protocol and shall be ignored in other protocols.
bool KeyPress();
// The CT2 field is a 1-bit flag that shall be set to 1 upon transmission to indicate support for the h7 function.
bool CT2();
void setBonding(bool state);
void setMITM(bool state);
void setSC(bool state);
void setKeyPress(bool state);
void setCT2(bool state);
private:
uint8_t _octet;
};
enum IOCap {
DisplayOnly,
DisplayYesNo,
KeyboardOnly,
NoInputNoOutput,
KeyboardDisplay
};
#endif
================================================
FILE: src/utility/btct.cpp
================================================
#include "btct.h"
#include
#include "HCI.h"
#include "ArduinoBLE.h"
BluetoothCryptoToolbox::BluetoothCryptoToolbox(){}
// In step 1, AES-128 with key K is applied to an all-zero input block.
// In step 2, K1 is derived through the following operation:
// If the most significant bit of L is equal to 0, K1 is the left-shift
// of L by 1 bit.
// Otherwise, K1 is the exclusive-OR of const_Rb and the left-shift of L
// by 1 bit.
// In step 3, K2 is derived through the following operation:
// If the most significant bit of K1 is equal to 0, K2 is the left-shift
// of K1 by 1 bit.
// Otherwise, K2 is the exclusive-OR of const_Rb and the left-shift of
// K1 by 1 bit.
// In step 4, (K1,K2) := Generate_Subkey(K) is returned.
unsigned char const_Rb[16] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
};
#define DHKEY_LENGTH 32
#define N_LEN 16
#define ADDR_LEN 6
#define LEN_LTK 16
#define LEN_MAC_KEY 16
void BluetoothCryptoToolbox::printBytes(uint8_t bytes[], uint8_t length){
#ifdef _BLE_TRACE_
for(int i=0; i0){
Serial.print(", 0x");
}else{
Serial.print("0x");
}
Serial.print(bytes[i],HEX);
}
Serial.print('\n');
#else
(void)bytes;
(void)length;
#endif
}
int BluetoothCryptoToolbox::f5(uint8_t DHKey[],uint8_t N_master[], uint8_t N_slave[],
uint8_t BD_ADDR_master[], uint8_t BD_ADDR_slave[], uint8_t MacKey[], uint8_t LTK[])
{
uint8_t SALT[16] = {0x6C, 0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
uint8_t keyID[4] = {0x62, 0x74, 0x6c, 0x65};
uint8_t length[2];
length[0] = 0x01;
length[1] = 0x00;
#ifdef _BLE_TRACE_
Serial.print("Starting f5 calculation");
Serial.print("Using DHKey: ");
printBytes(DHKey, DHKEY_LENGTH);
Serial.print("Using N_Master: ");
printBytes(N_master, N_LEN);
Serial.print("Using N_Slave: ");
printBytes(N_slave, N_LEN);
Serial.println("Using BD_ADDR_MASTER: ");
printBytes(BD_ADDR_master, ADDR_LEN);
Serial.println("Using BD_ADDR_SLAVE: ");
printBytes(BD_ADDR_slave, ADDR_LEN);
#endif
uint8_t T[16];
struct __attribute__ ((packed)) CmacInput
{
uint8_t counter;
uint8_t keyID[4];
uint8_t N1[16];
uint8_t N2[16];
uint8_t A1[7];
uint8_t A2[7];
uint8_t length[2];
} cmacInput = {0,{0},{0},{0},{0},{0},{0}};
cmacInput.counter = 0;
memcpy(cmacInput.keyID, keyID, 4);
memcpy(cmacInput.N1,N_master,16);
memcpy(cmacInput.N2,N_slave,16);
memcpy(cmacInput.A1,BD_ADDR_master,7);
memcpy(cmacInput.A2,BD_ADDR_slave,7);
memcpy(cmacInput.length,length,2);
AES_CMAC(SALT, DHKey, 32, T);
AES_CMAC(T, (uint8_t*)&cmacInput,sizeof(cmacInput), MacKey);
cmacInput.counter=1;
AES_CMAC(T, (uint8_t*)&cmacInput, sizeof(cmacInput), LTK);
return 1;
}
int BluetoothCryptoToolbox::f6(uint8_t W[], uint8_t N1[],uint8_t N2[],uint8_t R[], uint8_t IOCap[], uint8_t A1[], uint8_t A2[], uint8_t Ex[])
{
struct __attribute__ ((packed)) F6Input
{
uint8_t N1[16];
uint8_t N2[16];
uint8_t R[16];
uint8_t IOCap[3];
uint8_t A1[7];
uint8_t A2[7];
} f6Input = {{0},{0},{0},{0},{0},{0}};
memcpy(f6Input.N1, N1, 16);
memcpy(f6Input.N2, N2, 16);
memcpy(f6Input.R, R, 16);
memcpy(f6Input.IOCap, IOCap, 3);
memcpy(f6Input.A1, A1, 7);
memcpy(f6Input.A2, A2, 7);
AES_CMAC(W, (uint8_t*)&f6Input, sizeof(f6Input),Ex);
return 1;
}
// AES_CMAC from RFC
int BluetoothCryptoToolbox::ah(uint8_t k[16], uint8_t r[3], uint8_t* result)
{
uint8_t r_[16];
int i=0;
for(i=0; i<16; i++) r_[i] = 0;
for(i=0; i<3; i++) r_[i+13] = r[i];
uint8_t intermediate[16];
AES_128(k,r_,intermediate);
for(i=0; i<3; i++){
result[i] = intermediate[i+13];
}
return 1;
}
void BluetoothCryptoToolbox::testAh()
{
uint8_t irk[16] = {0xec,0x02,0x34,0xa3,0x57,0xc8,0xad,0x05,0x34,0x10,0x10,0xa6,0x0a,0x39,0x7d,0x9b};
uint8_t expected_final[3] = {0x0d,0xfb,0xaa};
uint8_t ourResult[3];
ah(irk, expected_final, ourResult);
#ifdef _BLE_TRACE_
Serial.print("Expected : ");
printBytes(&expected_final[3], 3);
Serial.print("Actual : ");
printBytes(ourResult, 3);
#endif
}
int BluetoothCryptoToolbox::g2(uint8_t U[], uint8_t V[], uint8_t X[], uint8_t Y[], uint8_t out[4])
{
struct __attribute__ ((packed)) CmacInput {
uint8_t U[32];
uint8_t V[32];
uint8_t Y[16];
} cmacInput= {{0},{0},{0}};
memcpy(cmacInput.U,U,32);
memcpy(cmacInput.V,V,32);
memcpy(cmacInput.Y,Y,16);
uint8_t intermediate[16];
AES_CMAC(X,(uint8_t*)&cmacInput,sizeof(CmacInput),intermediate);
memcpy(out,&intermediate[12],4);
return 1;
}
void BluetoothCryptoToolbox::testg2(){
uint8_t U[32] = {0x20,0xb0,0x03,0xd2,0xf2,0x97,0xbe,0x2c,0x5e,0x2c,0x83,0xa7,0xe9,0xf9,0xa5,0xb9,0xef,0xf4,0x91,0x11,0xac,0xf4,0xfd,0xdb,0xcc,0x03,0x01,0x48,0x0e,0x35,0x9d,0xe6};
uint8_t V[32] = {0x55,0x18,0x8b,0x3d,0x32,0xf6,0xbb,0x9a,0x90,0x0a,0xfc,0xfb,0xee,0xd4,0xe7,0x2a,0x59,0xcb,0x9a,0xc2,0xf1,0x9d,0x7c,0xfb,0x6b,0x4f,0xdd,0x49,0xf4,0x7f,0xc5,0xfd};
uint8_t X[16] = {0xd5,0xcb,0x84,0x54,0xd1,0x77,0x73,0x3e,0xff,0xff,0xb2,0xec,0x71,0x2b,0xae,0xab};
uint8_t Y[16] = {0xa6,0xe8,0xe7,0xcc,0x25,0xa7,0x5f,0x6e,0x21,0x65,0x83,0xf7,0xff,0x3d,0xc4,0xcf};
uint8_t out[4];
g2(U,V,X,Y,out);
uint32_t result = 0;
for(int i=0; i<4; i++) result += out[i] << 8*i;
#ifdef _BLE_TRACE_
Serial.println("Expected : 0");
Serial.print("Result : ");
Serial.println(result);
Serial.println();
#endif
}
void BluetoothCryptoToolbox::AES_CMAC ( unsigned char *key, unsigned char *input, int length,
unsigned char *mac )
{
unsigned char X[16],Y[16], M_last[16], padded[16];
unsigned char K1[16], K2[16];
int n, i, flag;
generateSubkey(key,K1,K2);
n = (length+15) / 16; /* n is number of rounds */
if ( n == 0 ) {
n = 1;
flag = 0;
} else {
if ( (length%16) == 0 ) { /* last block is a complete block */
flag = 1;
} else { /* last block is not complete block */
flag = 0;
}
}
if ( flag ) { /* last block is complete block */
xor_128(&input[16*(n-1)],K1,M_last);
} else {
padding(&input[16*(n-1)],padded,length%16);
xor_128(padded,K2,M_last);
}
for ( i=0; i<16; i++ ) X[i] = 0;
for ( i=0; i=0; i-- ) {
output[i] = input[i] << 1;
output[i] |= overflow;
overflow = (input[i] & 0x80)?1:0;
}
return;
}
// From RFC
void BluetoothCryptoToolbox::xor_128(unsigned char *a, unsigned char *b, unsigned char *out)
{
int i;
for (i=0;i<16; i++)
{
out[i] = a[i] ^ b[i];
}
}
BluetoothCryptoToolbox btct;
================================================
FILE: src/utility/btct.h
================================================
#ifndef _BTCT_H_
#define _BTCT_H_
#include
// Implementation of functions defined in BTLE standard
class BluetoothCryptoToolbox{
public:
BluetoothCryptoToolbox();
void printBytes(uint8_t bytes[], uint8_t length);
void generateSubkey(uint8_t* K, uint8_t* K1, uint8_t* K2);
void AES_CMAC ( unsigned char *key, unsigned char *input, int length,
unsigned char *mac );
int f5(uint8_t DHKey[],uint8_t N_master[], uint8_t N_slave[],
uint8_t BD_ADDR_master[], uint8_t BD_ADDR_slave[], uint8_t MacKey[], uint8_t LTK[]);
int f6(uint8_t W[], uint8_t N1[],uint8_t N2[],uint8_t R[], uint8_t IOCap[], uint8_t A1[], uint8_t A2[], uint8_t Ex[]);
int g2(uint8_t U[], uint8_t V[], uint8_t X[], uint8_t Y[], uint8_t out[4]);
int ah(uint8_t k[16], uint8_t r[3], uint8_t result[3]);
void test();
void testF5();
void testF6();
void testAh();
void testg2();
private:
int AES_128(uint8_t key[], uint8_t data_in[], uint8_t data_out[]);
void leftshift_onebit(unsigned char *input,unsigned char *output);
void xor_128(unsigned char *a, unsigned char *b, unsigned char *out);
void padding ( unsigned char *lastb, unsigned char *pad, int length );
};
extern BluetoothCryptoToolbox btct;
#endif
================================================
FILE: src/utility/keyDistribution.cpp
================================================
#include "keyDistribution.h"
KeyDistribution::KeyDistribution():_octet(0){}
KeyDistribution::KeyDistribution(uint8_t octet):_octet(octet){}
#define ENCKEY 0b00000001
#define IDKEY 0b00000010
#define SIGNKEY 0b00000100
#define LINKKEY 0b00001000
void KeyDistribution::setOctet( uint8_t octet){_octet = octet;}
uint8_t KeyDistribution::getOctet() {return _octet;}
// Ignored when SMP is on LE transport
bool KeyDistribution::EncKey(){ return (_octet & ENCKEY)>0;}
// Device shall distribute IRK using Identity information command followed by its address using Identity address information
bool KeyDistribution::IdKey(){ return (_octet & IDKEY)>0;}
// Device shall distribute CSRK using signing information command
bool KeyDistribution::SignKey(){ return (_octet & SIGNKEY)>0;}
// Device would like to derive BR/EDR from LTK
bool KeyDistribution::LinkKey(){ return (_octet & LINKKEY)>0;}
void KeyDistribution::setEncKey(bool state) { _octet= state? _octet|ENCKEY : _octet&~ENCKEY;}
void KeyDistribution::setIdKey(bool state) { _octet= state? _octet|IDKEY : _octet&~IDKEY;}
void KeyDistribution::setSignKey(bool state){ _octet= state? _octet|SIGNKEY : _octet&~SIGNKEY;}
void KeyDistribution::setLinkKey(bool state){ _octet= state? _octet|LINKKEY : _octet&~LINKKEY;}
================================================
FILE: src/utility/keyDistribution.h
================================================
#ifndef _KEY_DISTRIBUTION_H_
#define _KEY_DISTRIBUTION_H_
#include
class KeyDistribution{
public:
KeyDistribution();
KeyDistribution(uint8_t octet);
void setOctet( uint8_t octet);
uint8_t getOctet();
// Ignored when SMP is on LE transport
bool EncKey();
// Device shall distribute IRK using Identity information command followed by its address using Identity address information
bool IdKey();
// Device shall distribute CSRK using signing information command
bool SignKey();
// Device would like to derive BR/EDR from LTK
bool LinkKey();
void setEncKey(bool state);
void setIdKey(bool state);
void setSignKey(bool state);
void setLinkKey(bool state);
private:
uint8_t _octet;
// 1. IRK by the slave2. BD ADDR by the slave3. CSRK by the slave4. IRK by the master5. BD_ADDR by the master6. CSRK by the master
};
#endif