diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..f2bfa724 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# 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" diff --git a/.github/workflows/compile-examples.yml b/.github/workflows/compile-examples.yml index 884f11d6..a1faf997 100644 --- a/.github/workflows/compile-examples.yml +++ b/.github/workflows/compile-examples.yml @@ -1,22 +1,24 @@ name: Compile Examples -on: [push, pull_request] +on: + - push + - pull_request + jobs: - build: - runs-on: ubuntu-latest + build: + runs-on: ubuntu-latest - strategy: - matrix: - fqbn: [ - "arduino:samd:mkrwifi1010", - "arduino:samd:nano_33_iot", - "arduino:megaavr:uno2018:mode=on", - "arduino:mbed:nano33ble" - ] + strategy: + matrix: + fqbn: + - arduino:samd:mkrwifi1010 + - arduino:samd:nano_33_iot + - arduino:megaavr:uno2018:mode=on + - arduino:mbed:nano33ble + - arduino:mbed_nano:nanorp2040connect - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - uses: arduino/actions/libraries/compile-examples@master - with: - fqbn: ${{ matrix.fqbn }} + steps: + - uses: actions/checkout@v3 + - uses: arduino/compile-sketches@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + fqbn: ${{ matrix.fqbn }} diff --git a/.github/workflows/spell-check.yml b/.github/workflows/spell-check.yml index 7b45d77e..0cbdde58 100644 --- a/.github/workflows/spell-check.yml +++ b/.github/workflows/spell-check.yml @@ -1,11 +1,16 @@ name: Spell Check + on: [push, pull_request] + jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - uses: arduino/actions/libraries/spell-check@master + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Spell check + uses: arduino/actions/libraries/spell-check@master + with: + skip-paths: ./extras/test \ No newline at end of file diff --git a/.github/workflows/sync-labels.yml b/.github/workflows/sync-labels.yml new file mode 100644 index 00000000..94938f35 --- /dev/null +++ b/.github/workflows/sync-labels.yml @@ -0,0 +1,138 @@ +# 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@v3 + + - 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@v3 + 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@v3 + + - name: Download configuration files artifact + uses: actions/download-artifact@v3 + with: + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + path: ${{ env.CONFIGURATIONS_FOLDER }} + + - name: Remove unneeded artifact + uses: geekyeggo/delete-artifact@v2 + 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 }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..9bea4330 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ + +.DS_Store diff --git a/README.md b/README.md index b2f649ca..9ec934a3 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,9 @@ [![Compile Examples Status](https://github.com/arduino-libraries/ArduinoBLE/workflows/Compile%20Examples/badge.svg)](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Compile+Examples) [![Spell Check Status](https://github.com/arduino-libraries/ArduinoBLE/workflows/Spell%20Check/badge.svg)](https://github.com/arduino-libraries/ArduinoBLE/actions?workflow=Spell+Check) -Enables BLE connectivity on the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev.2, Arduino Nano 33 IoT, and Arduino Nano 33 BLE. +Enables Bluetooth® Low Energy connectivity on the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev.2, Arduino Nano 33 IoT, and Arduino Nano 33 BLE. -This library supports creating a BLE peripheral and BLE central mode. +This library supports creating a Bluetooth® Low Energy peripheral & central mode. For the Arduino MKR WiFi 1010, Arduino UNO WiFi Rev.2, and Arduino Nano 33 IoT boards, it requires the NINA module to be running [Arduino NINA-W102 firmware](https://github.com/arduino/nina-fw) v1.2.0 or later. diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 00000000..636fe52c --- /dev/null +++ b/docs/api.md @@ -0,0 +1,3859 @@ +# 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 “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 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 batteryLevelCharacterisic = peripheral.characteristic("2a19"); + + if (batteryLevelCharacterisic) { + // 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(" characteristis 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 BLECharateristic 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 batteryLevelCharacterisic = peripheral.characteristic("2a19"); + + if (batteryLevelCharacterisic) { + // 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, value, valueSize) +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 +- **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"); + } + +``` diff --git a/docs/readme.md b/docs/readme.md new file mode 100644 index 00000000..5a52d988 --- /dev/null +++ b/docs/readme.md @@ -0,0 +1,91 @@ +# 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 Rev 2, 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 Blueooth 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. + +![Communication between central and peripheral devices](https://www.arduino.cc/en/uploads/Reference/ble-bulletin-board-model.png) + +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 acknowledgement 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](https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx). + +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 a 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. diff --git a/examples/Central/LedControl/LedControl.ino b/examples/Central/LedControl/LedControl.ino index 8301a311..953de7d8 100644 --- a/examples/Central/LedControl/LedControl.ino +++ b/examples/Central/LedControl/LedControl.ino @@ -1,9 +1,9 @@ /* LED Control - This example scans for BLE peripherals until one with the advertised service + 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 BLE Peripheral's LED, when the button is pressed or released. + 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, @@ -29,10 +29,10 @@ void setup() { // configure the button pin as input pinMode(buttonPin, INPUT); - // initialize the BLE hardware + // initialize the Bluetooth® Low Energy hardware BLE.begin(); - Serial.println("BLE Central - LED control"); + Serial.println("Bluetooth® Low Energy Central - LED control"); // start scanning for peripherals BLE.scanForUuid("19b10000-e8f2-537e-4f6c-d104768a1214"); diff --git a/examples/Central/PeripheralExplorer/PeripheralExplorer.ino b/examples/Central/PeripheralExplorer/PeripheralExplorer.ino index 100225d6..919cdde0 100644 --- a/examples/Central/PeripheralExplorer/PeripheralExplorer.ino +++ b/examples/Central/PeripheralExplorer/PeripheralExplorer.ino @@ -1,7 +1,7 @@ /* Peripheral Explorer - This example scans for BLE peripherals until one with a particular name ("LED") + 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: @@ -22,12 +22,12 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } - Serial.println("BLE Central - Peripheral Explorer"); + Serial.println("Bluetooth® Low Energy Central - Peripheral Explorer"); // start scanning for peripherals BLE.scan(); diff --git a/examples/Central/Scan/Scan.ino b/examples/Central/Scan/Scan.ino index 784f3058..162e3c07 100644 --- a/examples/Central/Scan/Scan.ino +++ b/examples/Central/Scan/Scan.ino @@ -1,8 +1,8 @@ /* Scan - This example scans for BLE peripherals and prints out their advertising details: - address, local name, adverised service UUID's. + 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, @@ -19,12 +19,12 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } - Serial.println("BLE Central scan"); + Serial.println("Bluetooth® Low Energy Central scan"); // start scanning for peripheral BLE.scan(); diff --git a/examples/Central/ScanCallback/ScanCallback.ino b/examples/Central/ScanCallback/ScanCallback.ino index 9583079c..2687a3b9 100644 --- a/examples/Central/ScanCallback/ScanCallback.ino +++ b/examples/Central/ScanCallback/ScanCallback.ino @@ -1,8 +1,8 @@ /* Scan Callback - This example scans for BLE peripherals and prints out their advertising details: - address, local name, adverised service UUIDs. Unlike the Scan example, it uses + 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. @@ -21,12 +21,12 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } - Serial.println("BLE Central scan callback"); + Serial.println("Bluetooth® Low Energy Central scan callback"); // set the discovered event handle BLE.setEventHandler(BLEDiscovered, bleCentralDiscoverHandler); diff --git a/examples/Central/SensorTagButton/SensorTagButton.ino b/examples/Central/SensorTagButton/SensorTagButton.ino index 72dad90b..a56504f6 100644 --- a/examples/Central/SensorTagButton/SensorTagButton.ino +++ b/examples/Central/SensorTagButton/SensorTagButton.ino @@ -1,7 +1,7 @@ /* SensorTag Button - This example scans for BLE peripherals until a TI SensorTag is discovered. + 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 @@ -23,12 +23,12 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } - Serial.println("BLE Central - SensorTag button"); + Serial.println("Bluetooth® Low Energy Central - SensorTag button"); Serial.println("Make sure to turn on the device."); // start scanning for peripheral diff --git a/examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino b/examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino new file mode 100644 index 00000000..979b69a8 --- /dev/null +++ b/examples/Peripheral/Advertising/EnhancedAdvertising/EnhancedAdvertising.ino @@ -0,0 +1,44 @@ +#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("failed to initialize BLE!"); + 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(); +} diff --git a/examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino b/examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino new file mode 100644 index 00000000..d025dd62 --- /dev/null +++ b/examples/Peripheral/Advertising/RawDataAdvertising/RawDataAdvertising.ino @@ -0,0 +1,41 @@ +#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("failed to initialize BLE!"); + 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(); +} diff --git a/examples/Peripheral/BatteryMonitor/BatteryMonitor.ino b/examples/Peripheral/BatteryMonitor/BatteryMonitor.ino index 6c5d3d30..f013c6f5 100644 --- a/examples/Peripheral/BatteryMonitor/BatteryMonitor.ino +++ b/examples/Peripheral/BatteryMonitor/BatteryMonitor.ino @@ -1,14 +1,14 @@ /* Battery Monitor - This example creates a BLE peripheral with the standard battery service and + 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 BLE central app, like LightBlue (iOS and Android) or + 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. @@ -17,10 +17,10 @@ #include - // BLE Battery Service + // Bluetooth® Low Energy Battery Service BLEService batteryService("180F"); -// BLE Battery Level Characteristic +// 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 @@ -40,9 +40,9 @@ void setup() { while (1); } - /* Set a local name for the BLE device + /* 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 BLE device + 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"); @@ -51,18 +51,18 @@ void setup() { BLE.addService(batteryService); // Add the battery service batteryLevelChar.writeValue(oldBatteryLevel); // set initial value for this characteristic - /* Start advertising BLE. It will start continuously transmitting BLE - advertising packets and will be visible to remote BLE central devices + /* 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..."); + Serial.println("Bluetooth® device active, waiting for connections..."); } void loop() { - // wait for a BLE central + // wait for a Bluetooth® Low Energy central BLEDevice central = BLE.central(); // if a central is connected to the peripheral: diff --git a/examples/Peripheral/ButtonLED/ButtonLED.ino b/examples/Peripheral/ButtonLED/ButtonLED.ino index bd373731..cbc14dd8 100644 --- a/examples/Peripheral/ButtonLED/ButtonLED.ino +++ b/examples/Peripheral/ButtonLED/ButtonLED.ino @@ -1,7 +1,7 @@ /* Button LED - This example creates a BLE peripheral with service that contains a + 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. @@ -10,7 +10,7 @@ Arduino Nano 33 BLE, or Arduino Nano 33 BLE Sense board. - Button connected to pin 4 - You can use a generic BLE central app, like LightBlue (iOS and Android) or + 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. @@ -38,7 +38,7 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } @@ -61,18 +61,18 @@ void setup() { // start advertising BLE.advertise(); - Serial.println("Bluetooth device active, waiting for connections..."); + Serial.println("Bluetooth® device active, waiting for connections..."); } void loop() { - // poll for BLE events + // 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 - boolean buttonChanged = (buttonCharacteristic.value() != buttonValue); + bool buttonChanged = (buttonCharacteristic.value() != buttonValue); if (buttonChanged) { // button state changed, update characteristics diff --git a/examples/Peripheral/CallbackLED/CallbackLED.ino b/examples/Peripheral/CallbackLED/CallbackLED.ino index a874a77b..23f67bc3 100644 --- a/examples/Peripheral/CallbackLED/CallbackLED.ino +++ b/examples/Peripheral/CallbackLED/CallbackLED.ino @@ -1,7 +1,7 @@ /* Callback LED - This example creates a BLE peripheral with service that contains a + 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. @@ -9,7 +9,7 @@ - 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 + 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. @@ -33,7 +33,7 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } @@ -61,11 +61,11 @@ void setup() { // start advertising BLE.advertise(); - Serial.println(("Bluetooth device active, waiting for connections...")); + Serial.println(("Bluetooth® device active, waiting for connections...")); } void loop() { - // poll for BLE events + // poll for Bluetooth® Low Energy events BLE.poll(); } diff --git a/examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino b/examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino new file mode 100644 index 00000000..9f9d453b --- /dev/null +++ b/examples/Peripheral/EncryptedBatteryMonitor/EncryptedBatteryMonitor.ino @@ -0,0 +1,265 @@ +/* + 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_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[6]; + sprintf(code, "%06d", confirmCode); + Serial.println(code); + }); + + // Callback to allow accepting or rejecting pairing + BLE.setBinaryConfirmPairing([&acceptOrReject](){ + 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 BLE failed!"); + delay(200); + continue; + } + 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 + char* stringCharValue = new char[32]; + 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 30s"); + } else if (BLE.pairable() && millis() > pairingStarted + PAIR_INTERVAL){ + BLE.setPairable(false); + Serial.println("No longer accepting pairing"); + } + // Make LED blink while pairing is allowed + digitalWrite(PAIR_LED, (BLE.pairable() ? (millis()%400)<200 : BLE.paired()) ? PAIR_LED_ON : !PAIR_LED_ON); + + + // 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 + } +} \ No newline at end of file diff --git a/examples/Peripheral/LED/LED.ino b/examples/Peripheral/LED/LED.ino index 1ede6535..2e6d6db9 100644 --- a/examples/Peripheral/LED/LED.ino +++ b/examples/Peripheral/LED/LED.ino @@ -1,14 +1,14 @@ /* LED - This example creates a BLE peripheral with service that contains a + 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 BLE central app, like LightBlue (iOS and Android) or + 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. @@ -17,9 +17,9 @@ #include -BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service +BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // Bluetooth® Low Energy LED Service -// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central +// 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 @@ -33,7 +33,7 @@ void setup() { // begin initialization if (!BLE.begin()) { - Serial.println("starting BLE failed!"); + Serial.println("starting Bluetooth® Low Energy module failed!"); while (1); } @@ -58,7 +58,7 @@ void setup() { } void loop() { - // listen for BLE peripherals to connect: + // listen for Bluetooth® Low Energy peripherals to connect: BLEDevice central = BLE.central(); // if a central is connected to peripheral: diff --git a/extras/arduino-ble-parser.py b/extras/arduino-ble-parser.py new file mode 100644 index 00000000..8f678711 --- /dev/null +++ b/extras/arduino-ble-parser.py @@ -0,0 +1,85 @@ +''' +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) + diff --git a/extras/test/.gitignore b/extras/test/.gitignore new file mode 100644 index 00000000..c795b054 --- /dev/null +++ b/extras/test/.gitignore @@ -0,0 +1 @@ +build \ No newline at end of file diff --git a/extras/test/CMakeLists.txt b/extras/test/CMakeLists.txt new file mode 100644 index 00000000..bbba16ca --- /dev/null +++ b/extras/test/CMakeLists.txt @@ -0,0 +1,126 @@ +########################################################################## + +set(CMAKE_VERBOSE_MAKEFILE ON) +cmake_minimum_required(VERSION 2.8) + +########################################################################## + +project(testArduinoBLE) + +########################################################################## + +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/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(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}) + +########################################################################## + +include_directories(include) +include_directories(include/util) +include_directories(../../src) +include_directories(../../src/local) +include_directories(../../src/remote) +include_directories(../../src/utility) +include_directories(external/catch/v2.12.1/include) + +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_compile_definitions(TEST_TARGET_DISC_DEVICE PUBLIC FAKE_GAP) +target_compile_definitions(TEST_TARGET_ADVERTISING_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 +) diff --git a/extras/test/external/catch/v2.12.1/include/catch.hpp b/extras/test/external/catch/v2.12.1/include/catch.hpp new file mode 100644 index 00000000..1d2c9bb6 --- /dev/null +++ b/extras/test/external/catch/v2.12.1/include/catch.hpp @@ -0,0 +1,17698 @@ +/* + * Catch v2.12.1 + * Generated: 2020-04-21 19:29:20.964532 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +// start catch.hpp + + +#define CATCH_VERSION_MAJOR 2 +#define CATCH_VERSION_MINOR 12 +#define CATCH_VERSION_PATCH 1 + +#ifdef __clang__ +# pragma clang system_header +#elif defined __GNUC__ +# pragma GCC system_header +#endif + +// start catch_suppress_warnings.h + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(push) +# pragma warning(disable: 161 1682) +# else // __ICC +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +# pragma clang diagnostic ignored "-Wswitch-enum" +# pragma clang diagnostic ignored "-Wcovered-switch-default" +# endif +#elif defined __GNUC__ + // Because REQUIREs trigger GCC's -Wparentheses, and because still + // supported version of g++ have only buggy support for _Pragmas, + // Wparentheses have to be suppressed globally. +# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details + +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wpadded" +#endif +// end catch_suppress_warnings.h +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +# define CATCH_IMPL +# define CATCH_CONFIG_ALL_PARTS +#endif + +// In the impl file, we want to have access to all parts of the headers +// Can also be used to sanely support PCHs +#if defined(CATCH_CONFIG_ALL_PARTS) +# define CATCH_CONFIG_EXTERNAL_INTERFACES +# if defined(CATCH_CONFIG_DISABLE_MATCHERS) +# undef CATCH_CONFIG_DISABLE_MATCHERS +# endif +# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +# endif +#endif + +#if !defined(CATCH_CONFIG_IMPL_ONLY) +// start catch_platform.h + +#ifdef __APPLE__ +# include +# if TARGET_OS_OSX == 1 +# define CATCH_PLATFORM_MAC +# elif TARGET_OS_IPHONE == 1 +# define CATCH_PLATFORM_IPHONE +# endif + +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX + +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) +# define CATCH_PLATFORM_WINDOWS +#endif + +// end catch_platform.h + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// start catch_user_interfaces.h + +namespace Catch { + unsigned int rngSeed(); +} + +// end catch_user_interfaces.h +// start catch_tag_alias_autoregistrar.h + +// start catch_common.h + +// start catch_compiler_capabilities.h + +// Detect a number of compiler features - by compiler +// The following features are defined: +// +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +#ifdef __cplusplus + +# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define CATCH_CPP14_OR_GREATER +# endif + +# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define CATCH_CPP17_OR_GREATER +# endif + +#endif + +#if defined(__cpp_lib_uncaught_exceptions) +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif + +// We have to avoid both ICC and Clang, because they try to mask themselves +// as gcc, and we want only GCC in this block +#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" ) + +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) + +#endif + +#if defined(__clang__) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" ) + +// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug +// which results in calls to destructors being emitted for each temporary, +// without a matching initialization. In practice, this can result in something +// like `std::string::~string` being called on an uninitialized value. +// +// For example, this code will likely segfault under IBM XL: +// ``` +// REQUIRE(std::string("12") + "34" == "1234") +// ``` +// +// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented. +# if !defined(__ibmxl__) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg) */ +# endif + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) + +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \ + _Pragma( "clang diagnostic ignored \"-Wunused-template\"" ) + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Assume that non-Windows platforms support posix signals by default +#if !defined(CATCH_PLATFORM_WINDOWS) + #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#endif + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) + #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Android somehow still does not support std::to_string +#if defined(__ANDROID__) +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Not all Windows environments support SEH properly +#if defined(__MINGW32__) +# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#endif + +//////////////////////////////////////////////////////////////////////////////// +// PS4 +#if defined(__ORBIS__) +# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 +# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ + && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) + +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING + +# endif +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#if defined(_MSC_VER) + +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) ) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) ) + +# if _MSC_VER >= 1900 // Visual Studio 2015 or newer +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +# endif + +// Universal Windows platform does not support SEH +// Or console colours (or console at all...) +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define CATCH_CONFIG_COLOUR_NONE +# else +# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +# endif + +// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ +// _MSVC_TRADITIONAL == 0 means new conformant preprocessor +// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor +# if !defined(__clang__) // Handle Clang masquerading for msvc +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif // MSVC_TRADITIONAL +# endif // __clang__ + +#endif // _MSC_VER + +#if defined(_REENTRANT) || defined(_MSC_VER) +// Enable async processing, as -pthread is specified or no additional linking is required +# define CATCH_INTERNAL_CONFIG_USE_ASYNC +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// Check if we are compiled with -fno-exceptions or equivalent +#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) +# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#endif + +//////////////////////////////////////////////////////////////////////////////// +// DJGPP +#ifdef __DJGPP__ +# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#endif // __DJGPP__ + +//////////////////////////////////////////////////////////////////////////////// +// Embarcadero C++Build +#if defined(__BORLANDC__) + #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// Use of __COUNTER__ is suppressed during code analysis in +// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly +// handled by it. +// Otherwise all supported compilers support COUNTER macro, +// but user still might want to turn it off +#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// RTX is a special version of Windows that is real time. +// This means that it is detected as Windows, but does not provide +// the same set of capabilities as real Windows does. +#if defined(UNDER_RTSS) || defined(RTX64_BUILD) + #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH + #define CATCH_INTERNAL_CONFIG_NO_ASYNC + #define CATCH_CONFIG_COLOUR_NONE +#endif + +#if !defined(_GLIBCXX_USE_C99_MATH_TR1) +#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Various stdlib support checks that require __has_include +#if defined(__has_include) + // Check if string_view is available and usable + #if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW + #endif + + // Check if optional is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if byte is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # define CATCH_INTERNAL_CONFIG_CPP17_BYTE + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) + + // Check if variant is available and usable + # if __has_include() && defined(CATCH_CPP17_OR_GREATER) + # if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 + # include + # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # define CATCH_CONFIG_NO_CPP17_VARIANT + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) + # else + # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT + # endif // defined(__clang__) && (__clang_major__ < 8) + # endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // defined(__has_include) + +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif +// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +# define CATCH_CONFIG_WCHAR +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) +# define CATCH_CONFIG_CPP11_TO_STRING +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) +# define CATCH_CONFIG_CPP17_OPTIONAL +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) +# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +# define CATCH_CONFIG_CPP17_STRING_VIEW +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) +# define CATCH_CONFIG_CPP17_VARIANT +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE) +# define CATCH_CONFIG_CPP17_BYTE +#endif + +#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) +# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) +# define CATCH_CONFIG_NEW_CAPTURE +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) +# define CATCH_CONFIG_POLYFILL_ISNAN +#endif + +#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC) +# define CATCH_CONFIG_USE_ASYNC +#endif + +#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE) +# define CATCH_CONFIG_ANDROID_LOGWRITE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER) +# define CATCH_CONFIG_GLOBAL_NEXTAFTER +#endif + +// Even if we do not think the compiler has that warning, we still have +// to provide a macro that can be used by the code. +#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION) +# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS +#endif + +// The goal of this macro is to avoid evaluation of the arguments, but +// still have the compiler warn on problems inside... +#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN) +# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) +#endif + +#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#elif defined(__clang__) && (__clang_major__ < 5) +# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS +#endif + +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_TRY if ((true)) +#define CATCH_CATCH_ALL if ((false)) +#define CATCH_CATCH_ANON(type) if ((false)) +#else +#define CATCH_TRY try +#define CATCH_CATCH_ALL catch (...) +#define CATCH_CATCH_ANON(type) catch (type) +#endif + +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif + +// end catch_compiler_capabilities.h +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#include +#include +#include + +// We need a dummy global operator<< so we can bring it into Catch namespace later +struct Catch_global_namespace_dummy {}; +std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); + +namespace Catch { + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; + + protected: + NonCopyable(); + virtual ~NonCopyable(); + }; + + struct SourceLineInfo { + + SourceLineInfo() = delete; + SourceLineInfo( char const* _file, std::size_t _line ) noexcept + : file( _file ), + line( _line ) + {} + + SourceLineInfo( SourceLineInfo const& other ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo( SourceLineInfo&& ) noexcept = default; + SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + + bool empty() const noexcept { return file[0] == '\0'; } + bool operator == ( SourceLineInfo const& other ) const noexcept; + bool operator < ( SourceLineInfo const& other ) const noexcept; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // Bring in operator<< from global namespace into Catch namespace + // This is necessary because the overload of operator<< above makes + // lookup stop at namespace Catch + using ::operator<<; + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() const; + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) + +// end catch_common.h +namespace Catch { + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION + +// end catch_tag_alias_autoregistrar.h +// start catch_test_registry.h + +// start catch_interfaces_testcase.h + +#include + +namespace Catch { + + class TestSpec; + + struct ITestInvoker { + virtual void invoke () const = 0; + virtual ~ITestInvoker(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool isThrowSafe( TestCase const& testCase, IConfig const& config ); + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +// end catch_interfaces_testcase.h +// start catch_stringref.h + +#include +#include +#include +#include + +namespace Catch { + + /// A non-owning string class (similar to the forthcoming std::string_view) + /// Note that, because a StringRef may be a substring of another string, + /// it may not be null terminated. + class StringRef { + public: + using size_type = std::size_t; + using const_iterator = const char*; + + private: + static constexpr char const* const s_empty = ""; + + char const* m_start = s_empty; + size_type m_size = 0; + + public: // construction + constexpr StringRef() noexcept = default; + + StringRef( char const* rawChars ) noexcept; + + constexpr StringRef( char const* rawChars, size_type size ) noexcept + : m_start( rawChars ), + m_size( size ) + {} + + StringRef( std::string const& stdString ) noexcept + : m_start( stdString.c_str() ), + m_size( stdString.size() ) + {} + + explicit operator std::string() const { + return std::string(m_start, m_size); + } + + public: // operators + auto operator == ( StringRef const& other ) const noexcept -> bool; + auto operator != (StringRef const& other) const noexcept -> bool { + return !(*this == other); + } + + auto operator[] ( size_type index ) const noexcept -> char { + assert(index < m_size); + return m_start[index]; + } + + public: // named queries + constexpr auto empty() const noexcept -> bool { + return m_size == 0; + } + constexpr auto size() const noexcept -> size_type { + return m_size; + } + + // Returns the current start pointer. If the StringRef is not + // null-terminated, throws std::domain_exception + auto c_str() const -> char const*; + + public: // substrings and searches + // Returns a substring of [start, start + length). + // If start + length > size(), then the substring is [start, size()). + // If start > size(), then the substring is empty. + auto substr( size_type start, size_type length ) const noexcept -> StringRef; + + // Returns the current start pointer. May not be null-terminated. + auto data() const noexcept -> char const*; + + constexpr auto isNullTerminated() const noexcept -> bool { + return m_start[m_size] == '\0'; + } + + public: // iterators + constexpr const_iterator begin() const { return m_start; } + constexpr const_iterator end() const { return m_start + m_size; } + }; + + auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; + auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + + constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + return StringRef( rawChars, size ); + } +} // namespace Catch + +constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { + return Catch::StringRef( rawChars, size ); +} + +// end catch_stringref.h +// start catch_preprocessor.hpp + + +#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ +#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) + +#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ +// MSVC needs more evaluations +#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#else +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#endif + +#define CATCH_REC_END(...) +#define CATCH_REC_OUT + +#define CATCH_EMPTY() +#define CATCH_DEFER(id) id CATCH_EMPTY() + +#define CATCH_REC_GET_END2() 0, CATCH_REC_END +#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 +#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 +#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) + +#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) + +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) + +// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, +// and passes userdata as the first parameter to each invocation, +// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ +#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#else +// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) +#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#endif + +#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__ +#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name) + +#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper()) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#else +#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper())) +#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#endif + +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__) + +#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0) +#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1) +#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2) +#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3) +#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4) +#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5) +#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6) +#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7) +#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8) +#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9) +#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10) + +#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N + +#define INTERNAL_CATCH_TYPE_GEN\ + template struct TypeList {};\ + template\ + constexpr auto get_wrapper() noexcept -> TypeList { return {}; }\ + template class...> struct TemplateTypeList{};\ + template class...Cs>\ + constexpr auto get_wrapper() noexcept -> TemplateTypeList { return {}; }\ + template\ + struct append;\ + template\ + struct rewrap;\ + template class, typename...>\ + struct create;\ + template class, typename>\ + struct convert;\ + \ + template \ + struct append { using type = T; };\ + template< template class L1, typename...E1, template class L2, typename...E2, typename...Rest>\ + struct append, L2, Rest...> { using type = typename append, Rest...>::type; };\ + template< template class L1, typename...E1, typename...Rest>\ + struct append, TypeList, Rest...> { using type = L1; };\ + \ + template< template class Container, template class List, typename...elems>\ + struct rewrap, List> { using type = TypeList>; };\ + template< template class Container, template class List, class...Elems, typename...Elements>\ + struct rewrap, List, Elements...> { using type = typename append>, typename rewrap, Elements...>::type>::type; };\ + \ + template