diff --git a/.github/coding-convention-tool b/.github/coding-convention-tool deleted file mode 160000 index bd0d672..0000000 --- a/.github/coding-convention-tool +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bd0d672ee66ada2787bfc3b58e8b64e933b2c777 diff --git a/.github/workflows/00-Check-Code-Convention.yml b/.github/workflows/00-Check-Code-Convention.yml index 5c7f503..6cdd654 100644 --- a/.github/workflows/00-Check-Code-Convention.yml +++ b/.github/workflows/00-Check-Code-Convention.yml @@ -8,88 +8,38 @@ on: workflow_dispatch: inputs: branch: - description: 'Branch to test' + description: "Branch to test" type: string - default: 'master' + default: "main" jobs: job1: name: Check coding convention - runs-on: ubuntu-22.04 #uncrustify 0.64 can not be compiled on ubuntu-24.04 + runs-on: ubuntu-22.04 steps: - - name: Trigger - run: echo "Triggered by ${{github.event_name}} event" - - name: Check Branch Input - run: | - if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then - if [ -z "${{ github.event.inputs.branch }}" ]; then - echo "Branch input is required for manual trigger." - exit 1 - fi + - name: Trigger + run: echo "Triggered by ${{github.event_name}} event" + - name: Check Branch Input + run: | + if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then + if [ -z "${{ github.event.inputs.branch }}" ]; then + echo "Branch input is required for manual trigger." + exit 1 fi - - name: Checkout - uses: actions/checkout@v4.1.7 - with: - ref: "${{ github.event_name == 'workflow_dispatch' && github.event.inputs.branch || github.ref }}" - submodules: true - fetch-depth: 0 - - name: Log Current Branch and Commit - run: | + fi + - name: Checkout + uses: actions/checkout@v4.1.7 + with: + ref: "${{ github.event_name == 'workflow_dispatch' && github.event.inputs.branch || github.ref }}" + submodules: true + fetch-depth: 0 + - name: Log Current Branch and Commit + run: | echo "Current branch: $(git rev-parse --abbrev-ref HEAD)" echo "Current commit: $(git rev-parse HEAD)" - - name: Install commit check tools - run: | - echo "Installing pre-commit ..." - python3 -m pip install pre-commit - echo "Installing uncrustify 0.64 from source code ..." - sudo apt-get install --no-install-recommends -y\ - binutils ca-certificates git cmake make \ - gcc g++ binutils libc6-dev - echo "Cloning Uncrustify repository..." - git clone -b uncrustify-0.64 --single-branch https://github.com/uncrustify/uncrustify.git - echo "Building and installing Uncrustify..." - mkdir ./uncrustify/build && cd ./uncrustify/build - cmake -D CMAKE_INSTALL_PREFIX=/usr/local -D CMAKE_BUILD_TYPE=RelWithDebInfo ../ - sudo make -j "$(nproc)" - sudo make install - echo "Uncrustify has been installed successfully!" - cd ../../ - sudo cp ./.github/coding-convention-tool/tools/uncrustify/uncrustify.cfg ./uncrustify/uncrustify.cfg - echo "Install clang-tidy" - sudo apt-get install clang-tidy - - name: Apply custom formatting configuration - run: | - echo "Applying custom formatting configuration..." - chmod +x ./.github/coding-convention-tool/project_custom_config_handler.sh - ./.github/coding-convention-tool/project_custom_config_handler.sh - - - name: Run test - run: | - pre-commit install --config .github/coding-convention-tool/.pre-commit-config.yaml - pre-commit run --config .github/coding-convention-tool/.pre-commit-config.yaml --all-files 2>&1 | tee CodingConventionTool.txt - git diff > code-fix.patch || echo "No changes to patch." - ls -lah code-fix.patch - - - name: Upload Result - uses: actions/upload-artifact@v4.3.4 - with: - name: CodingConventionResult - path: CodingConventionTool.txt - retention-days: 90 - - name: Upload Patch - uses: actions/upload-artifact@v4.3.4 - with: - name: code-fix.patch - path: code-fix.patch - retention-days: 90 - - name: Check log file to set status of the job - run: | - keywords=("Failed") - for keyword in "${keywords[@]}"; do - if grep -q "$keyword" CodingConventionTool.txt; then - echo "Keyword '$keyword' found in the file." - exit 1 - else - echo "Keyword '$keyword' not found in the file." - fi - done + - name: Check Code Convention + uses: SiliconLabsSoftware/devs-coding-convention-tool@master + with: + exclude-regex: '.*\.(cs|txt)$' + codespell-ignore-words: "" + codespell-skip-paths: "" diff --git a/.github/workflows/01-cla-assistant.yml b/.github/workflows/01-cla-assistant.yml index 14ef483..9703450 100644 --- a/.github/workflows/01-cla-assistant.yml +++ b/.github/workflows/01-cla-assistant.yml @@ -1,6 +1,4 @@ name: 01-CLA-Assistant -## This workflow is used for public repositories - on: issue_comment: types: [created] @@ -15,7 +13,12 @@ permissions: jobs: CLAAssistant: - if: ${{ github.event.repository.visibility == 'public' }} + if: >- + github.event_name == 'pull_request_target' || + (github.event_name == 'issue_comment' && + github.event.issue.pull_request && + (github.event.comment.body == 'recheck' || + contains(github.event.comment.body, 'I have read the CLA Document and I hereby sign the CLA'))) runs-on: ubuntu-24.04 steps: - name: Create CLA Assistant Lite bot token @@ -28,7 +31,6 @@ jobs: repositories: contributor-license-agreements - name: "CLA Assistant" - if: ${{ contains(github.event.comment.body, 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target' }} uses: SiliconLabsSoftware/action-cla-assistant@silabs_flavour_v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -36,7 +38,7 @@ jobs: with: path-to-signatures: "cla_signatures_db.json" path-to-document: "https://github.com/SiliconLabsSoftware/agreements-and-guidelines/blob/main/contributor_license_agreement.md" - branch: 'cla-database' + branch: "cla-database" allowlist: silabs-*,bot* # the following are the optional inputs - If the optional inputs are not given, then default values will be taken remote-organization-name: "SiliconLabsInternal" diff --git a/.gitmodules b/.gitmodules index 594a64e..e69de29 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +0,0 @@ -[submodule ".github/coding-convention-tool"] - path = .github/coding-convention-tool - url = https://github.com/SiliconLabsSoftware/devs-coding-convention-tool.git diff --git a/advertising/advertising_and_scanning_with_le_coded_phy/src/scanner/app.c b/advertising/advertising_and_scanning_with_le_coded_phy/src/scanner/app.c index c7c84a6..5945b87 100644 --- a/advertising/advertising_and_scanning_with_le_coded_phy/src/scanner/app.c +++ b/advertising/advertising_and_scanning_with_le_coded_phy/src/scanner/app.c @@ -93,7 +93,6 @@ void sl_bt_on_event(sl_bt_msg_t *evt) system_id); app_assert_status(sc); - app_log_info("System Boot\r\n"); sc = sl_bt_scanner_set_parameters(sl_bt_scanner_scan_mode_passive, 200, 200); @@ -122,53 +121,52 @@ void sl_bt_on_event(sl_bt_msg_t *evt) break; case sl_bt_evt_system_external_signal_id: - if(evt->data.evt_system_external_signal.extsignals == SIGNAL_SCAN_TIMEOUT) - { - sl_bt_scanner_stop(); - app_log_info("no connectable devices in range\r\n"); - } + if (evt->data.evt_system_external_signal.extsignals == SIGNAL_SCAN_TIMEOUT) { + sl_bt_scanner_stop(); + app_log_info("no connectable devices in range\r\n"); + } break; case sl_bt_evt_scanner_extended_advertisement_report_id: // there is no filter here because the LE Coded PHY device is rare // add the filter if it is needed - remote_address = &(evt->data.evt_scanner_extended_advertisement_report.address); - app_log_info("advertisement/scan response from %2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X\r\n", - remote_address->addr[5], - remote_address->addr[4], - remote_address->addr[3], - remote_address->addr[2], - remote_address->addr[1], - remote_address->addr[0]); - - app_log_info("RSSI %d\r\n", evt->data.evt_scanner_extended_advertisement_report.rssi); - - app_log_info("data len: %d\r\n", evt->data.evt_scanner_extended_advertisement_report.data.len); - - app_log_info("data raw: \r\n"); - for(int i = 0; i< evt->data.evt_scanner_extended_advertisement_report.data.len; i++){ - app_log("%c ", evt->data.evt_scanner_extended_advertisement_report.data.data[i]); - } - app_log("\r\n"); - app_log_info("data hex: \r\n"); - for(int i = 0; i< evt->data.evt_scanner_extended_advertisement_report.data.len; i++){ - app_log("%x ", evt->data.evt_scanner_extended_advertisement_report.data.data[i]); - } - app_log("\r\n"); - - //stop the tracking timer - sl_sleeptimer_stop_timer(&sleep_timer_handle); - - sl_bt_scanner_stop(); - sc = sl_bt_connection_open(*remote_address, - sl_bt_gap_public_address, - sl_bt_gap_phy_coded, - &app_connection); - app_assert_status(sc); + remote_address = &(evt->data.evt_scanner_extended_advertisement_report.address); + app_log_info("advertisement/scan response from %2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X\r\n", + remote_address->addr[5], + remote_address->addr[4], + remote_address->addr[3], + remote_address->addr[2], + remote_address->addr[1], + remote_address->addr[0]); + + app_log_info("RSSI %d\r\n", evt->data.evt_scanner_extended_advertisement_report.rssi); + + app_log_info("data len: %d\r\n", evt->data.evt_scanner_extended_advertisement_report.data.len); + + app_log_info("data raw: \r\n"); + for (int i = 0; i < evt->data.evt_scanner_extended_advertisement_report.data.len; i++) { + app_log("%c ", evt->data.evt_scanner_extended_advertisement_report.data.data[i]); + } + app_log("\r\n"); + app_log_info("data hex: \r\n"); + for (int i = 0; i < evt->data.evt_scanner_extended_advertisement_report.data.len; i++) { + app_log("%x ", evt->data.evt_scanner_extended_advertisement_report.data.data[i]); + } + app_log("\r\n"); + + //stop the tracking timer + sl_sleeptimer_stop_timer(&sleep_timer_handle); + + sl_bt_scanner_stop(); + sc = sl_bt_connection_open(*remote_address, + sl_bt_gap_public_address, + sl_bt_gap_phy_coded, + &app_connection); + app_assert_status(sc); break; case sl_bt_evt_connection_phy_status_id: - app_log_info("using PHY %d\r\n", evt->data.evt_connection_phy_status.phy ); + app_log_info("using PHY %d\r\n", evt->data.evt_connection_phy_status.phy); break; /////////////////////////////////////////////////////////////////////////// @@ -190,10 +188,10 @@ void sl_bt_on_event(sl_bt_msg_t *evt) * @param[in] handle Handle of the sleeptimer instance * @param[in] data Callback data ******************************************************************************/ -void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data){ +void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data) +{ (void)handle; (void)data; sl_bt_external_signal(SIGNAL_SCAN_TIMEOUT); - } diff --git a/advertising/bluetooth_low_power_beacon/README.md b/advertising/bluetooth_low_power_beacon/README.md deleted file mode 100644 index 17cae19..0000000 --- a/advertising/bluetooth_low_power_beacon/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# BLE Low-power Beacon example # - -## Summary ## - -This project shows the implementation of a Bluetooth Low-Power beacon. This example also demonstrates the Energy Profiler to measure the current consumption. - -## Gecko SDK version ## - -v4.2 - -## Hardware Required ## - -- Thunderboard EFR32BG22 or -- EFR32xG22 Bluetooth Starter Kit -- Mobile Phone (optional) - -## Setup ## - -To test the Low-power beacon application, the Thunderboard needs to be programmed with the bluetooth_soc-BLELPBeacon_bg22.sls project. - -*Optional -Download the **Blue Gecko** App for your specific mobile phone OS (iOS, Android)* - -## How It Works ## - -Of the 40 channels in BLE, three channels (37, 38, and 39) are reserved for broadcasting advertising packets that contain information about the broadcasting node. These three channels are known as primary advertising channels. Beacons work by taking advantage of Bluetooth’s ability to broadcast packets with a small amount of customizable embedded data on these advertising channels. -By default, the Bluetooth stack advertises on all three of the primary advertising channels. - -To save power consumption the BLE Low-power example deploys the following techniques: - -1. Usage of only one advertising channel -2. Increase advertising interval to 1 sec -3. Transmit output power is set to 0dBm (6dBm default) -4. Reduction of transmit payload to 4 bytes -5. Set up of device to non-connectable to avoid RX mode -6. Disablement of debug features - -## .sls Projects Used ## - -- bluetooth_soc-BLELPBeacon_bg22.sls - -## How to Port to Another Part ## - -Open the "Project Properties" and navigate to the "C/C++ Build -> Board/Part/SDK" item. Select the new board or part to target and "Apply" the changes. Note: there may be dependencies that need to be resolved when changing the target architecture. diff --git a/advertising/bluetooth_low_power_beacon/SimplicityStudio/bluetooth_soc-BLELPBeacon_bg22.sls b/advertising/bluetooth_low_power_beacon/SimplicityStudio/bluetooth_soc-BLELPBeacon_bg22.sls deleted file mode 100644 index ce30919..0000000 Binary files a/advertising/bluetooth_low_power_beacon/SimplicityStudio/bluetooth_soc-BLELPBeacon_bg22.sls and /dev/null differ diff --git a/advertising/bluetooth_low_power_beacon/src/app.c b/advertising/bluetooth_low_power_beacon/src/app.c deleted file mode 100644 index 084c564..0000000 --- a/advertising/bluetooth_low_power_beacon/src/app.c +++ /dev/null @@ -1,182 +0,0 @@ -/***************************************************************************//** - * @file app.c - * @brief Silicon Labs Empty Example Project - * This example demonstrates the bare minimum needed for a Blue Gecko C - * application that allows Over-the-Air Device Firmware Upgrading (OTA DFU). - * The application starts advertising after boot and restarts advertising after - * a connection is closed. - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -/* Bluetooth stack headers */ -#include "bg_types.h" -#include "native_gecko.h" -#include "gatt_db.h" - -#include "app.h" - -/* Print boot message */ -static void bootMessage(struct gecko_msg_system_boot_evt_t *bootevt); - -/* Flag for indicating DFU Reset must be performed */ -static uint8_t boot_to_dfu = 0; - -/* Main application */ -void appMain(gecko_configuration_t *pconfig) -{ -#if DISABLE_SLEEP > 0 - pconfig->sleep.flags = 0; -#endif - - /* Initialize debug prints. Note: debug prints are off by default. See DEBUG_LEVEL in app.h */ - initLog(); - - /* Initialize stack */ - gecko_init(pconfig); - - while (1) { - /* Event pointer for handling events */ - struct gecko_cmd_packet* evt; - - /* if there are no events pending then the next call to gecko_wait_event() may cause - * device go to deep sleep. Make sure that debug prints are flushed before going to sleep */ - if (!gecko_event_pending()) { - flushLog(); - } - - /* Check for stack event. This is a blocking event listener. If you want non-blocking please see UG136. */ - evt = gecko_wait_event(); - - /* Handle events */ - switch (BGLIB_MSG_ID(evt->header)) { - /* This boot event is generated when the system boots up after reset. - * Do not call any stack commands before receiving the boot event. - * Here the system is set to start advertising immediately after boot procedure. */ - case gecko_evt_system_boot_id: - - bootMessage(&(evt->data.evt_system_boot)); - printLog("boot event - starting advertising\r\n"); - - /* Set adv on channel 37 only */ - gecko_cmd_le_gap_set_advertise_channel_map(0, 1); - - /* Set advertising parameters. 1000ms advertisement interval. - * The next two parameters are minimum and maximum advertising interval, both in - * units of (milliseconds * 1.6). - * The last two parameters are duration and maxevents left as default. */ - gecko_cmd_le_gap_set_advertise_timing(0, 1600, 1600, 0, 0); - - /* Set tx power to 0dBm */ - gecko_cmd_system_set_tx_power(0); - - /* Set the adv payload to 0 length */ - //gecko_cmd_le_gap_bt5_set_adv_data(0, 0, 0, NULL); - - uint8_t name[] = { 3, 9, 'D', 'T' }; - gecko_cmd_le_gap_bt5_set_adv_data(0, 0, 4, name); - - /* Start general advertising and enable connections. */ - //gecko_cmd_le_gap_start_advertising(0, le_gap_general_discoverable, le_gap_connectable_scannable); - - /* Start advertising and disable connections. */ - gecko_cmd_le_gap_start_advertising(0, le_gap_user_data, le_gap_non_connectable); - - break; - - case gecko_evt_le_connection_opened_id: - - printLog("connection opened\r\n"); - - break; - - case gecko_evt_le_connection_closed_id: - - printLog("connection closed, reason: 0x%2.2x\r\n", evt->data.evt_le_connection_closed.reason); - - /* Check if need to boot to OTA DFU mode */ - if (boot_to_dfu) { - /* Enter to OTA DFU mode */ - gecko_cmd_system_reset(2); - } else { - /* Restart advertising after client has disconnected */ - gecko_cmd_le_gap_start_advertising(0, le_gap_general_discoverable, le_gap_connectable_scannable); - } - break; - - /* Events related to OTA upgrading - ----------------------------------------------------------------------------- */ - - /* Check if the user-type OTA Control Characteristic was written. - * If ota_control was written, boot the device into Device Firmware Upgrade (DFU) mode. */ - case gecko_evt_gatt_server_user_write_request_id: - - if (evt->data.evt_gatt_server_user_write_request.characteristic == gattdb_ota_control) { - /* Set flag to enter to OTA mode */ - boot_to_dfu = 1; - /* Send response to Write Request */ - gecko_cmd_gatt_server_send_user_write_response( - evt->data.evt_gatt_server_user_write_request.connection, - gattdb_ota_control, - bg_err_success); - - /* Close connection to enter to DFU OTA mode */ - gecko_cmd_le_connection_close(evt->data.evt_gatt_server_user_write_request.connection); - } - break; - - /* Add additional event handlers as your application requires */ - - default: - break; - } - } -} - -/* Print stack version and local Bluetooth address as boot message */ -static void bootMessage(struct gecko_msg_system_boot_evt_t *bootevt) -{ -#if DEBUG_LEVEL - bd_addr local_addr; - int i; - - printLog("stack version: %u.%u.%u\r\n", bootevt->major, bootevt->minor, bootevt->patch); - local_addr = gecko_cmd_system_get_bt_address()->address; - - printLog("local BT device address: "); - for (i = 0; i < 5; i++) { - printLog("%2.2x:", local_addr.addr[5 - i]); - } - printLog("%2.2x\r\n", local_addr.addr[0]); -#endif -} diff --git a/advertising/bluetooth_low_power_beacon/src/app.h b/advertising/bluetooth_low_power_beacon/src/app.h deleted file mode 100644 index df6e4d5..0000000 --- a/advertising/bluetooth_low_power_beacon/src/app.h +++ /dev/null @@ -1,66 +0,0 @@ -/***************************************************************************//** - * @file app.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef APP_H_ -#define APP_H_ - -#include "gecko_configuration.h" - -/* DEBUG_LEVEL is used to enable/disable debug prints. Set DEBUG_LEVEL to 1 to enable debug prints */ -#define DEBUG_LEVEL 0 - -/* Set this value to 1 if you want to disable deep sleep completely */ -#define DISABLE_SLEEP 0 - -#if DEBUG_LEVEL -#include "retargetserial.h" -#include -#endif - -#if DEBUG_LEVEL -#define initLog() RETARGET_SerialInit() -#define flushLog() RETARGET_SerialFlush() -#define printLog(...) printf(__VA_ARGS__) -#else -#define initLog() -#define flushLog() -#define printLog(...) -#endif - -/* Main application */ -void appMain(gecko_configuration_t *pconfig); - -#endif diff --git a/advertising/directed_advertising/src/advertiser/app.c b/advertising/directed_advertising/src/advertiser/app.c index 2b075f6..9b10dfe 100644 --- a/advertising/directed_advertising/src/advertiser/app.c +++ b/advertising/directed_advertising/src/advertiser/app.c @@ -37,7 +37,7 @@ // The advertising set handle allocated from Bluetooth stack. static uint8_t advertising_set_handle = 0xff; // Scanner address -static bd_addr scanner = {.addr = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; +static bd_addr scanner = { .addr = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; /**************************************************************************//** * Application Init. @@ -104,13 +104,13 @@ void sl_bt_on_event(sl_bt_msg_t *evt) app_assert_status(sc); app_log("Bluetooth %s address: %02X:%02X:%02X:%02X:%02X:%02X\r\n", - address_type ? "static random" : "public device", - address.addr[5], - address.addr[4], - address.addr[3], - address.addr[2], - address.addr[1], - address.addr[0]); + address_type ? "static random" : "public device", + address.addr[5], + address.addr[4], + address.addr[3], + address.addr[2], + address.addr[1], + address.addr[0]); // Create an advertising set. sc = sl_bt_advertiser_create_set(&advertising_set_handle); @@ -167,11 +167,12 @@ void sl_bt_on_event(sl_bt_msg_t *evt) /**************************************************************************//** * Start directed advertising. *****************************************************************************/ -sl_status_t start_directed_advertising() { +sl_status_t start_directed_advertising() +{ return sl_bt_legacy_advertiser_start_directed( - advertising_set_handle, // The advertising set handle - sl_bt_legacy_advertiser_high_duty_directed_connectable, // A value of sl_bt_legacy_advertiser_directed_connection_mode_t - scanner, // The scanner address - 0 // 0: Public address, 1: Random address - ); + advertising_set_handle, // The advertising set handle + sl_bt_legacy_advertiser_high_duty_directed_connectable, // A value of sl_bt_legacy_advertiser_directed_connection_mode_t + scanner, // The scanner address + 0 // 0: Public address, 1: Random address + ); } diff --git a/advertising/extended_advertising/src/advertiser/app.c b/advertising/extended_advertising/src/advertiser/app.c index 9a68d4b..ccc214d 100644 --- a/advertising/extended_advertising/src/advertiser/app.c +++ b/advertising/extended_advertising/src/advertiser/app.c @@ -25,8 +25,7 @@ void demo_setup_start_ext_adv(uint8_t handle); // The advertising set handle allocated from Bluetooth stack. static uint8_t advertising_set_handle = 0xff; -const uint8_t dummy_service[16] = {0x81,0xc2,0x00,0x2d,0x31,0xf4,0xb0,0xbf,0x2b,0x42,0x49,0x68,0xc7,0x25,0x71,0x41}; - +const uint8_t dummy_service[16] = { 0x81, 0xc2, 0x00, 0x2d, 0x31, 0xf4, 0xb0, 0xbf, 0x2b, 0x42, 0x49, 0x68, 0xc7, 0x25, 0x71, 0x41 }; /**************************************************************************//** * Application Init. @@ -71,23 +70,23 @@ void sl_bt_on_event(sl_bt_msg_t *evt) case sl_bt_evt_system_boot_id: // Print boot message. app_log("Bluetooth stack booted: v%d.%d.%d-b%d\n", - evt->data.evt_system_boot.major, - evt->data.evt_system_boot.minor, - evt->data.evt_system_boot.patch, - evt->data.evt_system_boot.build); + evt->data.evt_system_boot.major, + evt->data.evt_system_boot.minor, + evt->data.evt_system_boot.patch, + evt->data.evt_system_boot.build); // Extract unique ID from BT Address. sc = sl_bt_system_get_identity_address(&address, &address_type); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to get Bluetooth address\n", - (int)sc); + "[E: 0x%04x] Failed to get Bluetooth address\n", + (int)sc); app_log("Bluetooth %s address: %02X:%02X:%02X:%02X:%02X:%02X\n", - address_type ? "static random" : "public device", - address.addr[5], - address.addr[4], - address.addr[3], - address.addr[2], - address.addr[1], - address.addr[0]); + address_type ? "static random" : "public device", + address.addr[5], + address.addr[4], + address.addr[3], + address.addr[2], + address.addr[1], + address.addr[0]); // Pad and reverse unique ID to get System ID. system_id[0] = address.addr[5]; system_id[1] = address.addr[4]; @@ -103,14 +102,14 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sizeof(system_id), system_id); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to write attribute\n", - (int)sc); + "[E: 0x%04x] Failed to write attribute\n", + (int)sc); // Create an advertising set. sc = sl_bt_advertiser_create_set(&advertising_set_handle); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to create advertising set\n", - (int)sc); + "[E: 0x%04x] Failed to create advertising set\n", + (int)sc); demo_setup_start_ext_adv(advertising_set_handle); break; @@ -126,15 +125,15 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sc = sl_bt_extended_advertiser_generate_data(advertising_set_handle, sl_bt_advertiser_general_discoverable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to generate data\n", - (int)sc); + "[E: 0x%04x] Failed to generate data\n", + (int)sc); sc = sl_bt_extended_advertiser_start( advertising_set_handle, sl_bt_extended_advertiser_scannable, 0); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); break; /////////////////////////////////////////////////////////////////////////// @@ -159,12 +158,12 @@ void demo_setup_ext_adv(uint8_t handle) // Initialize advertising data with Flag and Local name uint8_t adv_data[MAX_EXTENDED_ADV_LENGTH] = { - 0x02, // Length of flag - 0x01, // Type flag - 0x06, // Flag data - 0x05, // Length of Local name - 0x09, // Type local name - 'A', 'd', 'v', 'C', // Local name + 0x02, // Length of flag + 0x01, // Type flag + 0x06, // Flag data + 0x05, // Length of Local name + 0x09, // Type local name + 'A', 'd', 'v', 'C', // Local name }; // Byte amount in advertising data buffer now increased by 9 amout_bytes += 9; @@ -172,7 +171,7 @@ void demo_setup_ext_adv(uint8_t handle) adv_data[amout_bytes++] = 0x06;//more_128_uuids // copy the 128bits UUID of the service into the advertising data - memcpy(adv_data+amout_bytes,dummy_service,16); + memcpy(adv_data + amout_bytes, dummy_service, 16); amout_bytes += 16; // Prepare manufacturer_specific_data @@ -190,8 +189,8 @@ void demo_setup_ext_adv(uint8_t handle) // Set advertising data sc = sl_bt_extended_advertiser_set_data(handle, amout_bytes, adv_data); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to set advertising data\n", - (int)sc); + "[E: 0x%04x] Failed to set advertising data\n", + (int)sc); } void demo_setup_start_ext_adv(uint8_t handle) @@ -205,18 +204,18 @@ void demo_setup_start_ext_adv(uint8_t handle) 0, // adv. duration 0); // max. num. adv. events app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to set advertising timing\n", - (int)sc); + "[E: 0x%04x] Failed to set advertising timing\n", + (int)sc); demo_setup_ext_adv(handle); sc = sl_bt_extended_advertiser_start( - handle, - sl_bt_extended_advertiser_non_connectable, - 0); + handle, + sl_bt_extended_advertiser_non_connectable, + 0); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); /* Start general advertising and enable connections. */ app_log("Start advertising.\r\n"); } diff --git a/advertising/extended_advertising/src/scanner/rsp_queue.c b/advertising/extended_advertising/src/scanner/rsp_queue.c index 9160c0e..75b76ce 100644 --- a/advertising/extended_advertising/src/scanner/rsp_queue.c +++ b/advertising/extended_advertising/src/scanner/rsp_queue.c @@ -33,7 +33,7 @@ int __match( } void __copy(const sl_bt_evt_scanner_extended_advertisement_report_t *rsp, - rsp_t *r) + rsp_t *r) { memcpy(&r->data, rsp, sizeof(sl_bt_evt_scanner_extended_advertisement_report_t) + rsp->data.len); diff --git a/channel_sounding/initiator_as_peripheral_reflector_as_central/README.md b/channel_sounding/initiator_as_peripheral_reflector_as_central/README.md index 5cf2433..fcd2ab5 100644 --- a/channel_sounding/initiator_as_peripheral_reflector_as_central/README.md +++ b/channel_sounding/initiator_as_peripheral_reflector_as_central/README.md @@ -120,7 +120,7 @@ break; if (!cs_reflector_identify(conn_handle)) { break; } - + reflector_log_info(INSTANCE_PREFIX "CS configuration completed" NL, conn_handle); reflector_log_debug(INSTANCE_PREFIX "CS - enable security" NL, conn_handle); diff --git a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/initiator/app.c b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/initiator/app.c index 2e8b11c..6db2f82 100644 --- a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/initiator/app.c +++ b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/initiator/app.c @@ -667,7 +667,6 @@ static sl_status_t create_new_initiator_instance(uint8_t conn_handle) conn_handle, sc); (void)ble_peer_manager_peripheral_close_connection(conn_handle); - } return sc; } @@ -926,11 +925,11 @@ void sl_bt_on_event(sl_bt_msg_t * evt) /*sc = ble_peer_manager_set_filter_device_name(device_name, strlen(device_name), false); - app_assert_status(sc); + app_assert_status(sc); - uint16_t ras_service_uuid = CS_RAS_SERVICE_UUID; - sc = ble_peer_manager_set_filter_service_uuid16((sl_bt_uuid_16_t *)&ras_service_uuid); - app_assert_status(sc);*/ + uint16_t ras_service_uuid = CS_RAS_SERVICE_UUID; + sc = ble_peer_manager_set_filter_service_uuid16((sl_bt_uuid_16_t *)&ras_service_uuid); + app_assert_status(sc);*/ #ifndef SL_CATALOG_CS_INITIATOR_CLI_PRESENT sc = ble_peer_manager_peripheral_create_connection(); @@ -1029,7 +1028,7 @@ void sl_bt_on_event(sl_bt_msg_t * evt) cs_initiator_instances[instance_num].read_remote_capabilities = true; // Advertise for new reflector connections if we have room for more if (num_reflector_connections < CS_INITIATOR_MAX_CONNECTIONS) { - sc = ble_peer_manager_peripheral_create_connection(); + sc = ble_peer_manager_peripheral_create_connection(); app_assert_status(sc); //cs_initiator_display_start_scanning(); log_info(APP_PREFIX "Advertising restarted for new reflector connections..." NL); @@ -1065,7 +1064,7 @@ void ble_peer_manager_on_event_initiator(ble_peer_manager_evt_type_t * event) bd_addr *address; switch (event->evt_id) { - case BLE_PEER_MANAGER_ON_CONN_OPENED_PERIPHERAL: + case BLE_PEER_MANAGER_ON_CONN_OPENED_PERIPHERAL: address = ble_peer_manager_get_bt_address(event->connection_id); log_info(APP_INSTANCE_PREFIX "Connection opened as peripheral with CS Reflector" " '%02X:%02X:%02X:%02X:%02X:%02X'" NL, diff --git a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/app.c b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/app.c index 878a74a..91869c0 100644 --- a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/app.c +++ b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/app.c @@ -159,7 +159,6 @@ void sl_bt_on_event(sl_bt_msg_t *evt) ble_peer_manager_central_init(); ble_peer_manager_filter_init(); - // Print the Bluetooth address app_log_info(APP_PREFIX "Bluetooth %s address: %02X:%02X:%02X:%02X:%02X:%02X\n", address_type ? "static random" : "public device", @@ -187,7 +186,7 @@ void sl_bt_on_event(sl_bt_msg_t *evt) // Start scanning for initiator connections if (SL_BT_CONFIG_MAX_CONNECTIONS > 0) { #ifndef SL_CATALOG_CS_REFLECTOR_CLI_PRESENT - sc = ble_peer_manager_central_create_connection(); + sc = ble_peer_manager_central_create_connection(); app_assert_status(sc); app_log_info(APP_PREFIX "Scanning started for initiator connections..." APP_LOG_NL); #else @@ -309,7 +308,7 @@ static void on_connection_opened_with_initiator(uint8_t conn_handle) // Scan for new initiator connections if we have room for more if (cs_reflector_get_active_instance_count() < SL_BT_CONFIG_MAX_CONNECTIONS) { - sc = ble_peer_manager_central_create_connection(); + sc = ble_peer_manager_central_create_connection(); app_assert_status(sc); app_log_info(APP_PREFIX "Scanning restarted for new initiator connections..." APP_LOG_NL); } @@ -335,7 +334,7 @@ static void on_connection_closed(uint8_t conn_handle) // Restart scanning if needed if (scanning_should_be_restarted) { //sc = ble_peer_manager_central_create_connection(); - (void)ble_peer_manager_central_create_connection(); + (void)ble_peer_manager_central_create_connection(); //app_assert_status(sc); app_log_info(APP_PREFIX "Scanning restarted for new initiator connections..." APP_LOG_NL); } diff --git a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/security.c b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/security.c index 635c27a..6147721 100644 --- a/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/security.c +++ b/channel_sounding/initiator_as_peripheral_reflector_as_central/src/reflector/security.c @@ -170,4 +170,4 @@ bool security_is_confirmation_in_progress(void) void security_set_confirmation(enum security_send_confirmation confirmation) { send_confirmation = confirmation; -} \ No newline at end of file +} diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/README.md b/firmware_upgrade/bluetooth_host_ota_target_controlled/README.md deleted file mode 100644 index 4bdd3b6..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/README.md +++ /dev/null @@ -1,96 +0,0 @@ -# NCP OTA Target Controlled Project # - -## Summary ## - -The GG11 is the host and the MG12 is the target. -In this project, the target is responsible for setting the host to bootloader mode (using the gpio activation and reset pin) and send the image through USART to the host. The host does not have any code regarding the OTA Control and Data. That is handled inside the target device. All code related to updating the host is in the btl_app folder of this project. - -## Gecko SDK Version ## - -v2.7 - -## Hardware Required ## - -- One BRD4162A radio board -- One BRD4001A WSTK board -- One SLSTK3701A EFM32 Giant Gecko GG11 Starter Kit - -## Connections Required ## - -Host uses USART4, target uses USART0, but these connections can be changed in btl_config.h - -### USART Connections ## - -| Host (GG11) | Target (MG12) | -| --- | --- | -| PI4 - CTS | PA3 - RTS | -| PI5 - RTS | PA2 - CTS | -| PI6 - TX | PA1 - RX | -| PI7 - RX | PA0 - TX | - -### Additional Connections ### - -| Host (GG11) | Target (MG12) | -| --- | --- | -| PC10 | PC9 | -| RST | PC10 | - -## Setup ## - -1. Have the USART connections plus the reset and gpio pin connections. -2. The target's bootloader must have a storage slot. Upload the Bootloader Storage Internal Single 1024k example into the target. -3. The host's bootloader uses the UART XMODEM configuration; the following needs to be altered and uploaded for the example to work: - - USART4 pins had to be changed to Port I because the default pins were not accessible on the starter kit - - USART4 configured for UART HW flow control because the target's default UARTDrv has HW flow control configured. - - GPIO Activation Pin changed to PC10. The original pin (PC8) was connected to button 0 and was not accessible. -4. Upload the target's application code. This code has a bootloader handler for handling the OTA service and packaging of the XMODEM packets. -5. Upload the host's application code. This code is just default starter code that has the necessary gatt_db source files and initializes the USART for communication. - -### GATT Service and Characteristics Configuration ### - -The GATT OTA Control characteristic should have the property Write with Mandatory requirements to work properly with the Blue Gecko App. -The OTA Control Characteristic will either be a 0 (start OTA transfer) or 3 (end OTA Transfer) with its value type being user. -The GATT OTA Data characteristic should have the following properties: - -- Write with Mandatory -- Write without response with Mandatory - -## How It Works (On the Target) ## - -1. Blue Gecko App writes 0 to the OTA Control Characteristic to start transfer. -2. The target will get 20 bytes of data at a time from the OTA Data characteristic and stores image into storage slot 0. -3. Keep getting data until Blue Gecko App writes 3 to the OTA Control Characteristic. -4. Once whole image has been stored (3 received), clear the GPIO activation pin (low). -5. Clear the reset pin (low) -6. Delay -7. Set the reset pin (high) -8. Wait until the host's bootloader sends the menu string i.e. wait until host's bootloader is ready to receive commands. -9. Send '1' character to host. The '1' command starts the image uploading. -10. Wait until the host's bootloader sends the 'C' command. This is part of the XMODEM File Transfer Protocol and it means the last 2 bytes of each packet must have the CRC result. -11. Send XMODEM packet. XMODEM packets only allow 128 bytes of data. If the image is not 128 byte aligned, the end is padded with 0x1A which indicates EOF. -12. Wait for ACK response from host's bootloader. -13. Repeat 9 and 10 until whole image has been sent. -14. Send EOT which indicates the end of the image. -15. Wait until the host's bootloader sends the menu string again. -16. Send '2' character to host. The '2' command makes the host start running the new application. - -## .sls Projects Used ## - -### Target (MG12) ### - -- app_ncp_target_controlled_ota_mg12.sls -- bootloader_storage_internal_1024k_mg12.sls - -### Host (GG11) ### - -- bootloader_storage_internal_single_2048k_gg11.sls - -## Special Notes ## - -When porting the btl_app to another project, make sure add: extern UARTDRV_Handle_t handle; to the ncp_usart.h. This is to use the USARTDrv in the bootloader files. - -## How to Port to Another Part ## - -Go [here](./host_gg11/README.md) for instructions on how to implement the HOST code on another part. - -Go [here](./target_mg12/README.md) for instructions on how to implement the TARGET code on another part. diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/README.md b/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/README.md deleted file mode 100644 index 1cdfad1..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# NCP OTA Target Controlled Project # - -## Summary ## - -This directory is meant for the HOST. The host only requires the bootloader. Any application can be programmed because the host does not control its own bootloader in this example. Import the bootloader_storage_internal_single_2048k_gg11.sls to Simplicity to use as is. - -## Tested Hardware ## - -- One SLSTK3701A EFM32 Giant Gecko GG11 Starter Kit - -## How to Port to Another Part ## - -To create a new bootloader for the host, perform the following steps: - -1. Create new bootloader project for your part. Storage slots are not required. -2. In the plugins tab of the isc file, select the following: - - Communication / UART XMODEM - - Communication / XMODEM Parser - - Drivers / Delay - - Drivers / UART - - Utils / GPIO Activation -3. Under Drivers / UART, USART4 pins had to be changed to Port I because the default pins were not accessible on the starter kit. The target application uses the following Port I pins: - - PI4 - CTS - - PI5 - RTS - - PI6 - TX - - PI7 - RX -4. USART4 configured for UART HW flow control because the target's default UARTDrv has HW flow control configured. -5. Under Utils / GPIO Activation, change pin to PC10. The original pin (PC8) was connected to button 0 which is not accessible. diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/SimplicityStudio/bootloader_storage_internal_single_2048k_gg11.sls b/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/SimplicityStudio/bootloader_storage_internal_single_2048k_gg11.sls deleted file mode 100644 index 1ef678f..0000000 Binary files a/firmware_upgrade/bluetooth_host_ota_target_controlled/host_gg11/SimplicityStudio/bootloader_storage_internal_single_2048k_gg11.sls and /dev/null differ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/README.md b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/README.md deleted file mode 100644 index fe11eee..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# NCP OTA Target Controlled Project # - -## Summary ## - -This directory is meant for the TARGET. There are two programs that need to be uploaded to the target: the application and the bootloader. The necessary .sls projects are provided to use the example as is. - -## Hardware Required ## - -- One BRD4162A radio board -- One BRD4001A WSTK board - -## How to Port to Another Part ## - -### Bootloader ### - -Any bootloader with at least one storage slot will work. - -### Application ### - -If you want the target controlled app on a different radio chip, do the following: - -1. Place all src code into newly created project. - - In main.c, only initialization code and event handler was added. Everything else stayed the same as NCP Empty Target example. - - In ncp_usart.h, add extern UARTDRV_Handle_t handle; -2. Get the bootloader_interface.c and bootloader_interface_storage.c from the bootloader api folder and add to the project. Make sure to include the path of the header files in the project as well. -`C:\SiliconLabs\SimplicityStudio\v4\developer\sdks\gecko_sdk_suite\v2.7\platform\bootloader\api` -3. Configure btl_config.h to match your application. -4. Import gatt.xml diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/app_ncp_target_controlled_ota_mg12.sls b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/app_ncp_target_controlled_ota_mg12.sls deleted file mode 100644 index 6fcf5c3..0000000 Binary files a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/app_ncp_target_controlled_ota_mg12.sls and /dev/null differ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/bootloader_storage_internal_1024k_mg12.sls b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/bootloader_storage_internal_1024k_mg12.sls deleted file mode 100644 index 52fc68d..0000000 Binary files a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/SimplicityStudio/bootloader_storage_internal_1024k_mg12.sls and /dev/null differ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/config/gatt.xml b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/config/gatt.xml deleted file mode 100644 index 5ee29d4..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/config/gatt.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - Abstract: The generic_access service contains generic information about the device. All available Characteristics are readonly. - - - - - OTA Example - - - - - - Abstract: The external appearance of this device. The values are composed of a category (10-bits) and sub-categories (6-bits). - 0000 - - - - - - - Abstract: The Device Information Service exposes manufacturer and/or vendor information about a device. Summary: This service exposes manufacturer information about a device. The Device Information Service is instantiated as a Primary Service. Only one instance of the Device Information Service is exposed on a device. - - - - Abstract: The value of this characteristic is a UTF-8 string representing the name of the manufacturer of the device. - Silicon Labs - - - - - - Abstract: The value of this characteristic is a UTF-8 string representing the model number assigned by the device vendor. - Blue Gecko - - - - - - Abstract: The SYSTEM ID characteristic consists of a structure with two fields. The first field are the LSOs and the second field contains the MSOs. This is a 64-bit structure which consists of a 40-bit manufacturer-defined identifier concatenated with a 24 bit unique Organizationally Unique Identifier (OUI). The OUI is issued by the IEEE Registration Authority (http://standards.ieee.org/regauth/index.html) and is required to be used in accordance with IEEE Standard 802-2001.6 while the least significant 40 bits are manufacturer defined. If System ID generated based on a Bluetooth Device Address, it is required to be done as follows. System ID and the Bluetooth Device Address have a very similar structure: a Bluetooth Device Address is 48 bits in length and consists of a 24 bit Company Assigned Identifier (manufacturer defined identifier) concatenated with a 24 bit Company Identifier (OUI). In order to encapsulate a Bluetooth Device Address as System ID, the Company Identifier is concatenated with 0xFFFE followed by the Company Assigned Identifier of the Bluetooth Address. For more guidelines related to EUI-64, refer to http://standards.ieee.org/develop/regauth/tut/eui64.pdf. Examples: If the system ID is based of a Bluetooth Device Address with a Company Identifier (OUI) is 0x123456 and the Company Assigned Identifier is 0x9ABCDE, then the System Identifier is required to be 0x123456FFFE9ABCDE. - 000102030405 - - - - - - - Abstract: The Silicon Labs OTA Service enables over-the-air firmware update of the device. - - - - Abstract: Silicon Labs OTA Control. - - - - - - - Abstract: Silicon Labs OTA Data. - - - - - diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.c b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.c deleted file mode 100644 index 29b0279..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.c +++ /dev/null @@ -1,262 +0,0 @@ -/***************************************************************************//** - * @file btl_app.c - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#include -#include -#include -#include "ncp_gecko.h" -#include "gatt_db.h" -#include "ncp.h" -#include "ncp_usart.h" -#include "udelay.h" -#include "btl_interface.h" -#include "btl_interface_storage.h" -#include "btl_gpio.h" -#include "btl_app.h" -#include "btl_xmodem.h" -#include "btl_config.h" -#include "uartdrv.h" - -static uint8_t ota_connection = 0; -static uint32_t ota_mode = 0; -static uint32_t ota_data_len = 0; - -void handle_bootloader_cmds(void); - -void bootloader_appInit(void) -{ - bootloader_init(); - bootloader_gpioInit(); - UDELAY_Calibrate(); - - /* Make sure GPIO activation pin is low so NCP host won't go into BootLoader mode. */ - bootloader_setGPIOActivation(APP_MODE); - // Delay to stabilize - UDELAY_Delay(TIME_5MS); - - /* Make sure reset pin is high so NCP host can run. */ - bootloader_setResetPin(1); - // Delay to stabilize - UDELAY_Delay(TIME_5MS); -} - -uint32_t bootloader_handle_event(struct gecko_cmd_packet *evt) -{ - bool evt_handled = false; - switch (BGLIB_MSG_ID(evt->header)) { - case gecko_evt_system_boot_id: - gecko_cmd_le_gap_set_advertise_timing(0, 160, 160, 0, 0); - gecko_cmd_le_gap_start_advertising(0, le_gap_general_discoverable, le_gap_connectable_scannable); - break; - - case gecko_evt_le_connection_opened_id: - if (ota_mode != 0) { - gecko_cmd_le_connection_set_parameters(ota_connection, 6, 6, 0, 1000); - evt_handled = true; - } - break; - - case gecko_evt_gatt_server_user_write_request_id: { - uint32_t characteristic = evt->data.evt_gatt_server_user_write_request.characteristic; - uint8_t *data = &(evt->data.evt_gatt_server_user_write_request.value.data[0]); - uint8_t length = evt->data.evt_gatt_server_user_write_request.value.len; - - if (characteristic == gattdb_ota_control) { - evt_handled = true; - - /* If control data = 0, then start transfer - * If control data = 3, then end transfer. */ - switch (data[0]) { - /* Start Transfer. */ - case 0: - /* To work with blue gecko app, connection reset must occur. */ - if (ota_mode == 0) { - ota_connection = evt->data.evt_gatt_server_user_write_request.connection; - ota_mode = 1; - ota_data_len = 0; - - /* Erase current contents in storage slot. This may cause errors if not erased. */ - bootloader_eraseStorageSlot(STORAGE_SLOT_ID); - - /* Send success response. */ - gecko_cmd_gatt_server_send_user_write_response(ota_connection, - characteristic, - bg_err_success); - - /* Close connection. */ - gecko_cmd_le_connection_close(ota_connection); - break; - } - - /* This line is reached when a connection reset has occurred. */ - ota_data_len = 0; - gecko_cmd_gatt_server_send_user_write_response(ota_connection, - characteristic, - bg_err_success); - break; - - /* End Transfer. */ - case 3: - ota_mode = 0; - gecko_cmd_gatt_server_send_user_write_response(ota_connection, - characteristic, - bg_err_success); - - /* Verify Image */ - int32_t ret = bootloader_verifyImage(STORAGE_SLOT_ID, 0); - - if (ret != BOOTLOADER_OK) { - gecko_cmd_le_gap_start_advertising(0, le_gap_discover_generic, le_gap_connectable_scannable); - break; - } - - bootloader_appTransferImage(); - gecko_cmd_le_gap_start_advertising(0, le_gap_discover_generic, le_gap_connectable_scannable); - break; - } - } - // Store image into a storage slot - else if (characteristic == gattdb_ota_data) { - evt_handled = true; - bootloader_writeStorage(STORAGE_SLOT_ID, - ota_data_len, - data, - length); - gecko_cmd_gatt_server_send_user_write_response(ota_connection, - characteristic, - bg_err_success); - ota_data_len += length; - } - - break; - } - - case gecko_evt_le_connection_closed_id: - if (ota_mode != 0) { - gecko_cmd_le_gap_start_advertising(0, le_gap_discover_generic, le_gap_connectable_scannable); - evt_handled = true; - } - break; - - default: - break; - } - - return evt_handled; -} - -void bootloader_appTransferImage(void) -{ - /* Prevent BootLoader from getting any weird data. */ - tx_queue_reset(); - UARTDRV_Abort(handle, uartdrvAbortAll); - - bootloader_setGPIOActivation(BOOTLOADER_MODE); - UDELAY_Delay(TIME_5MS); - - /* Press and release reset pin. */ - bootloader_setResetPin(0); - UDELAY_Delay(TIME_5MS); - bootloader_setResetPin(1); - - /* The BootLoader will print some user commands. */ - handle_bootloader_cmds(); -} - -/* Wait until device is ready to receive a command. - * Look in AN0003 for what is printed by BootLoader. */ -void wait_for_char(uint8_t character) -{ - uint8_t response = 0; - - do { - /* Clean rx queue. */ - UARTDRV_Abort(handle, uartdrvAbortAll); - - UARTDRV_ReceiveB(handle, &response, 1); - } while (response != character); -} - -void handle_bootloader_cmds(void) -{ - uint8_t command = 0; - - /* Wait until menu is printed. */ - wait_for_char(0); - - /* Send upload gbl command. - * Needs to be char 1 due to user keyboard inputs are only accepted. */ - command = '1'; - UARTDRV_TransmitB(handle, &command, 1); - - /* Wait until response is received. */ - wait_for_char(0); - - /* Wait until C command has been received from host. Signifies CRC use. */ - wait_for_char('C'); - - /* Get image address. */ - BootloaderStorageSlot_t slotInfo; - bootloader_getStorageSlotInfo(STORAGE_SLOT_ID, &slotInfo); - - /* Transmit gbl file, make it blocking so no USART transfers occur. */ - if (bootloader_xmodemSend((uint8_t *)slotInfo.address, ota_data_len) == 0) { - /* Failed. */ - /* Set gpio activation pin back to low. */ - bootloader_setGPIOActivation(APP_MODE); - UDELAY_Delay(TIME_5MS); - - /* Press and release reset pin. */ - bootloader_setResetPin(0); - UDELAY_Delay(TIME_5MS); - bootloader_setResetPin(1); - return; - } - - /* Wait until ready. */ - wait_for_char(0); - - /* Wait until menu is printed. */ - wait_for_char(0); - - /* Set gpio activation pin back to low. */ - bootloader_setGPIOActivation(APP_MODE); - UDELAY_Delay(TIME_5MS); - - /* Send run application command. */ - command = '2'; - UARTDRV_TransmitB(handle, &command, 1); -} diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.h b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.h deleted file mode 100644 index f7e2b46..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_app.h +++ /dev/null @@ -1,48 +0,0 @@ -/***************************************************************************//** - * @file btl_app.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef BTL_APP_BTL_APP_H_ -#define BTL_APP_BTL_APP_H_ - -void bootloader_appInit(void); - -uint32_t bootloader_handle_event(struct gecko_cmd_packet *evt); - -void bootloader_appTransferImage(void); - -uint8_t bootloader_isTransferReady(void); - -#endif /* BTL_APP_BTL_APP_H_ */ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_config.h b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_config.h deleted file mode 100644 index a98a228..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_config.h +++ /dev/null @@ -1,60 +0,0 @@ -/***************************************************************************//** - * @file btl_config.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef BTL_APP_BTL_CONFIG_H_ -#define BTL_APP_BTL_CONFIG_H_ - -#include "em_gpio.h" - -/* Edit to match your application. */ -#define GPIO_ACTIVATION_PORT gpioPortC -#define GPIO_ACTIVATION_PIN 9 -#define GPIO_ACTIVE_STATE 0 - -#define RESET_PORT gpioPortC -#define RESET_PIN 10 - -#define STORAGE_SLOT_ID 0 - -/* Do not edit. */ -#define TIME_10MS 10 * TIME_1MS -#define TIME_5MS 5 * TIME_1MS -#define TIME_1MS 1000 - -#define BOOTLOADER_MODE GPIO_ACTIVE_STATE -#define APP_MODE !GPIO_ACTIVE_STATE - -#endif /* BTL_APP_BTL_CONFIG_H_ */ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.c b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.c deleted file mode 100644 index b96643a..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.c +++ /dev/null @@ -1,69 +0,0 @@ -/***************************************************************************//** - * @file btl_gpio.c - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#include -#include "em_cmu.h" -#include "em_gpio.h" -#include "btl_config.h" - -void bootloader_gpioInit(void) -{ - CMU_ClockEnable(cmuClock_GPIO, true); - GPIO_PinModeSet(GPIO_ACTIVATION_PORT, - GPIO_ACTIVATION_PIN, - gpioModePushPull, - !GPIO_ACTIVE_STATE); - - /* Make sure there the reset pin has a pull up. This will prevent unintentional - * resets to occur during initialization. */ - GPIO_PinModeSet(RESET_PORT, RESET_PIN, gpioModePushPull, 1); -} - -void bootloader_setGPIOActivation(uint8_t state) -{ - if(state != 0) - GPIO_PinOutSet(GPIO_ACTIVATION_PORT, GPIO_ACTIVATION_PIN); - else - GPIO_PinOutClear(GPIO_ACTIVATION_PORT, GPIO_ACTIVATION_PIN); -} - -void bootloader_setResetPin(uint8_t state) -{ - if(state != 0) - GPIO_PinOutSet(RESET_PORT, RESET_PIN); - else - GPIO_PinOutClear(RESET_PORT, RESET_PIN); -} diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.h b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.h deleted file mode 100644 index 4d07f01..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_gpio.h +++ /dev/null @@ -1,46 +0,0 @@ -/***************************************************************************//** - * @file btl_gpio.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef BTL_GPIO_H_ -#define BTL_GPIO_H_ - -void bootloader_gpioInit(void); - -void bootloader_setGPIOActivation(uint8_t state); - -void bootloader_setResetPin(uint8_t state); - -#endif /* BTL_GPIO_H_ */ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.c b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.c deleted file mode 100644 index 1b0ab89..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.c +++ /dev/null @@ -1,171 +0,0 @@ -/***************************************************************************//** - * @file btl_xmodem.c - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#include -#include "ncp_usart.h" -#include "uartdrv.h" -#include "udelay.h" -#include "btl_config.h" - -#define SOH 0x01 -#define EOT 0x04 -#define ACK 0x06 -#define NAK 0x15 -#define ETB 0x17 -#define CAN 0x18 -#define C 0x43 -#define EOF 0x1A - -#define XMODEM_DATA_SIZE 128 - -// 128 byte data packets -// This is not what the actual packet looks like -/// XMODEM packet -typedef struct { - uint8_t header; ///< Packet header (@ref XMODEM_CMD_SOH) - uint8_t packetNumber; ///< Packet sequence number - uint8_t packetNumberC; ///< Complement of packet sequence number - uint8_t data[XMODEM_DATA_SIZE]; ///< Payload - uint8_t crcH; ///< CRC high byte - uint8_t crcL; ///< CRC low byte -} SL_ATTRIBUTE_PACKED XmodemPacket_t; - -static XmodemPacket_t packet; - -// http://web.mit.edu/6.115/www/amulet/xmodem.htm -int32_t calcrc(int8_t *ptr, int32_t count) -{ - int32_t crc; - int8_t i; - crc = 0; - while (--count >= 0) { - crc = crc ^ (int32_t) *ptr++ << 8; - i = 8; - do { - if (crc & 0x8000) { - crc = crc << 1 ^ 0x1021; - } else { - crc = crc << 1; - } - } while (--i); - } - return (crc); -} - -/* Keep sending until ACK has been received. */ -uint32_t send_until_ack(uint8_t *data, uint32_t length) -{ - uint8_t success = 0; - uint8_t response = 0; - - do { - /* Clean rx and tx queue. */ - UARTDRV_Abort(handle, uartdrvAbortAll); - - // Send off packet - UARTDRV_ForceTransmit(handle, data, length); - - /* Clean rx queue. */ - UARTDRV_Abort(handle, uartdrvAbortReceive); -// UARTDRV_Abort(handle, uartdrvAbortReceive); - - /* Check if ACK received. */ - UARTDRV_ReceiveB(handle, &response, 1); - - switch (response) { - case ACK: - success = 1; - break; - - case CAN: - return 0; - - default: - - break; - } - } while (success == 0); - - return 1; -} - -uint32_t transmit_SOH_packet(uint8_t *data, uint32_t length, uint8_t number) -{ - packet.header = SOH; - packet.packetNumber = number; - packet.packetNumberC = ~number; - - /* Add 0x1A (EOF) padding if the data is less than 128 bytes. */ - memset((packet.data), EOF, XMODEM_DATA_SIZE); - memcpy((packet.data), data, length); - - packet.crcH = (uint8_t)((calcrc((int8_t *)(packet.data), XMODEM_DATA_SIZE) >> 8) & 0x00FF); - packet.crcL = (uint8_t)(calcrc((int8_t *)(packet.data), XMODEM_DATA_SIZE) & 0x00FF); - return send_until_ack((uint8_t *)&packet, XMODEM_DATA_SIZE + 3 + 2); -} - -uint32_t bootloader_xmodemSend(uint8_t *data, uint32_t length) -{ - uint32_t totalPackets = length / 128; - uint32_t success = 0; - - /* 128 bytes of data are sent at a time. */ - uint16_t packetNumber = 1; - for (int i = 0; i < totalPackets; i++) { - success = transmit_SOH_packet(data + (i * XMODEM_DATA_SIZE), - XMODEM_DATA_SIZE, - (uint8_t)packetNumber); - if (success == 0) { - return 0; - } - - packetNumber = (packetNumber + 1) & 0x00FF; - } - - /* Last packet may not be 128 bytes long. */ - if (length % 128) { - success = transmit_SOH_packet(data + (totalPackets * XMODEM_DATA_SIZE), - length % XMODEM_DATA_SIZE, - (uint8_t)((packetNumber) & 0x00FF)); - - if (success == 0) { - return 0; - } - } - - uint8_t header = EOT; - return send_until_ack(&header, 1); -} diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.h b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.h deleted file mode 100644 index 42d72bc..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/btl_xmodem.h +++ /dev/null @@ -1,42 +0,0 @@ -/***************************************************************************//** - * @file btl_xmodem.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef BTL_APP_BTL_XMODEM_H_ -#define BTL_APP_BTL_XMODEM_H_ - -uint32_t bootloader_xmodemSend(uint8_t *data, uint32_t length); - -#endif /* BTL_APP_BTL_XMODEM_H_ */ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/main.c b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/main.c deleted file mode 100644 index 1329c13..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/main.c +++ /dev/null @@ -1,207 +0,0 @@ -/***************************************************************************//** - * @file main.c - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#include "init_mcu.h" -#include "init_board.h" -#include "init_app.h" -#include "ble-configuration.h" -#include "board_features.h" - -/* BG stack headers */ -#include "bg_types.h" -#include "ncp_gecko.h" -#include "gatt_db.h" -#include "ncp_usart.h" -#include "em_core.h" - -/* libraries containing default gecko configuration values */ -#include "em_emu.h" -#include "em_cmu.h" - -/* Device initialization header */ -#include "hal-config.h" - -#ifdef FEATURE_BOARD_DETECTED -#if defined(HAL_CONFIG) -#include "bsphalconfig.h" -#else -#include "bspconfig.h" -#endif // HAL_CONFIG -#endif // FEATURE_BOARD_DETECTED - -#include "btl_app.h" - -/***********************************************************************************************//** - * @addtogroup Application - * @{ - **************************************************************************************************/ - -/***********************************************************************************************//** - * @addtogroup app - * @{ - **************************************************************************************************/ - -#ifndef MAX_CONNECTIONS -#define MAX_CONNECTIONS 8 -#endif -#ifndef MAX_ADVERTISERS -#define MAX_ADVERTISERS 2 -#endif - -#if defined(NCP_DEEP_SLEEP_ENABLED) -#define NCP_TX_WATCH_COUNTER_MAX 1000 -#else -#define NCP_TX_WATCH_COUNTER_MAX 0xffff -#endif - -uint8_t bluetooth_stack_heap[DEFAULT_BLUETOOTH_HEAP(MAX_CONNECTIONS)]; -static int ncp_tx_queue_watch_counter = 0; - -// Gecko configuration parameters (see gecko_configuration.h) -static const gecko_configuration_t config = { - .config_flags = 0, -#if defined(FEATURE_LFXO) && defined(NCP_DEEP_SLEEP_ENABLED) - .sleep.flags = SLEEP_FLAGS_DEEP_SLEEP_ENABLE, -#else - .sleep.flags = 0, -#endif - .bluetooth.max_connections = MAX_CONNECTIONS, - .bluetooth.max_advertisers = MAX_ADVERTISERS, - .bluetooth.heap = bluetooth_stack_heap, - .bluetooth.heap_size = sizeof(bluetooth_stack_heap), - .bluetooth.sleep_clock_accuracy = 100, // ppm - .gattdb = &bg_gattdb_data, -#if (HAL_PA_ENABLE) - .pa.config_enable = 1, // Set this to be a valid PA config -#if defined(FEATURE_PA_INPUT_FROM_VBAT) - .pa.input = GECKO_RADIO_PA_INPUT_VBAT, // Configure PA input to VBAT -#else - .pa.input = GECKO_RADIO_PA_INPUT_DCDC, -#endif // defined(FEATURE_PA_INPUT_FROM_VBAT) -#endif // (HAL_PA_ENABLE) - .rf.flags = GECKO_RF_CONFIG_ANTENNA, /* Enable antenna configuration. */ - .rf.antenna = GECKO_RF_ANTENNA, /* Select antenna path! */ -}; - -/** - * Handle events meant to be handled locally - */ -static uint32_t local_handle_event(struct gecko_cmd_packet *evt) -{ - bool evt_handled = bootloader_handle_event(evt); - - switch (BGLIB_MSG_ID(evt->header)) { - default: - break; - } - return evt_handled; -} - -/* - * Check if the TX queue has enough space for a new event message. - * A counter is used here for catching a rare situation where the NCP gets stuck somehow. - */ -static bool check_ncp_tx_queue_space() -{ - if (ncp_get_transmit_space_for_events() < NCP_CMD_SIZE) { - ++ncp_tx_queue_watch_counter; - if (ncp_tx_queue_watch_counter > NCP_TX_WATCH_COUNTER_MAX) { - // Fatal error, or the NCP transport has been shut down for too long. - // Reset the queue for keeping the device responsive in case the stack is still running in background. - tx_queue_reset(); - ncp_tx_queue_watch_counter = 0; - return true; - } - return false; - } else { - ncp_tx_queue_watch_counter = 0; - return true; - } -} - -/** - * Extract the next BGAPI event only when there is enough space for buffering it in TX queue. - */ -static struct gecko_cmd_packet *get_bgapi_event() -{ - if (check_ncp_tx_queue_space()) { - return gecko_peek_event(); - } - return NULL; -} - -int main(void) -{ - // Initialize device - initMcu(); - // Initialize board - initBoard(); - // NCP USART init - ncp_usart_init(); - // Initialize application - initApp(); - - bootloader_appInit(); - - // Initialize stack - gecko_init(&config); - - while (1) { - struct gecko_cmd_packet *evt; - ncp_handle_command(); - for (evt = get_bgapi_event(); evt != NULL; evt = get_bgapi_event()) { - if (!ncp_handle_event(evt) && !local_handle_event(evt)) { - // send out the event if not handled either by NCP or locally - ncp_transmit_enqueue(evt); - } - // if a command is received, break and handle the command - if (ncp_command_received()) { - break; - } - } - ncp_transmit(); - - // If an NCP command received, do not sleep - if (!ncp_command_received()) { - CORE_CRITICAL_IRQ_DISABLE(); - gecko_sleep_for_ms(gecko_can_sleep_ms()); - CORE_CRITICAL_IRQ_ENABLE(); - } - } -} - -/** @} (end addtogroup app) */ -/** @} (end addtogroup Application) */ diff --git a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/ncp_usart.h b/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/ncp_usart.h deleted file mode 100644 index 73668ac..0000000 --- a/firmware_upgrade/bluetooth_host_ota_target_controlled/target_mg12/src/ncp_usart.h +++ /dev/null @@ -1,128 +0,0 @@ -/***************************************************************************//** - * @file ncp_usart.h - * @version 1.0.1 - ******************************************************************************* - * # License - * Copyright 2020 Silicon Laboratories Inc. www.silabs.com - ******************************************************************************* - * - * SPDX-License-Identifier: Zlib - * - * The licensor of this software is Silicon Laboratories Inc. - * - * This software is provided 'as-is', without any express or implied - * warranty. In no event will the authors be held liable for any damages - * arising from the use of this software. - * - * Permission is granted to anyone to use this software for any purpose, - * including commercial applications, and to alter it and redistribute it - * freely, subject to the following restrictions: - * - * 1. The origin of this software must not be misrepresented; you must not - * claim that you wrote the original software. If you use this software - * in a product, an acknowledgment in the product documentation would be - * appreciated but is not required. - * 2. Altered source versions must be plainly marked as such, and must not be - * misrepresented as being the original software. - * 3. This notice may not be removed or altered from any source distribution. - * - ******************************************************************************* - * # Experimental Quality - * This code has not been formally tested and is provided as-is. It is not - * suitable for production environments. In addition, this code will not be - * maintained and there may be no bug maintenance planned for these resources. - * Silicon Labs may update projects from time to time. - ******************************************************************************/ - -#ifndef NCP_UART_H_ -#define NCP_UART_H_ - -#include "hal-config.h" -#include "ncp.h" -#include "uartdrv.h" - -#if BSP_UARTNCP_USART_PORT == HAL_SERIAL_PORT_USART0 -// USART0 -#define NCP_USART_UART USART0 -#define NCP_USART_CLK cmuClock_USART0 -#define NCP_USART_IRQ_NAME USART0_RX_IRQHandler -#define NCP_USART_IRQn USART0_RX_IRQn -#define NCP_USART_TX_IRQ_NAME USART0_TX_IRQHandler -#define NCP_USART_TX_IRQn USART0_TX_IRQn -#define NCP_USART_USART 0 -#elif BSP_UARTNCP_USART_PORT == HAL_SERIAL_PORT_USART1 -// USART1 -#define NCP_USART_UART USART1 -#define NCP_USART_CLK cmuClock_USART1 -#define NCP_USART_IRQ_NAME USART1_RX_IRQHandler -#define NCP_USART_IRQn USART1_RX_IRQn -#define NCP_USART_TX_IRQ_NAME USART1_TX_IRQHandler -#define NCP_USART_TX_IRQn USART1_TX_IRQn -#define NCP_USART_USART 1 -#elif BSP_UARTNCP_USART_PORT == HAL_SERIAL_PORT_USART2 -// USART2 -#define NCP_USART_UART USART2 -#define NCP_USART_CLK cmuClock_USART2 -#define NCP_USART_IRQ_NAME USART2_RX_IRQHandler -#define NCP_USART_IRQn USART2_RX_IRQn -#define NCP_USART_TX_IRQ_NAME USART2_TX_IRQHandler -#define NCP_USART_TX_IRQn USART2_TX_IRQn -#define NCP_USART_USART 2 -#elif BSP_UARTNCP_USART_PORT == HAL_SERIAL_PORT_USART3 -// USART3 -#define NCP_USART_UART USART3 -#define NCP_USART_CLK cmuClock_USART3 -#define NCP_USART_IRQ_NAME USART3_RX_IRQHandler -#define NCP_USART_IRQn USART3_RX_IRQn -#define NCP_USART_TX_IRQ_NAME USART3_TX_IRQHandler -#define NCP_USART_TX_IRQn USART3_TX_IRQn -#define NCP_USART_USART 3 -#else -#error "Unsupported UART port!" -#endif - -#define NCP_USART_WAKEUP_SIGNAL (1 << 0) -#define NCP_USART_UPDATE_SIGNAL (1 << 1) -#define NCP_USART_TIMEOUT_SIGNAL (1 << 2) -#define NCP_USART_SECURITY_SIGNAL (1 << 3) - -extern UARTDRV_Handle_t handle; - -/***************************************************************************//** - * @brief - * Initialize USART for NCP. - * - * @details - * This function will initialize USART peripheral and start receiving NCP commands. - * - ******************************************************************************/ -void ncp_usart_init(); - -/***************************************************************************//** - * @brief - * Update USART status for sleep/wakeup. - * - * @details - * This function will handle USART_UPDATE signal and update USART status accordingly. - * - ******************************************************************************/ -void ncp_usart_status_update(); - -/***************************************************************************//** - * @brief - * This function should be called in application's event loop. - * - * @details - * This function will handle an event and return if the event was processed by - * the library or not. - * - * @param[in] evt - * Pointer to the event received from the Bluetooth stack. - * - * @return - * True if the event was processed, False otherwise. - * - ******************************************************************************/ -bool ncp_handle_event(struct gecko_cmd_packet *evt); - -#endif /* NCP_UART_H_ */ diff --git a/security/oob-example/src/central/app.c b/security/oob-example/src/central/app.c index 40c8bf5..c0b482b 100644 --- a/security/oob-example/src/central/app.c +++ b/security/oob-example/src/central/app.c @@ -33,56 +33,59 @@ #define SIGNAL_WRITE_TIMER 1 const uint8_t Svc_uuid[] = { - 0x07, - 0xb9, - 0xf9, - 0xd7, - 0x50, - 0xa1, - 0x20, - 0x89, - 0x77, - 0x40, - 0xcb, - 0xfd, - 0x2c, - 0xc1, - 0x80, - 0x48}; + 0x07, + 0xb9, + 0xf9, + 0xd7, + 0x50, + 0xa1, + 0x20, + 0x89, + 0x77, + 0x40, + 0xcb, + 0xfd, + 0x2c, + 0xc1, + 0x80, + 0x48 +}; const uint8_t Ntf_uuid[] = { - 0x07, - 0xb9, - 0xf9, - 0xd7, - 0x50, - 0xa2, - 0x20, - 0x89, - 0x77, - 0x40, - 0xcb, - 0xfd, - 0x2c, - 0xc1, - 0x80, - 0x48}; + 0x07, + 0xb9, + 0xf9, + 0xd7, + 0x50, + 0xa2, + 0x20, + 0x89, + 0x77, + 0x40, + 0xcb, + 0xfd, + 0x2c, + 0xc1, + 0x80, + 0x48 +}; const uint8_t Wrt_uuid[] = { - 0x07, - 0xb9, - 0xf9, - 0xd7, - 0x50, - 0xa3, - 0x20, - 0x89, - 0x77, - 0x40, - 0xcb, - 0xfd, - 0x2c, - 0xc1, - 0x80, - 0x48}; + 0x07, + 0xb9, + 0xf9, + 0xd7, + 0x50, + 0xa3, + 0x20, + 0x89, + 0x77, + 0x40, + 0xcb, + 0xfd, + 0x2c, + 0xc1, + 0x80, + 0x48 +}; #define PRINT_GATT_INFO @@ -91,7 +94,7 @@ static uint8_t _main_state; static uint32_t _service_handle; static uint16_t ntf_char_handle; static uint16_t wrt_char_handle; -static uint8_t writeBuf[21] = {0}; +static uint8_t writeBuf[21] = { 0 }; static aes_key_128 key_random, key_confirm; @@ -118,21 +121,17 @@ uint8_t Process_scan_response(sl_bt_evt_scanner_legacy_advertisement_report_t *p uint8_t ad_len; uint8_t ad_type; - while (i < (pResp->data.len - 1)) - { - + while (i < (pResp->data.len - 1)) { ad_len = pResp->data.data[i]; ad_type = pResp->data.data[i + 1]; - if (ad_type == 0x06 || ad_type == 0x07) - { + if (ad_type == 0x06 || ad_type == 0x07) { // type 0x06 = More 128-bit UUIDs available // type 0x07 = Complete list of 128-bit UUIDs available // note: this check assumes that the service we are looking for is first // in the list. To be fixed so that there is no such limitation... - if (memcmp(Svc_uuid, &(pResp->data.data[i + 2]), 16) == 0) - { + if (memcmp(Svc_uuid, &(pResp->data.data[i + 2]), 16) == 0) { ad_match_found = 1; break; } @@ -148,13 +147,10 @@ static void writeToPeripheral() sl_status_t ret; uint8_t i = writeBuf[0]; - if (i == '9') - { + if (i == '9') { i = '0'; memset(writeBuf, i, 20); - } - else - { + } else { memset(writeBuf, i + 1, 20); } ret = sl_bt_gatt_write_characteristic_value(_conn_handle, wrt_char_handle, 20, writeBuf); @@ -196,309 +192,286 @@ void sl_bt_on_event(sl_bt_msg_t *evt) uint8_t address_type; uint8_t system_id[8]; - switch (SL_BT_MSG_ID(evt->header)) - { - // ------------------------------- - // This event indicates the device has started and the radio is ready. - // Do not call any stack command before receiving this boot event! - case sl_bt_evt_system_boot_id: - app_log_info("stack version: %u.%u.%u\r\r\n", evt->data.evt_system_boot.major, evt->data.evt_system_boot.minor, evt->data.evt_system_boot.patch); - app_log_info("Central Boot\r\n"); - // Extract unique ID from BT Address. - sc = sl_bt_system_get_identity_address(&address, &address_type); - app_assert_status(sc); - app_log_info("local BT device address: "); - for (uint8_t i = 0; i < 5; i++) - { - app_log_info("%2.2x:", address.addr[5 - i]); - } - app_log_info("%2.2x\r\n", address.addr[0]); - // Pad and reverse unique ID to get System ID. - system_id[0] = address.addr[5]; - system_id[1] = address.addr[4]; - system_id[2] = address.addr[3]; - system_id[3] = 0xFF; - system_id[4] = 0xFE; - system_id[5] = address.addr[2]; - system_id[6] = address.addr[1]; - system_id[7] = address.addr[0]; - - sc = sl_bt_gatt_server_write_attribute_value(gattdb_system_id, - 0, - sizeof(system_id), - system_id); - app_assert_status(sc); - - /* delete all bondings to force the pairing process */ - app_log_info("All bonding deleted\r\n"); - sc = sl_bt_sm_delete_bondings(); - app_assert_status(sc); - - sc = sl_bt_sm_configure(0x0B, sl_bt_sm_io_capability_keyboarddisplay); - app_assert_status(sc); - - sc = sl_bt_sm_set_bondable_mode(1); - app_assert_status(sc); - - sc = sl_bt_sm_set_oob(1, &key_random, &key_confirm); - app_assert_status(sc); - - app_log_info("Enable OOB with Secure Connection Pairing - Success.\r\n"); - app_log_info("16-byte random OOB data: "); - for (uint8_t i = 0; i < 16; i++) - { - app_log("0x%02X ", key_random.data[i]); - } - app_log("\r\n"); - app_log_info("16-byte confirm value: "); - for (uint8_t i = 0; i < 16; i++) - { - app_log("0x%02X ", key_confirm.data[i]); - } - app_log("\r\n"); - - Reset_variables(); - // start discovery - sc = sl_bt_scanner_start(0x01, sl_bt_scanner_discover_generic); - app_assert_status(sc); - break; - case sl_bt_evt_scanner_legacy_advertisement_report_id: - // process scan responses: this function returns 1 if we found the service we are looking for - if (Process_scan_response(&(evt->data.evt_scanner_legacy_advertisement_report)) > 0) - { - uint8_t pResp_connection; - - // match found -> stop discovery and try to connect - sc = sl_bt_scanner_stop(); + switch (SL_BT_MSG_ID(evt->header)) { + // ------------------------------- + // This event indicates the device has started and the radio is ready. + // Do not call any stack command before receiving this boot event! + case sl_bt_evt_system_boot_id: + app_log_info("stack version: %u.%u.%u\r\r\n", evt->data.evt_system_boot.major, evt->data.evt_system_boot.minor, evt->data.evt_system_boot.patch); + app_log_info("Central Boot\r\n"); + // Extract unique ID from BT Address. + sc = sl_bt_system_get_identity_address(&address, &address_type); + app_assert_status(sc); + app_log_info("local BT device address: "); + for (uint8_t i = 0; i < 5; i++) { + app_log_info("%2.2x:", address.addr[5 - i]); + } + app_log_info("%2.2x\r\n", address.addr[0]); + // Pad and reverse unique ID to get System ID. + system_id[0] = address.addr[5]; + system_id[1] = address.addr[4]; + system_id[2] = address.addr[3]; + system_id[3] = 0xFF; + system_id[4] = 0xFE; + system_id[5] = address.addr[2]; + system_id[6] = address.addr[1]; + system_id[7] = address.addr[0]; + + sc = sl_bt_gatt_server_write_attribute_value(gattdb_system_id, + 0, + sizeof(system_id), + system_id); app_assert_status(sc); - sc = sl_bt_connection_open(evt->data.evt_scanner_legacy_advertisement_report.address, evt->data.evt_scanner_legacy_advertisement_report.address_type, 0x01, &pResp_connection); + /* delete all bondings to force the pairing process */ + app_log_info("All bonding deleted\r\n"); + sc = sl_bt_sm_delete_bondings(); app_assert_status(sc); - // make copy of connection handle for later use (for example, to cancel the connection attempt) - _conn_handle = pResp_connection; - } - break; - // ------------------------------- - // This event indicates that a new connection was opened. - case sl_bt_evt_connection_opened_id: - // Start service discovery (we are only interested in one UUID) - app_log_info("Connected\r\n"); - sc = sl_bt_gatt_discover_primary_services_by_uuid(_conn_handle, 16, Svc_uuid); - app_assert_status(sc); - _main_state = FIND_SERVICE; - break; - - case sl_bt_evt_connection_closed_id: - // start discovery - sc = sl_bt_scanner_start(0x01, sl_bt_scanner_discover_generic); - app_assert_status(sc); - sc = sl_sleeptimer_stop_timer(&sleep_timer_handle); - app_assert_status(sc); - break; - - case sl_bt_evt_gatt_service_id: - if (evt->data.evt_gatt_service.uuid.len == 16) - { - if (memcmp(Svc_uuid, evt->data.evt_gatt_service.uuid.data, 16) == 0) - { - // Service Found. - app_log_info("Specified Service Found.\r\n"); - _service_handle = evt->data.evt_gatt_service.service; - } - } - break; - - case sl_bt_evt_gatt_characteristic_id: - if (evt->data.evt_gatt_characteristic.uuid.len == 16) - { - if (memcmp(Ntf_uuid, evt->data.evt_gatt_characteristic.uuid.data, 16) == 0) - { - ntf_char_handle = evt->data.evt_gatt_characteristic.characteristic; - } - else if (memcmp(Wrt_uuid, evt->data.evt_gatt_characteristic.uuid.data, 16) == 0) - { - wrt_char_handle = evt->data.evt_gatt_characteristic.characteristic; - } - } - break; + sc = sl_bt_sm_configure(0x0B, sl_bt_sm_io_capability_keyboarddisplay); + app_assert_status(sc); - case sl_bt_evt_gatt_procedure_completed_id: - switch (_main_state) - { - case FIND_SERVICE: + sc = sl_bt_sm_set_bondable_mode(1); + app_assert_status(sc); - if (_service_handle != 0) - { - // Service found, next search for characteristics - sc = sl_bt_gatt_discover_characteristics(_conn_handle, _service_handle); - app_assert_status(sc); - _main_state = FIND_CHAR; + sc = sl_bt_sm_set_oob(1, &key_random, &key_confirm); + app_assert_status(sc); + + app_log_info("Enable OOB with Secure Connection Pairing - Success.\r\n"); + app_log_info("16-byte random OOB data: "); + for (uint8_t i = 0; i < 16; i++) { + app_log("0x%02X ", key_random.data[i]); } - else - { - // no service found -> disconnect - sc = sl_bt_connection_close(_conn_handle); - app_assert_status(sc); + app_log("\r\n"); + app_log_info("16-byte confirm value: "); + for (uint8_t i = 0; i < 16; i++) { + app_log("0x%02X ", key_confirm.data[i]); } + app_log("\r\n"); + + Reset_variables(); + // start discovery + sc = sl_bt_scanner_start(0x01, sl_bt_scanner_discover_generic); + app_assert_status(sc); break; + case sl_bt_evt_scanner_legacy_advertisement_report_id: + // process scan responses: this function returns 1 if we found the service we are looking for + if (Process_scan_response(&(evt->data.evt_scanner_legacy_advertisement_report)) > 0) { + uint8_t pResp_connection; - case FIND_CHAR: - if (ntf_char_handle && wrt_char_handle) - { - // Char found, turn on indications - sc = sl_bt_gatt_set_characteristic_notification(_conn_handle, ntf_char_handle, sl_bt_gatt_notification); + // match found -> stop discovery and try to connect + sc = sl_bt_scanner_stop(); app_assert_status(sc); - _main_state = ENABLE_NOTIF; - } - else - { - // no characteristic found? -> disconnect - sc = sl_bt_connection_close(_conn_handle); + + sc = sl_bt_connection_open(evt->data.evt_scanner_legacy_advertisement_report.address, evt->data.evt_scanner_legacy_advertisement_report.address_type, 0x01, &pResp_connection); app_assert_status(sc); + + // make copy of connection handle for later use (for example, to cancel the connection attempt) + _conn_handle = pResp_connection; } break; - - case ENABLE_NOTIF: - _main_state = DATA_MODE; - sc = sl_sleeptimer_start_periodic_timer_ms(&sleep_timer_handle, - TIMER_TIMEOUT, - sleeptimer_callback, - (void *)NULL, - 0, - 0); + // ------------------------------- + // This event indicates that a new connection was opened. + case sl_bt_evt_connection_opened_id: + // Start service discovery (we are only interested in one UUID) + app_log_info("Connected\r\n"); + sc = sl_bt_gatt_discover_primary_services_by_uuid(_conn_handle, 16, Svc_uuid); app_assert_status(sc); + _main_state = FIND_SERVICE; break; - default: + case sl_bt_evt_connection_closed_id: + // start discovery + sc = sl_bt_scanner_start(0x01, sl_bt_scanner_discover_generic); + app_assert_status(sc); + sc = sl_sleeptimer_stop_timer(&sleep_timer_handle); + app_assert_status(sc); break; - } - break; - - case sl_bt_evt_gatt_characteristic_value_id: - if ((evt->data.evt_gatt_characteristic_value.att_opcode == sl_bt_gatt_handle_value_notification) && (evt->data.evt_gatt_characteristic_value.characteristic == ntf_char_handle)) - { - // TODO: data notification is received here -#ifdef PRINT_GATT_INFO - app_log_info("Gatt Notification Received: "); - for (uint8_t i = 0; i < evt->data.evt_gatt_characteristic_value.value.len; i++) - { - app_log("%c", evt->data.evt_gatt_characteristic_value.value.data[i]); - } - app_log("\r\n"); -#endif - } - break; - - case sl_bt_evt_system_external_signal_id: - if(SIGNAL_WRITE_TIMER == evt->data.evt_system_external_signal.extsignals){ - if ((_conn_handle != 0xFF) && (wrt_char_handle != 0)) - { - writeToPeripheral(); + case sl_bt_evt_gatt_service_id: + if (evt->data.evt_gatt_service.uuid.len == 16) { + if (memcmp(Svc_uuid, evt->data.evt_gatt_service.uuid.data, 16) == 0) { + // Service Found. + app_log_info("Specified Service Found.\r\n"); + _service_handle = evt->data.evt_gatt_service.service; + } } - } - break; - - case sl_bt_evt_sm_confirm_bonding_id: - app_log_info("Bonding confirmed\r\n"); - sc = sl_bt_sm_bonding_confirm(evt->data.evt_sm_confirm_bonding.connection, 1); - app_assert_status(sc); - break; - - case sl_bt_evt_sm_passkey_display_id: - app_log_info("Passkey display\r\n"); - // app_log_info("Enter this passkey on the tablet:\r\n%d\r\n", - // evt->data.evt_sm_passkey_display.passkey); - break; - - case sl_bt_evt_sm_passkey_request_id: - app_log_info("Passkey request\r\n"); - // app_log_info("Enter the passkey you see on the tablet\r\n"); - break; - - case sl_bt_evt_sm_confirm_passkey_id: - app_log_info("Confirm passkey\r\n"); - // app_log_info("Are you see the same passkey on the tablet: %d (y/n)?\r\n",evt->data.evt_sm_confirm_passkey.passkey); - break; - - case sl_bt_evt_sm_bonded_id: - /* The bonding/pairing was successful so set the flag to allow indications to proceed */ - app_log_info("Bonding completed\r\n"); - break; - - case sl_bt_evt_sm_bonding_failed_id: - /* If the attempt at bonding/pairing failed, clear the bonded flag and display the reason */ - app_log_info("Bonding failed: "); - switch (evt->data.evt_sm_bonding_failed.reason) - { - case SL_STATUS_BT_SMP_PASSKEY_ENTRY_FAILED: - app_log_info("The user input of passkey failed\r\n"); break; - case SL_STATUS_BT_SMP_OOB_NOT_AVAILABLE: - app_log_info("Out of Band data is not available for authentication\r\n"); + case sl_bt_evt_gatt_characteristic_id: + if (evt->data.evt_gatt_characteristic.uuid.len == 16) { + if (memcmp(Ntf_uuid, evt->data.evt_gatt_characteristic.uuid.data, 16) == 0) { + ntf_char_handle = evt->data.evt_gatt_characteristic.characteristic; + } else if (memcmp(Wrt_uuid, evt->data.evt_gatt_characteristic.uuid.data, 16) == 0) { + wrt_char_handle = evt->data.evt_gatt_characteristic.characteristic; + } + } break; - case SL_STATUS_BT_SMP_AUTHENTICATION_REQUIREMENTS: - app_log_info("The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices\r\n"); + case sl_bt_evt_gatt_procedure_completed_id: + switch (_main_state) { + case FIND_SERVICE: + + if (_service_handle != 0) { + // Service found, next search for characteristics + sc = sl_bt_gatt_discover_characteristics(_conn_handle, _service_handle); + app_assert_status(sc); + _main_state = FIND_CHAR; + } else { + // no service found -> disconnect + sc = sl_bt_connection_close(_conn_handle); + app_assert_status(sc); + } + break; + + case FIND_CHAR: + if (ntf_char_handle && wrt_char_handle) { + // Char found, turn on indications + sc = sl_bt_gatt_set_characteristic_notification(_conn_handle, ntf_char_handle, sl_bt_gatt_notification); + app_assert_status(sc); + _main_state = ENABLE_NOTIF; + } else { + // no characteristic found? -> disconnect + sc = sl_bt_connection_close(_conn_handle); + app_assert_status(sc); + } + break; + + case ENABLE_NOTIF: + _main_state = DATA_MODE; + sc = sl_sleeptimer_start_periodic_timer_ms(&sleep_timer_handle, + TIMER_TIMEOUT, + sleeptimer_callback, + (void *)NULL, + 0, + 0); + app_assert_status(sc); + break; + + default: + break; + } break; - case SL_STATUS_BT_SMP_CONFIRM_VALUE_FAILED: - app_log_info("The confirm value does not match the calculated compare value\r\n"); + case sl_bt_evt_gatt_characteristic_value_id: + if ((evt->data.evt_gatt_characteristic_value.att_opcode == sl_bt_gatt_handle_value_notification) && (evt->data.evt_gatt_characteristic_value.characteristic == ntf_char_handle)) { + // TODO: data notification is received here +#ifdef PRINT_GATT_INFO + app_log_info("Gatt Notification Received: "); + for (uint8_t i = 0; i < evt->data.evt_gatt_characteristic_value.value.len; i++) { + app_log("%c", evt->data.evt_gatt_characteristic_value.value.data[i]); + } + app_log("\r\n"); +#endif + } break; - case SL_STATUS_BT_SMP_PAIRING_NOT_SUPPORTED: - app_log_info("Pairing is not supported by the device\r\n"); + case sl_bt_evt_system_external_signal_id: + if (SIGNAL_WRITE_TIMER == evt->data.evt_system_external_signal.extsignals) { + if ((_conn_handle != 0xFF) && (wrt_char_handle != 0)) { + writeToPeripheral(); + } + } break; - case SL_STATUS_BT_SMP_ENCRYPTION_KEY_SIZE: - app_log_info("The resultant encryption key size is insufficient for the security requirements of this device\r\n"); + case sl_bt_evt_sm_confirm_bonding_id: + app_log_info("Bonding confirmed\r\n"); + sc = sl_bt_sm_bonding_confirm(evt->data.evt_sm_confirm_bonding.connection, 1); + app_assert_status(sc); break; - case SL_STATUS_BT_SMP_COMMAND_NOT_SUPPORTED: - app_log_info("The SMP command received is not supported on this device\r\n"); + case sl_bt_evt_sm_passkey_display_id: + app_log_info("Passkey display\r\n"); + // app_log_info("Enter this passkey on the tablet:\r\n%d\r\n", + // evt->data.evt_sm_passkey_display.passkey); break; - case SL_STATUS_BT_SMP_UNSPECIFIED_REASON: - app_log_info("Pairing failed due to an unspecified reason\r\n"); + case sl_bt_evt_sm_passkey_request_id: + app_log_info("Passkey request\r\n"); + // app_log_info("Enter the passkey you see on the tablet\r\n"); break; - case SL_STATUS_BT_SMP_REPEATED_ATTEMPTS: - app_log_info("Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request\r\n"); + case sl_bt_evt_sm_confirm_passkey_id: + app_log_info("Confirm passkey\r\n"); + // app_log_info("Are you see the same passkey on the tablet: %d (y/n)?\r\n",evt->data.evt_sm_confirm_passkey.passkey); break; - case SL_STATUS_BT_SMP_INVALID_PARAMETERS: - app_log_info("Invalid Parameters\r\n"); + case sl_bt_evt_sm_bonded_id: + /* The bonding/pairing was successful so set the flag to allow indications to proceed */ + app_log_info("Bonding completed\r\n"); break; - case SL_STATUS_BT_SMP_DHKEY_CHECK_FAILED: - app_log_info("The bonding does not exist\r\n"); - break; + case sl_bt_evt_sm_bonding_failed_id: + /* If the attempt at bonding/pairing failed, clear the bonded flag and display the reason */ + app_log_info("Bonding failed: "); + switch (evt->data.evt_sm_bonding_failed.reason) { + case SL_STATUS_BT_SMP_PASSKEY_ENTRY_FAILED: + app_log_info("The user input of passkey failed\r\n"); + break; + + case SL_STATUS_BT_SMP_OOB_NOT_AVAILABLE: + app_log_info("Out of Band data is not available for authentication\r\n"); + break; + + case SL_STATUS_BT_SMP_AUTHENTICATION_REQUIREMENTS: + app_log_info("The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices\r\n"); + break; + + case SL_STATUS_BT_SMP_CONFIRM_VALUE_FAILED: + app_log_info("The confirm value does not match the calculated compare value\r\n"); + break; + + case SL_STATUS_BT_SMP_PAIRING_NOT_SUPPORTED: + app_log_info("Pairing is not supported by the device\r\n"); + break; + + case SL_STATUS_BT_SMP_ENCRYPTION_KEY_SIZE: + app_log_info("The resultant encryption key size is insufficient for the security requirements of this device\r\n"); + break; + + case SL_STATUS_BT_SMP_COMMAND_NOT_SUPPORTED: + app_log_info("The SMP command received is not supported on this device\r\n"); + break; + + case SL_STATUS_BT_SMP_UNSPECIFIED_REASON: + app_log_info("Pairing failed due to an unspecified reason\r\n"); + break; + + case SL_STATUS_BT_SMP_REPEATED_ATTEMPTS: + app_log_info("Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request\r\n"); + break; + + case SL_STATUS_BT_SMP_INVALID_PARAMETERS: + app_log_info("Invalid Parameters\r\n"); + break; + + case SL_STATUS_BT_SMP_DHKEY_CHECK_FAILED: + app_log_info("The bonding does not exist\r\n"); + break; + + case SL_STATUS_BT_CTRL_PIN_OR_KEY_MISSING: + app_log_info("Pairing failed because of missing PIN, or authentication failed because of missing Key\r\n"); + break; + + case SL_STATUS_TIMEOUT: + app_log_info("Operation timed out\r\n"); + break; + + default: + app_log_info("Unknown error: 0x%X\r\n", evt->data.evt_sm_bonding_failed.reason); + break; + } - case SL_STATUS_BT_CTRL_PIN_OR_KEY_MISSING: - app_log_info("Pairing failed because of missing PIN, or authentication failed because of missing Key\r\n"); break; - case SL_STATUS_TIMEOUT: - app_log_info("Operation timed out\r\n"); - break; + /////////////////////////////////////////////////////////////////////////// + // Add additional event handlers here as your application requires! // + /////////////////////////////////////////////////////////////////////////// + // ------------------------------- + // Default event handler. default: - app_log_info("Unknown error: 0x%X\r\n", evt->data.evt_sm_bonding_failed.reason); break; - } - - break; - - /////////////////////////////////////////////////////////////////////////// - // Add additional event handlers here as your application requires! // - /////////////////////////////////////////////////////////////////////////// - - // ------------------------------- - // Default event handler. - default: - break; } } @@ -510,10 +483,10 @@ void sl_bt_on_event(sl_bt_msg_t *evt) * @param[in] handle Handle of the sleeptimer instance * @param[in] data Callback data ******************************************************************************/ -void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data){ +void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data) +{ (void)handle; (void)data; sl_bt_external_signal(SIGNAL_WRITE_TIMER); - } diff --git a/security/oob-example/src/peripheral/app.c b/security/oob-example/src/peripheral/app.c index c49a288..c7739b6 100644 --- a/security/oob-example/src/peripheral/app.c +++ b/security/oob-example/src/peripheral/app.c @@ -24,8 +24,6 @@ #include "string.h" #include "stdio.h" - - #define TIMER_TIMEOUT 3000 #define SIGNAL_NOTIFY_TIMER 1 #define LOCAL_ECHO @@ -40,8 +38,6 @@ #define ASCII_NUMBER_CONVERT 48 #define ASCII_BACKSPACE 8 - - #ifndef MAX_CONNECTIONS #define MAX_CONNECTIONS 4 #endif @@ -54,12 +50,11 @@ static void read_oob_data(); sl_sleeptimer_timer_handle_t sleep_timer_handle; void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data); - uint8_t rx_oob_buf[32]; uint8_t rx_oob_buf_ascii[64]; static uint16_t notifyEnabled = 0; static uint8_t connHandle = 0xFF; -static uint8_t notifyBuf[20] = {0}; +static uint8_t notifyBuf[20] = { 0 }; // The advertising set handle allocated from Bluetooth stack. static uint8_t advertising_set_handle = 0xff; static uint8_t _oob_state = STATE_IDLE_MODE; @@ -86,8 +81,7 @@ SL_WEAK void app_process_action(void) // This is called infinitely. // // Do not call blocking functions from here! // ///////////////////////////////////////////////////////////////////////////// - if (STATE_OOB_MODE == _oob_state) - { + if (STATE_OOB_MODE == _oob_state) { read_oob_data(); } } @@ -105,237 +99,224 @@ void sl_bt_on_event(sl_bt_msg_t *evt) uint8_t address_type; uint8_t system_id[8]; - switch (SL_BT_MSG_ID(evt->header)) - { - // ------------------------------- - // This event indicates the device has started and the radio is ready. - // Do not call any stack command before receiving this boot event! - case sl_bt_evt_system_boot_id: - memset(notifyBuf, '0', 20); - app_log_info("stack version: %u.%u.%u\r\r\n", evt->data.evt_system_boot.major, evt->data.evt_system_boot.minor, evt->data.evt_system_boot.patch); - app_log_info("Peripheral Boot\r\n"); - // Extract unique ID from BT Address. - sc = sl_bt_system_get_identity_address(&address, &address_type); - app_assert_status(sc); - app_log_info("local BT device address: "); - for (uint8_t i = 0; i < 5; i++) - { - app_log("%2.2x:", address.addr[5 - i]); - } - app_log("%2.2x\r\n", address.addr[0]); - // Pad and reverse unique ID to get System ID. - system_id[0] = address.addr[5]; - system_id[1] = address.addr[4]; - system_id[2] = address.addr[3]; - system_id[3] = 0xFF; - system_id[4] = 0xFE; - system_id[5] = address.addr[2]; - system_id[6] = address.addr[1]; - system_id[7] = address.addr[0]; - - sc = sl_bt_gatt_server_write_attribute_value(gattdb_system_id, - 0, - sizeof(system_id), - system_id); - app_assert_status(sc); - // Create an advertising set. - sc = sl_bt_advertiser_create_set(&advertising_set_handle); - app_assert_status(sc); - app_log_info("All bonding deleted\r\n"); - sc = sl_bt_sm_delete_bondings(); - app_assert_status(sc); + switch (SL_BT_MSG_ID(evt->header)) { + // ------------------------------- + // This event indicates the device has started and the radio is ready. + // Do not call any stack command before receiving this boot event! + case sl_bt_evt_system_boot_id: + memset(notifyBuf, '0', 20); + app_log_info("stack version: %u.%u.%u\r\r\n", evt->data.evt_system_boot.major, evt->data.evt_system_boot.minor, evt->data.evt_system_boot.patch); + app_log_info("Peripheral Boot\r\n"); + // Extract unique ID from BT Address. + sc = sl_bt_system_get_identity_address(&address, &address_type); + app_assert_status(sc); + app_log_info("local BT device address: "); + for (uint8_t i = 0; i < 5; i++) { + app_log("%2.2x:", address.addr[5 - i]); + } + app_log("%2.2x\r\n", address.addr[0]); + // Pad and reverse unique ID to get System ID. + system_id[0] = address.addr[5]; + system_id[1] = address.addr[4]; + system_id[2] = address.addr[3]; + system_id[3] = 0xFF; + system_id[4] = 0xFE; + system_id[5] = address.addr[2]; + system_id[6] = address.addr[1]; + system_id[7] = address.addr[0]; + + sc = sl_bt_gatt_server_write_attribute_value(gattdb_system_id, + 0, + sizeof(system_id), + system_id); + app_assert_status(sc); + // Create an advertising set. + sc = sl_bt_advertiser_create_set(&advertising_set_handle); + app_assert_status(sc); + app_log_info("All bonding deleted\r\n"); + sc = sl_bt_sm_delete_bondings(); + app_assert_status(sc); - /* bit 3 of flag is 0 to allow legacy pairing */ - sc = sl_bt_sm_configure(0x0B, sl_bt_sm_io_capability_keyboarddisplay); - app_assert_status(sc); + /* bit 3 of flag is 0 to allow legacy pairing */ + sc = sl_bt_sm_configure(0x0B, sl_bt_sm_io_capability_keyboarddisplay); + app_assert_status(sc); - sc = sl_bt_sm_set_bondable_mode(1); - app_assert_status(sc); + sc = sl_bt_sm_set_bondable_mode(1); + app_assert_status(sc); - app_log_info("Use Secure Connection Pairing.\r\n"); - app_log_info("Enter 32-byte OOB data and confirm value.\r\n"); - sc = sl_bt_sm_set_oob(1, NULL, NULL); - app_assert_status(sc); + app_log_info("Use Secure Connection Pairing.\r\n"); + app_log_info("Enter 32-byte OOB data and confirm value.\r\n"); + sc = sl_bt_sm_set_oob(1, NULL, NULL); + app_assert_status(sc); - _oob_state = STATE_OOB_MODE; - break; - - // ------------------------------- - // This event indicates that a new connection was opened. - case sl_bt_evt_connection_opened_id: - app_log_info("Connected\r\n"); - connHandle = evt->data.evt_connection_opened.connection; - // a delay could be needed before sending the security request to the phone, sending the request too soon - // can cause the phone to drop it. 0.5s is a suggested value - sl_sleeptimer_delay_millisecond(500); - sc = sl_bt_sm_increase_security(connHandle); - app_assert_status(sc); - app_log_info("Increasing security\r\n"); - break; + _oob_state = STATE_OOB_MODE; + break; - // ------------------------------- - // This event indicates that a connection was closed. - case sl_bt_evt_connection_closed_id: - // Restart advertising after client has disconnected. - sc = sl_bt_legacy_advertiser_start(advertising_set_handle, - sl_bt_advertiser_connectable_scannable); - app_assert_status(sc); - sc = sl_sleeptimer_stop_timer(&sleep_timer_handle); - app_assert_status(sc); - break; - case sl_bt_evt_gatt_server_characteristic_status_id: - /* Char status changed */ - if ((evt->data.evt_gatt_server_characteristic_status.characteristic == gattdb_ntf_char) && (evt->data.evt_gatt_server_characteristic_status.status_flags == 0x01)) - { - notifyEnabled = evt->data.evt_gatt_server_characteristic_status.client_config_flags; - } - if (notifyEnabled == sl_bt_gatt_server_notification) - { - sc = sl_sleeptimer_start_periodic_timer_ms(&sleep_timer_handle, - TIMER_TIMEOUT, - sleeptimer_callback, - (void *)NULL, - 0, - 0); + // ------------------------------- + // This event indicates that a new connection was opened. + case sl_bt_evt_connection_opened_id: + app_log_info("Connected\r\n"); + connHandle = evt->data.evt_connection_opened.connection; + // a delay could be needed before sending the security request to the phone, sending the request too soon + // can cause the phone to drop it. 0.5s is a suggested value + sl_sleeptimer_delay_millisecond(500); + sc = sl_bt_sm_increase_security(connHandle); + app_assert_status(sc); + app_log_info("Increasing security\r\n"); + break; + + // ------------------------------- + // This event indicates that a connection was closed. + case sl_bt_evt_connection_closed_id: + // Restart advertising after client has disconnected. + sc = sl_bt_legacy_advertiser_start(advertising_set_handle, + sl_bt_advertiser_connectable_scannable); app_assert_status(sc); - } - else - { sc = sl_sleeptimer_stop_timer(&sleep_timer_handle); app_assert_status(sc); - } - break; - - case sl_bt_evt_gatt_server_attribute_value_id: - if ((evt->data.evt_gatt_server_attribute_value.att_opcode == sl_bt_gatt_write_request) && (evt->data.evt_gatt_server_attribute_value.attribute == gattdb_wrt_char)) - { - app_log_info("Gatt Write Received: "); - for (uint8_t i = 0; i < evt->data.evt_gatt_server_attribute_value.value.len; i++) - { - app_log("%c", evt->data.evt_gatt_server_attribute_value.value.data[i]); + break; + case sl_bt_evt_gatt_server_characteristic_status_id: + /* Char status changed */ + if ((evt->data.evt_gatt_server_characteristic_status.characteristic == gattdb_ntf_char) && (evt->data.evt_gatt_server_characteristic_status.status_flags == 0x01)) { + notifyEnabled = evt->data.evt_gatt_server_characteristic_status.client_config_flags; } - app_log("\r\n"); - } - break; + if (notifyEnabled == sl_bt_gatt_server_notification) { + sc = sl_sleeptimer_start_periodic_timer_ms(&sleep_timer_handle, + TIMER_TIMEOUT, + sleeptimer_callback, + (void *)NULL, + 0, + 0); + app_assert_status(sc); + } else { + sc = sl_sleeptimer_stop_timer(&sleep_timer_handle); + app_assert_status(sc); + } + break; - case sl_bt_evt_system_external_signal_id: - if(evt->data.evt_system_external_signal.extsignals == SIGNAL_NOTIFY_TIMER){ - if ((connHandle != 0xFF) && (notifyEnabled == sl_bt_gatt_server_notification)) - { + case sl_bt_evt_gatt_server_attribute_value_id: + if ((evt->data.evt_gatt_server_attribute_value.att_opcode == sl_bt_gatt_write_request) && (evt->data.evt_gatt_server_attribute_value.attribute == gattdb_wrt_char)) { + app_log_info("Gatt Write Received: "); + for (uint8_t i = 0; i < evt->data.evt_gatt_server_attribute_value.value.len; i++) { + app_log("%c", evt->data.evt_gatt_server_attribute_value.value.data[i]); + } + app_log("\r\n"); + } + break; + + case sl_bt_evt_system_external_signal_id: + if (evt->data.evt_system_external_signal.extsignals == SIGNAL_NOTIFY_TIMER) { + if ((connHandle != 0xFF) && (notifyEnabled == sl_bt_gatt_server_notification)) { uint8_t i = notifyBuf[0]; - if (i == '9') - { + if (i == '9') { i = '0'; memset(notifyBuf, i, 20); - } - else - { + } else { memset(notifyBuf, i + 1, 20); } sc = sl_bt_gatt_server_send_notification(connHandle, gattdb_ntf_char, 20, notifyBuf); app_assert_status(sc); } } - break; - - case sl_bt_evt_sm_confirm_bonding_id: - sc = sl_bt_sm_bonding_confirm(evt->data.evt_sm_confirm_bonding.connection, 1); - app_assert_status(sc); - app_log_info("Bonding confirmed\r\n"); - break; - - case sl_bt_evt_sm_passkey_display_id: - app_log_info("Passkey display\r\n"); - // app_log_info("Enter this passkey on the tablet:\r\n%d\r\n", - // evt->data.evt_sm_passkey_display.passkey); - break; - - case sl_bt_evt_sm_passkey_request_id: - app_log_info("Passkey request\r\n"); - // app_log_info("Enter the passkey you see on the tablet\r\n"); - break; - - case sl_bt_evt_sm_confirm_passkey_id: - app_log_info("Confirm passkey\r\n"); - // app_log_info("Are you see the same passkey on the tablet: %d (y/n)?\r\n",evt->data.evt_sm_confirm_passkey.passkey); - break; - - case sl_bt_evt_sm_bonded_id: - /* The bonding/pairing was successful so set the flag to allow indications to proceed */ - app_log_info("Bonding completed\r\n"); - break; - - case sl_bt_evt_sm_bonding_failed_id: - /* If the attempt at bonding/pairing failed, clear the bonded flag and display the reason */ - app_log_info("Bonding failed: "); - switch (evt->data.evt_sm_bonding_failed.reason) - { - case SL_STATUS_BT_SMP_PASSKEY_ENTRY_FAILED: - app_log_info("The user input of passkey failed\r\n"); - break; - - case SL_STATUS_BT_SMP_OOB_NOT_AVAILABLE: - app_log_info("Out of Band data is not available for authentication\r\n"); - break; - - case SL_STATUS_BT_SMP_AUTHENTICATION_REQUIREMENTS: - app_log_info("The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices\r\n"); - break; - - case SL_STATUS_BT_SMP_CONFIRM_VALUE_FAILED: - app_log_info("The confirm value does not match the calculated compare value\r\n"); break; - case SL_STATUS_BT_SMP_PAIRING_NOT_SUPPORTED: - app_log_info("Pairing is not supported by the device\r\n"); - break; - - case SL_STATUS_BT_SMP_ENCRYPTION_KEY_SIZE: - app_log_info("The resultant encryption key size is insufficient for the security requirements of this device\r\n"); - break; - - case SL_STATUS_BT_SMP_COMMAND_NOT_SUPPORTED: - app_log_info("The SMP command received is not supported on this device\r\n"); + case sl_bt_evt_sm_confirm_bonding_id: + sc = sl_bt_sm_bonding_confirm(evt->data.evt_sm_confirm_bonding.connection, 1); + app_assert_status(sc); + app_log_info("Bonding confirmed\r\n"); break; - case SL_STATUS_BT_SMP_UNSPECIFIED_REASON: - app_log_info("Pairing failed due to an unspecified reason\r\n"); + case sl_bt_evt_sm_passkey_display_id: + app_log_info("Passkey display\r\n"); + // app_log_info("Enter this passkey on the tablet:\r\n%d\r\n", + // evt->data.evt_sm_passkey_display.passkey); break; - case SL_STATUS_BT_SMP_REPEATED_ATTEMPTS: - app_log_info("Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request\r\n"); + case sl_bt_evt_sm_passkey_request_id: + app_log_info("Passkey request\r\n"); + // app_log_info("Enter the passkey you see on the tablet\r\n"); break; - case SL_STATUS_BT_SMP_INVALID_PARAMETERS: - app_log_info("Invalid Parameters\r\n"); + case sl_bt_evt_sm_confirm_passkey_id: + app_log_info("Confirm passkey\r\n"); + // app_log_info("Are you see the same passkey on the tablet: %d (y/n)?\r\n",evt->data.evt_sm_confirm_passkey.passkey); break; - case SL_STATUS_BT_SMP_DHKEY_CHECK_FAILED: - app_log_info("The bonding does not exist\r\n"); + case sl_bt_evt_sm_bonded_id: + /* The bonding/pairing was successful so set the flag to allow indications to proceed */ + app_log_info("Bonding completed\r\n"); break; - case SL_STATUS_BT_CTRL_PIN_OR_KEY_MISSING: - app_log_info("Pairing failed because of missing PIN, or authentication failed because of missing Key\r\n"); + case sl_bt_evt_sm_bonding_failed_id: + /* If the attempt at bonding/pairing failed, clear the bonded flag and display the reason */ + app_log_info("Bonding failed: "); + switch (evt->data.evt_sm_bonding_failed.reason) { + case SL_STATUS_BT_SMP_PASSKEY_ENTRY_FAILED: + app_log_info("The user input of passkey failed\r\n"); + break; + + case SL_STATUS_BT_SMP_OOB_NOT_AVAILABLE: + app_log_info("Out of Band data is not available for authentication\r\n"); + break; + + case SL_STATUS_BT_SMP_AUTHENTICATION_REQUIREMENTS: + app_log_info("The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices\r\n"); + break; + + case SL_STATUS_BT_SMP_CONFIRM_VALUE_FAILED: + app_log_info("The confirm value does not match the calculated compare value\r\n"); + break; + + case SL_STATUS_BT_SMP_PAIRING_NOT_SUPPORTED: + app_log_info("Pairing is not supported by the device\r\n"); + break; + + case SL_STATUS_BT_SMP_ENCRYPTION_KEY_SIZE: + app_log_info("The resultant encryption key size is insufficient for the security requirements of this device\r\n"); + break; + + case SL_STATUS_BT_SMP_COMMAND_NOT_SUPPORTED: + app_log_info("The SMP command received is not supported on this device\r\n"); + break; + + case SL_STATUS_BT_SMP_UNSPECIFIED_REASON: + app_log_info("Pairing failed due to an unspecified reason\r\n"); + break; + + case SL_STATUS_BT_SMP_REPEATED_ATTEMPTS: + app_log_info("Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request\r\n"); + break; + + case SL_STATUS_BT_SMP_INVALID_PARAMETERS: + app_log_info("Invalid Parameters\r\n"); + break; + + case SL_STATUS_BT_SMP_DHKEY_CHECK_FAILED: + app_log_info("The bonding does not exist\r\n"); + break; + + case SL_STATUS_BT_CTRL_PIN_OR_KEY_MISSING: + app_log_info("Pairing failed because of missing PIN, or authentication failed because of missing Key\r\n"); + break; + + case SL_STATUS_TIMEOUT: + app_log_info("Operation timed out\r\n"); + break; + + default: + app_log_info("Unknown error: 0x%X\r\n", evt->data.evt_sm_bonding_failed.reason); + break; + } break; - case SL_STATUS_TIMEOUT: - app_log_info("Operation timed out\r\n"); - break; + /////////////////////////////////////////////////////////////////////////// + // Add additional event handlers here as your application requires! // + /////////////////////////////////////////////////////////////////////////// + // ------------------------------- + // Default event handler. default: - app_log_info("Unknown error: 0x%X\r\n", evt->data.evt_sm_bonding_failed.reason); break; - } - break; - - /////////////////////////////////////////////////////////////////////////// - // Add additional event handlers here as your application requires! // - /////////////////////////////////////////////////////////////////////////// - - // ------------------------------- - // Default event handler. - default: - break; } } @@ -346,79 +327,56 @@ static void read_oob_data() sc = sl_iostream_getchar(sl_iostream_vcom_handle, (char *)&input); static uint8_t num = 0; - if (sc == SL_STATUS_OK) - { + if (sc == SL_STATUS_OK) { #ifdef LOCAL_ECHO - if (input != '\n') - { + if (input != '\n') { app_log("%c", input); } #endif if (((input >= ASCII_LOWER_LETTER_MIN) && (input <= ASCII_LOWER_LETTER_MAX)) || ((input >= ASCII_NUMBER_MIN) && (input <= ASCII_NUMBER_MAX)) - || ((input >= ASCII_CAPITAL_LETTER_MIN) && (input <= ASCII_CAPITAL_LETTER_MAX))) - { - app_log(" Position in the array: %d\r\n", num); - rx_oob_buf_ascii[num++] = input; + || ((input >= ASCII_CAPITAL_LETTER_MIN) && (input <= ASCII_CAPITAL_LETTER_MAX))) { + app_log(" Position in the array: %d\r\n", num); + rx_oob_buf_ascii[num++] = input; + } else if (input == ASCII_BACKSPACE) { + if (num != 0) { + num = num - 1; } - else if (input == ASCII_BACKSPACE) - { - if (num != 0) - { - num = num - 1; - } - app_log("Deleted character: %c\r\n", rx_oob_buf_ascii[num]); - if (num == 0) - { - app_log("The whole 32-byte OOB data got deleted.\r\n"); - } - app_log("Position of the next character in the array after delete: %d\r\n", num); - } - else - { - app_log("\r\n"); - app_log("Invalid character deleted: %c, keep typing the 32-byte OOB data.\r\n", input); + app_log("Deleted character: %c\r\n", rx_oob_buf_ascii[num]); + if (num == 0) { + app_log("The whole 32-byte OOB data got deleted.\r\n"); } + app_log("Position of the next character in the array after delete: %d\r\n", num); + } else { + app_log("\r\n"); + app_log("Invalid character deleted: %c, keep typing the 32-byte OOB data.\r\n", input); + } } - if (num == 64) - { - for (uint8_t x = 0; x < 64; x+=2) - { - uint8_t val = rx_oob_buf_ascii[x+1]; - if ((rx_oob_buf_ascii[x] >= ASCII_LOWER_LETTER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_LOWER_LETTER_MAX)) - { - rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_LOWER_LETTER_CONVERT; - } - else if ((rx_oob_buf_ascii[x] >= ASCII_NUMBER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_NUMBER_MAX)) - { - rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_NUMBER_CONVERT; - } - else if ((rx_oob_buf_ascii[x] >= ASCII_CAPITAL_LETTER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_CAPITAL_LETTER_MAX)) - { - rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_CAPITAL_LETTER_CONVERT; - } - if ((val >= ASCII_LOWER_LETTER_MIN) && (val <= ASCII_LOWER_LETTER_MAX)) - { - val = val - ASCII_LOWER_LETTER_CONVERT; - } - else if ((val >= ASCII_NUMBER_MIN) && (val <= ASCII_NUMBER_MAX)) - { - val = val - ASCII_NUMBER_CONVERT; - } - else if ((val >= ASCII_CAPITAL_LETTER_MIN) && (val <= ASCII_CAPITAL_LETTER_MAX)) - { - val = val - ASCII_CAPITAL_LETTER_CONVERT; - } - rx_oob_buf[x/2] = (rx_oob_buf_ascii[x] << 4) + val; + if (num == 64) { + for (uint8_t x = 0; x < 64; x += 2) { + uint8_t val = rx_oob_buf_ascii[x + 1]; + if ((rx_oob_buf_ascii[x] >= ASCII_LOWER_LETTER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_LOWER_LETTER_MAX)) { + rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_LOWER_LETTER_CONVERT; + } else if ((rx_oob_buf_ascii[x] >= ASCII_NUMBER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_NUMBER_MAX)) { + rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_NUMBER_CONVERT; + } else if ((rx_oob_buf_ascii[x] >= ASCII_CAPITAL_LETTER_MIN) && (rx_oob_buf_ascii[x] <= ASCII_CAPITAL_LETTER_MAX)) { + rx_oob_buf_ascii[x] = rx_oob_buf_ascii[x] - ASCII_CAPITAL_LETTER_CONVERT; + } + if ((val >= ASCII_LOWER_LETTER_MIN) && (val <= ASCII_LOWER_LETTER_MAX)) { + val = val - ASCII_LOWER_LETTER_CONVERT; + } else if ((val >= ASCII_NUMBER_MIN) && (val <= ASCII_NUMBER_MAX)) { + val = val - ASCII_NUMBER_CONVERT; + } else if ((val >= ASCII_CAPITAL_LETTER_MIN) && (val <= ASCII_CAPITAL_LETTER_MAX)) { + val = val - ASCII_CAPITAL_LETTER_CONVERT; } + rx_oob_buf[x / 2] = (rx_oob_buf_ascii[x] << 4) + val; + } app_log_info("16-byte OOB data: "); - for (uint8_t x = 0; x < 32; x++) - { - if(x == 16) - { - app_log_info("\r\n"); - app_log_info("16-byte confirm value: "); - } + for (uint8_t x = 0; x < 32; x++) { + if (x == 16) { + app_log_info("\r\n"); + app_log_info("16-byte confirm value: "); + } app_log("0x%02X ", rx_oob_buf[x]); } app_log_info("\r\n"); @@ -440,15 +398,13 @@ static void read_oob_data() app_assert_status(sc); /* Start general advertising and enable connections. */ sc = sl_bt_legacy_advertiser_start(advertising_set_handle, - sl_bt_advertiser_connectable_scannable); + sl_bt_advertiser_connectable_scannable); app_assert_status(sc); num = 0; _oob_state = STATE_IDLE_MODE; } - } - /***************************************************************************//** * Sleeptimer callback * @@ -457,10 +413,10 @@ static void read_oob_data() * @param[in] handle Handle of the sleeptimer instance * @param[in] data Callback data ******************************************************************************/ -void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data){ +void sleeptimer_callback(sl_sleeptimer_timer_handle_t *handle, void *data) +{ (void)handle; (void)data; sl_bt_external_signal(SIGNAL_NOTIFY_TIMER); - } diff --git a/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/readme.md b/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/readme.md index 0813ea0..0388838 100644 --- a/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/readme.md +++ b/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/readme.md @@ -56,5 +56,3 @@ SoC-empty example starts advertising by default. Therefore, if you connect a log ## Source * [app.c](src/app.c) - - diff --git a/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/src/app.c b/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/src/app.c index bb0c2af..baa52cb 100644 --- a/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/src/app.c +++ b/system_and_performance/bluetooth_tx_and_rx_activity_indicator_pins/src/app.c @@ -50,37 +50,36 @@ void enableDebugGpios(GPIO_Port_TypeDef rx_obs_port, uint8_t rx_obs_pin, GPIO_Po #ifdef _SILICON_LABS_32B_SERIES_2 - // Configure PRS Channel 0 to output RAC_RX. - PRS_SourceAsyncSignalSet(0,PRS_ASYNC_CH_CTRL_SOURCESEL_RAC,_PRS_ASYNC_CH_CTRL_SIGSEL_RACRX) ; - PRS_PinOutput(RX_OBS_PRS_CHANNEL, prsTypeAsync,rx_obs_port, rx_obs_pin); + PRS_SourceAsyncSignalSet(0, PRS_ASYNC_CH_CTRL_SOURCESEL_RAC, _PRS_ASYNC_CH_CTRL_SIGSEL_RACRX); + PRS_PinOutput(RX_OBS_PRS_CHANNEL, prsTypeAsync, rx_obs_port, rx_obs_pin); /* Configure PRS Channel 1 to output RAC_RX.*/ - PRS_SourceAsyncSignalSet(1,PRS_ASYNC_CH_CTRL_SOURCESEL_RAC,_PRS_ASYNC_CH_CTRL_SIGSEL_RACTX) ; - PRS_PinOutput(TX_OBS_PRS_CHANNEL, prsTypeAsync,tx_obs_port, tx_obs_pin); + PRS_SourceAsyncSignalSet(1, PRS_ASYNC_CH_CTRL_SOURCESEL_RAC, _PRS_ASYNC_CH_CTRL_SIGSEL_RACTX); + PRS_PinOutput(TX_OBS_PRS_CHANNEL, prsTypeAsync, tx_obs_port, tx_obs_pin); #elif defined(_SILICON_LABS_32B_SERIES_1) - if((tx_obs_port != gpioPortF)||(rx_obs_port != gpioPortF)){ - return; + if ((tx_obs_port != gpioPortF) || (rx_obs_port != gpioPortF)) { + return; } - if(rx_obs_port == gpioPortF){ - ch0_loc = rx_obs_pin; + if (rx_obs_port == gpioPortF) { + ch0_loc = rx_obs_pin; } /*set the radio RX active to channel 0*/ PRS_SourceAsyncSignalSet(RX_OBS_PRS_CHANNEL, - PRS_RAC_RX, - ((PRS_RAC_RX & _PRS_CH_CTRL_SIGSEL_MASK)>> _PRS_CH_CTRL_SIGSEL_SHIFT)); + PRS_RAC_RX, + ((PRS_RAC_RX & _PRS_CH_CTRL_SIGSEL_MASK) >> _PRS_CH_CTRL_SIGSEL_SHIFT)); /* set the location for channel0 and enable it*/ - PRS_GpioOutputLocation(RX_OBS_PRS_CHANNEL,/*ch0_loc*/rx_obs_pin); + PRS_GpioOutputLocation(RX_OBS_PRS_CHANNEL, /*ch0_loc*/ rx_obs_pin); /*set radio Tx active to channel 1. * channel 1. Locations can be 0 - 7*/ PRS_SourceAsyncSignalSet(TX_OBS_PRS_CHANNEL, - (PRS_RAC_RX & _PRS_CH_CTRL_SOURCESEL_MASK), - ((PRS_RAC_RX & _PRS_CH_CTRL_SIGSEL_MASK)>> _PRS_CH_CTRL_SIGSEL_SHIFT)); + (PRS_RAC_RX & _PRS_CH_CTRL_SOURCESEL_MASK), + ((PRS_RAC_RX & _PRS_CH_CTRL_SIGSEL_MASK) >> _PRS_CH_CTRL_SIGSEL_SHIFT)); - /*for series 1 PRS channel 1 can only be output on port F so the pin number minus 1 equates to the location*/ - PRS_GpioOutputLocation(TX_OBS_PRS_CHANNEL,tx_obs_pin-1); + /*for series 1 PRS channel 1 can only be output on port F so the pin number minus 1 equates to the location*/ + PRS_GpioOutputLocation(TX_OBS_PRS_CHANNEL, tx_obs_pin - 1); #endif } @@ -94,8 +93,7 @@ SL_WEAK void app_init(void) // This is called once during start-up. // ///////////////////////////////////////////////////////////////////////////// - enableDebugGpios(gpioPortB,0,gpioPortB,1); - + enableDebugGpios(gpioPortB, 0, gpioPortB, 1); } /**************************************************************************//** @@ -110,8 +108,6 @@ SL_WEAK void app_process_action(void) ///////////////////////////////////////////////////////////////////////////// } - - /**************************************************************************//** * Bluetooth stack event handler. * This overrides the dummy weak implementation. @@ -167,13 +163,13 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sc = sl_bt_legacy_advertiser_generate_data(advertising_set_handle, sl_bt_advertiser_general_discoverable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to generate data\n", - (int)sc); + "[E: 0x%04x] Failed to generate data\n", + (int)sc); sc = sl_bt_legacy_advertiser_start(advertising_set_handle, sl_bt_advertiser_connectable_scannable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); break; // ------------------------------- @@ -188,13 +184,13 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sc = sl_bt_legacy_advertiser_generate_data(advertising_set_handle, sl_bt_advertiser_general_discoverable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to generate data\n", - (int)sc); + "[E: 0x%04x] Failed to generate data\n", + (int)sc); sc = sl_bt_legacy_advertiser_start(advertising_set_handle, sl_bt_advertiser_connectable_scannable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); break; /////////////////////////////////////////////////////////////////////////// diff --git a/system_and_performance/setting_custom_bt_address/src/app.c b/system_and_performance/setting_custom_bt_address/src/app.c index c0d7163..ff0c1d0 100644 --- a/system_and_performance/setting_custom_bt_address/src/app.c +++ b/system_and_performance/setting_custom_bt_address/src/app.c @@ -70,7 +70,6 @@ static void sli_set_custom_bt_address(void); // Public Function Definitions // ----------------------------------------------------------------------------- - /**************************************************************************//** * Application Init. *****************************************************************************/ @@ -152,13 +151,13 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sc = sl_bt_legacy_advertiser_generate_data(advertising_set_handle, sl_bt_advertiser_general_discoverable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to generate data\n", - (int)sc); + "[E: 0x%04x] Failed to generate data\n", + (int)sc); sc = sl_bt_legacy_advertiser_start(advertising_set_handle, sl_bt_advertiser_connectable_scannable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); break; // ------------------------------- @@ -173,13 +172,13 @@ void sl_bt_on_event(sl_bt_msg_t *evt) sc = sl_bt_legacy_advertiser_generate_data(advertising_set_handle, sl_bt_advertiser_general_discoverable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to generate data\n", - (int)sc); + "[E: 0x%04x] Failed to generate data\n", + (int)sc); sc = sl_bt_legacy_advertiser_start(advertising_set_handle, sl_bt_advertiser_connectable_scannable); app_assert(sc == SL_STATUS_OK, - "[E: 0x%04x] Failed to start advertising\n", - (int)sc); + "[E: 0x%04x] Failed to start advertising\n", + (int)sc); break; /////////////////////////////////////////////////////////////////////////// @@ -193,7 +192,6 @@ void sl_bt_on_event(sl_bt_msg_t *evt) } } - /**************************************************************************//** * @brief * Reads MFG_CUSTOM_EUI_64 token and uses it to determine a custom BT address @@ -207,8 +205,8 @@ static void sli_set_custom_bt_address(void) sl_status_t status; //Adjust token byte Endianness - for(uint8_t i = 0; i < 6; i++) { - myaddr.addr[i] = mfg_token[7-i]; + for (uint8_t i = 0; i < 6; i++) { + myaddr.addr[i] = mfg_token[7 - i]; } //Get current BT address: @@ -217,16 +215,16 @@ static void sli_set_custom_bt_address(void) status = sl_bt_system_get_identity_address(&cur_addr, &address_type); if (status != SL_STATUS_OK) { - while(1); //Issue retrieving the status + while (1) ; //Issue retrieving the status } //Compare current and desired BT address, IF NOT EQUAL update and reset // reset needed to apply BT address changes in stack - if((memcmp(&cur_addr, &myaddr, 6)) != 0) { - status = sl_bt_system_set_identity_address(myaddr,0); // set new BT address + if ((memcmp(&cur_addr, &myaddr, 6)) != 0) { + status = sl_bt_system_set_identity_address(myaddr, 0); // set new BT address if (status != SL_STATUS_OK) { - while(1); //Issue setting the address + while (1) ; //Issue setting the address } sl_bt_system_reset(0); // reset diff --git a/system_and_performance/waking_from_deep_sleep_using_rfsense/inc/syncword/hw_filter_tags.yaml b/system_and_performance/waking_from_deep_sleep_using_rfsense/inc/syncword/hw_filter_tags.yaml index a9b065c..3f44e37 100644 --- a/system_and_performance/waking_from_deep_sleep_using_rfsense/inc/syncword/hw_filter_tags.yaml +++ b/system_and_performance/waking_from_deep_sleep_using_rfsense/inc/syncword/hw_filter_tags.yaml @@ -16,4 +16,3 @@ tag: allow_shared: false led: 2+ button: 2+ - diff --git a/tools/channel_sounding/cs_plotter/DataPlotter.py b/tools/channel_sounding/cs_plotter/DataPlotter.py index 362db77..967eb25 100644 --- a/tools/channel_sounding/cs_plotter/DataPlotter.py +++ b/tools/channel_sounding/cs_plotter/DataPlotter.py @@ -33,7 +33,7 @@ def __init__(self, window_size: tuple, self._cs_filtered_label = None self._velocity_label = None self._velocity_widget = None - + self._cs_data_buffer = collections.deque([0], maxlen=buffer_size) self._raw_distance_buffer = collections.deque([0], maxlen=buffer_size) self._rssi_data_buffer = collections.deque([0], maxlen=buffer_size) @@ -45,7 +45,7 @@ def __init__(self, window_size: tuple, self._timer = QtCore.QTimer() self._start_time = 0 self._previous_sample_time = 0 - + # Track whether each metric has been received self._raw_distance_ever_received = False self._rssi_distance_ever_received = False @@ -80,19 +80,19 @@ def _setup_window(self): # Create widgets for the upper portion of the main widget cs_filtered_widget, self._cs_filtered_label = create_label_widget() self._velocity_widget, self._velocity_label = create_label_widget() - + upper_upper_splitter.addWidget(cs_filtered_widget) upper_upper_splitter.addWidget(self._velocity_widget) # Hide velocity widget initially until data is received self._velocity_widget.hide() - + plot_window = pg.GraphicsLayoutWidget(title="Real-Time CS Distance Plot") self._plot = plot_window.addPlot() self._plot.setLabel("left", "Distance (m)", color="#555555", size="12pt") self._plot.setLabel("bottom", "Time (s)", color="#555555", size="12pt") self._legend = self._plot.addLegend(offset=(-1,1)) - + # Create CS distance curve (always visible) self._curve_cs_distance = self._plot.plot(pen=pg.mkPen("#3498DB", width=5), name="CS DISTANCE") # Create optional curves but don't add to plot yet @@ -115,7 +115,7 @@ def updateViews(): self._plot_velocity.linkedViewChanged(self._plot.vb, self._plot_velocity.XAxis) updateViews() self._plot.vb.sigResized.connect(updateViews) - + # Add the plot and upper split to the main splitter. Now we should have plot in the lower and values in the upper section main_splitter.addWidget(upper_upper_splitter) main_splitter.addWidget(upper_lower_splitter) @@ -124,9 +124,9 @@ def updateViews(): layout = QtWidgets.QVBoxLayout() layout.addWidget(main_splitter) central_widget.setLayout(layout) - + # Layout is complete - + def start_plot(self): # Initialize the timer so that we get periodic updates to the plot self._start_time = time.perf_counter() @@ -197,7 +197,7 @@ def _update_plot(self): self._raw_distance_buffer.append(self._raw_distance_buffer[-1]) if not rssi_distance_received: self._rssi_distance_buffer.append(self._rssi_distance_buffer[-1]) - + self._cs_filtered_label.setText( f"
Distance
{self._cs_data_buffer[-1]} m" ) @@ -216,7 +216,7 @@ def _update_plot(self): if self._velocity_ever_received: self._curve_velocity.setData(list(self._time_buffer), list(self._velocity_buffer)) - + # Adjust the Y-range for distance (left axis) if Y_LIM_M != None: y_lim = Y_LIM_M @@ -228,15 +228,14 @@ def _update_plot(self): y_lim = max(max_values) if any(max_values) else 1 self._plot.setYRange(-y_lim, y_lim) self._plot.setXRange(self._time_buffer[0], self._time_buffer[-1] + X_PADDING_S) - + # Adjust the Y-range for velocity (right axis) if self._velocity_ever_received and self._velocity_buffer: vel_max = max(abs(min(self._velocity_buffer)), abs(max(self._velocity_buffer))) vel_range = max(vel_max * 1.2, 0.1) # Add 20% padding, minimum 0.1 self._plot_velocity.setYRange(-vel_range, vel_range) - + def _handle_sigint(self, signum, frame): print("\nCtrl+C detected. Closing application...") self._timer.stop() self._app.quit() - diff --git a/tools/channel_sounding/cs_plotter/SerialReadProcess.py b/tools/channel_sounding/cs_plotter/SerialReadProcess.py index 6662f2a..87ecec0 100644 --- a/tools/channel_sounding/cs_plotter/SerialReadProcess.py +++ b/tools/channel_sounding/cs_plotter/SerialReadProcess.py @@ -59,4 +59,3 @@ def run(self): def _handle_sigint(self, signum, frame): self._ser.cancel_read() self._ser.close() - diff --git a/tools/channel_sounding/cs_plotter/cs_plotter.py b/tools/channel_sounding/cs_plotter/cs_plotter.py index 584c51e..8480a28 100644 --- a/tools/channel_sounding/cs_plotter/cs_plotter.py +++ b/tools/channel_sounding/cs_plotter/cs_plotter.py @@ -31,7 +31,7 @@ args = parser.parse_args() data_queue = mp.Manager().Queue() - + reading_process = SerialReadProcess(args.serial_port, args.baud_rate, data_queue) reading_process.start() plotter = DataPlotter(window_size=WINDOW_SIZE, refresh_period=PLOT_REFRESH_PERIOD_MS, @@ -39,4 +39,3 @@ plotter.start_plot() reading_process.join() - diff --git a/tools/channel_sounding/cs_plotter/utils.py b/tools/channel_sounding/cs_plotter/utils.py index 9cf608f..711f9bf 100644 --- a/tools/channel_sounding/cs_plotter/utils.py +++ b/tools/channel_sounding/cs_plotter/utils.py @@ -65,7 +65,7 @@ def parse_data(data): rssi_distance_match = re.search(r'(\d+)\s*mm', parts[3]) if rssi_distance_match: result['rssi_distance'] = int(rssi_distance_match.group(1)) - + # Parse speed in m/s: look for pattern like "| +0.85 m/s" or "| -0.00 m/s" speed_match = re.search(r'([+-]?\d*\.?\d+)\s*m/s', data) if speed_match: diff --git a/tools/channel_sounding/cs_step_data_parser/README.md b/tools/channel_sounding/cs_step_data_parser/README.md index 13f5122..ecc881c 100644 --- a/tools/channel_sounding/cs_step_data_parser/README.md +++ b/tools/channel_sounding/cs_step_data_parser/README.md @@ -95,4 +95,4 @@ python step_data_parser.py └── step_data/ # Role-specific classes used by the parser ├── InitiatorData.py └── ... -``` \ No newline at end of file +``` diff --git a/tools/channel_sounding/cs_step_data_parser/example_logs/example_pbr_output.json b/tools/channel_sounding/cs_step_data_parser/example_logs/example_pbr_output.json index 0c6d2d2..45f656c 100644 --- a/tools/channel_sounding/cs_step_data_parser/example_logs/example_pbr_output.json +++ b/tools/channel_sounding/cs_step_data_parser/example_logs/example_pbr_output.json @@ -114856,4 +114856,4 @@ } } ] -} \ No newline at end of file +} diff --git a/tools/channel_sounding/cs_step_data_parser/example_logs/example_rtt_output.json b/tools/channel_sounding/cs_step_data_parser/example_logs/example_rtt_output.json index 61af893..91b9129 100644 --- a/tools/channel_sounding/cs_step_data_parser/example_logs/example_rtt_output.json +++ b/tools/channel_sounding/cs_step_data_parser/example_logs/example_rtt_output.json @@ -63211,4 +63211,4 @@ } } ] -} \ No newline at end of file +} diff --git a/tools/channel_sounding/cs_step_data_parser/step_data/InitiatorData.py b/tools/channel_sounding/cs_step_data_parser/step_data/InitiatorData.py index a2061a2..fa67d97 100644 --- a/tools/channel_sounding/cs_step_data_parser/step_data/InitiatorData.py +++ b/tools/channel_sounding/cs_step_data_parser/step_data/InitiatorData.py @@ -28,12 +28,12 @@ def __init__(self, subevent_tstamp, freq_comp, ref_plevel, num_antenna_paths, st self._ras_status_byte_index = 8 self._ras_num_of_steps_index = 11 self.step_channels = [] - + def parse_step_data(self): """ Iterate over the step data, parse it, and save it in a dict. """ byte_index = 0 step_index = 1 - + # Step through the raw procedure data # step_data_len = self.step_data_len while byte_index < self.step_data_len: @@ -42,17 +42,17 @@ def parse_step_data(self): step_channel, byte_index = self._get_bytes(byte_index, 1) self.step_channels.append(step_channel) single_step_data_len, byte_index = self._get_bytes(byte_index, 1) - + step_data = { "Step_Mode": int(step_mode), "Step_Channel": int(step_channel), "Step_Data_Length": int(single_step_data_len) } - + # Parse the role and mode specific data mode_specific_data, byte_index = self._get_mode_specific_data(step_mode, byte_index) - + # Add the parsed data to the dict step_data.update(mode_specific_data) self.parsed_step_data[f"{self.role}_step_data"][f"step_{step_index}"] = step_data - step_index += 1 \ No newline at end of file + step_index += 1 diff --git a/tools/channel_sounding/cs_step_data_parser/step_data/ReflectorData.py b/tools/channel_sounding/cs_step_data_parser/step_data/ReflectorData.py index aaca6fd..a574589 100644 --- a/tools/channel_sounding/cs_step_data_parser/step_data/ReflectorData.py +++ b/tools/channel_sounding/cs_step_data_parser/step_data/ReflectorData.py @@ -28,7 +28,7 @@ def __init__(self, subevent_tstamp, freq_comp, ref_plevel, num_antenna_paths, st self._step_channels = step_channels self._ras_status_byte_index = 8 self._ras_num_of_steps_index = 11 - + def parse_step_data(self): """ Parse RAS reflector data. @@ -53,16 +53,16 @@ def parse_step_data(self): if int(step_mode) & 0x80: print(f"Reflector step {step_idx} aborted (bit 7 set).") return -1 - + mode_type = int(step_mode) & 0x03 - + if mode_type == 0: single_step_data_len = 3 elif mode_type == 1: single_step_data_len = 6 elif mode_type == 2: single_step_data_len = 4 * (self.num_antenna_paths + 1) + 1 - + if byte_index + single_step_data_len > len(self.raw_step_data_array): break @@ -74,10 +74,10 @@ def parse_step_data(self): "Step_Channel": int(step_channel), "Step_Data_Length": int(single_step_data_len) } - + mode_specific_data, byte_index = self._get_mode_specific_data(mode_type, byte_index) # Add the parsed data to the dict step_data.update(mode_specific_data) self.parsed_step_data[f"{self.role}_step_data"][f"step_{step_idx}"] = step_data - - return 0 \ No newline at end of file + + return 0 diff --git a/tools/channel_sounding/cs_step_data_parser/step_data/StepData.py b/tools/channel_sounding/cs_step_data_parser/step_data/StepData.py index 4f79f72..6c84690 100644 --- a/tools/channel_sounding/cs_step_data_parser/step_data/StepData.py +++ b/tools/channel_sounding/cs_step_data_parser/step_data/StepData.py @@ -41,7 +41,7 @@ def __init__(self, role, subevent_tstamp, freq_comp, ref_plevel, num_antenna_pat self.parsed_step_data = { f"{self.role}_step_data": {}, } - + def _get_mode_specific_data(self, step_mode, byte_index): """ Parse the step data according to the mode-specific data structures. This is described in BLE Core Spec V6.0 | Vol 4, Part E Section 7.7.65.44. """ mode_specific_data = {} @@ -51,7 +51,7 @@ def _get_mode_specific_data(self, step_mode, byte_index): packet_quality, byte_index = self._get_bytes(byte_index, 1) packet_rssi, byte_index = self._get_bytes(byte_index, 1) packet_antenna, byte_index = self._get_bytes(byte_index, 1) - + mode_specific_data["Packet_Quality"] = int(packet_quality) mode_specific_data["Packet_RSSI"] = int(np.int8(packet_rssi)) mode_specific_data["Packet_Antenna"] = int(packet_antenna) @@ -66,7 +66,7 @@ def _get_mode_specific_data(self, step_mode, byte_index): packet_rssi, byte_index = self._get_bytes(byte_index, 1) toa_tod, byte_index = self._get_bytes(byte_index, 2, True) packet_antenna, byte_index = self._get_bytes(byte_index, 1) - + mode_specific_data["Packet_Quality"] = int(packet_quality) mode_specific_data["Packet_NADM"] = int(packet_nadm) mode_specific_data["Packet_RSSI"] = int(np.int8(packet_rssi)) @@ -75,7 +75,7 @@ def _get_mode_specific_data(self, step_mode, byte_index): case 2: # PBR antenna_permutation_index, byte_index = self._get_bytes(byte_index, 1) - + # Read PCT and QI for all antenna paths and the tone extension tone_pct_all_antennas = [] tone_qi_all_antennas = [] @@ -84,16 +84,16 @@ def _get_mode_specific_data(self, step_mode, byte_index): tone_pct_all_antennas.append(int(tone_pct)) tone_qi, byte_index = self._get_bytes(byte_index, 1) tone_qi_all_antennas.append(int(tone_qi)) - + mode_specific_data["Antenna_Permutation_Index"] = int(antenna_permutation_index) mode_specific_data["Tone_PCT"] = tone_pct_all_antennas mode_specific_data["Tone_Quality_Indicator"] = tone_qi_all_antennas - + case _: pass return mode_specific_data, byte_index - + def _get_bytes(self, index, num_of_bytes, combine=False): """ Read the byte from a specific index in the procedure data. Multi-byte values can either be combined into little endian int or returned as an array. Return the data and the incremented index. """ @@ -105,7 +105,7 @@ def _get_bytes(self, index, num_of_bytes, combine=False): data = data[0] index += num_of_bytes return data, index - + # ------------- UTIL ------------- # @@ -115,5 +115,3 @@ def combine_bytes(byte_array): for i in range(len(byte_array)): combined = (combined << 8) | byte_array[-(i+1)] # Start from the back as the combined byte should be in little-endian return combined - - \ No newline at end of file diff --git a/tools/channel_sounding/cs_step_data_parser/step_data_parser.py b/tools/channel_sounding/cs_step_data_parser/step_data_parser.py index dd638de..fa95ec3 100644 --- a/tools/channel_sounding/cs_step_data_parser/step_data_parser.py +++ b/tools/channel_sounding/cs_step_data_parser/step_data_parser.py @@ -55,7 +55,7 @@ def extract_bytes_literal(line, key, ras=False): """ # Simple HCI-style pattern: pattern = re.compile(r"""\b(?:data|value)=b(['"])((?:\\.|(?!\1).)*)\1""") - + m = re.search(pattern, line) if not m: return b"" @@ -91,8 +91,8 @@ def parse_raw_log(input_file): if "bt_evt_gatt_characteristic" in line and RAS_CHAR_HANDLE == None: uuid = extract_field(r"uuid=(b'.*?')", line, int) if uuid.lower() == RANGING_DATA_UUID: - RAS_CHAR_HANDLE = extract_field(r"characteristic=(\d+)", line, int) - + RAS_CHAR_HANDLE = extract_field(r"characteristic=(\d+)", line, int) + # Global metadata from bt_evt_cs_procedure_enable_complete if "bt_evt_cs_procedure_enable_complete" in line: global_subevent_len = extract_field(r"subevent_len=(\d+)", line, int) @@ -105,7 +105,7 @@ def parse_raw_log(input_file): # Check if the new procedure starts before the reflector data is fully parsed if current_proc["reflector_finished"] == False: ras_intercepted = True - + current_proc = { "initiator_chunks": [], "reflector_chunks": [], @@ -136,14 +136,14 @@ def parse_raw_log(input_file): current_proc["initiator_finished"] = True continue - + # Continuation of initiator data if "bt_evt_cs_result_continue(" in line and current_proc: abort_reason = extract_field(r"abort_reason=(\d+)", line, int) - + if current_proc and abort_reason != 0: current_proc["initiator_metadata"]["abort_reason"] = abort_reason - + pds = extract_field(r"procedure_done_status=(\d+)", line, int) chunk = extract_bytes_literal(line, "data") if chunk: @@ -182,11 +182,11 @@ def build_json(procedures, subevent_len, subevent_interval, output_file): out = {"cs_procedures": []} for proc_index, proc in enumerate(procedures): - abort_reason = proc["initiator_metadata"].get("abort_reason", 0) + abort_reason = proc["initiator_metadata"].get("abort_reason", 0) if abort_reason != 0: print(f"Procedure {proc_index} aborted at initiator with reason {abort_reason}. Skipping to next procedure.") continue - + # Parse Initiator data initiator_raw = b"".join(proc["initiator_chunks"]) num_paths = proc["initiator_metadata"].get("num_paths", 0) @@ -216,7 +216,7 @@ def build_json(procedures, subevent_len, subevent_interval, output_file): step_channels=initiator.step_channels ) rslt = reflector.parse_step_data() - + if rslt != 0: print(f"Procedure {proc_index} aborted at reflector. Skipping to next procedure.") continue @@ -240,10 +240,10 @@ def build_json(procedures, subevent_len, subevent_interval, output_file): ) procedure_count += 1 - + with open(output_file, "w") as f: json.dump(out, f, indent=2) - + return procedure_count if __name__ == "__main__":