diff --git a/sld131-bluetooth-getting-started-demos-examples/index.md b/sld131-bluetooth-getting-started-demos-examples/index.md index fcfad21..f595277 100644 --- a/sld131-bluetooth-getting-started-demos-examples/index.md +++ b/sld131-bluetooth-getting-started-demos-examples/index.md @@ -1,115 +1,121 @@ -# More Demos and Examples - -Because starting application development from scratch is difficult, the Bluetooth SDK comes with a number of built-in demos and examples covering the most frequent use cases, as shown in the following figure. Demos are pre-built application images that you can run immediately. Software examples (example projects) can be modified before building the application image. See [Getting Started with Application Development](/bluetooth/{build-docspace-version}/bluetooth-getting-started-app-dev) for more information about configuring and customizing examples. - -Demos with the same name as examples are built from their respective example. Click **View Project Documentation** to see additional information about some examples. This is also displayed on a **readme** tab when you create a project based on the example. - -Use the **Demos** and **Example Projects** switches to filter on only examples or only demos. Demos are also noted by the blue Demo tag in the upper left of the card. The Solution Examples are primarily for use with multiprotocol applications. - -![Filtering examples and demos](resources/sld131-image15.png?darkModeUrl=resources/sld131-image15.png) - ->**Note**: The demos and examples you see are determined by the part selected. If you are using a custom solution with more than one part, click on the part you are working with to see only the items applicable to that part. - -## Demo and Example Descriptions - -The following examples are provided as part of the Bluetooth SDK. Examples with (\*) in their names have a matching pre-built demo. - -### Silicon Labs Gecko Bootloader Examples - -See *UG266: Silicon Labs Gecko Bootloader User’s Guide for GSDK 3.2 and Lower*, [Silicon Labs Gecko Bootloader User's Guide for GSDK 4.0 and Higher (series 1 and 2 devices)](/bluetooth/{build-docspace-version}/bootloader-user-guide-gsdk-4), or [Silicon Labs Gecko Bootloader User’s Guide for Series 3 and Higher](/bluetooth/{build-docspace-version}/bootloader-user-guide-series3-and-higher), and [Using the Gecko Bootloader with Silicon Labs Bluetooth Applications](/bluetooth/{build-docspace-version}/using-gecko-bootloader-with-bluetooth-apps). - -### Bluetooth Examples - -- **Bluetooth – RCP(\*)**: Radio Co-Processor (RCP) target application. Runs the Bluetooth Controller (i.e. the Link Layer only) and provides access to it using the standard HCI (Host-Controller Interface) over a UART connection. - -- **Bluetooth – RCP CPC(\*)**: Radio Co-Processor (RCP) target application. Runs the Bluetooth Controller (i.e. the Link Layer only) and provides access to it using the standard HCI (Host-Controller Interface) over CPC (Co-Processor Communication) protocol through a UART connection. - -- **Bluetooth – NCP(\*)**: Network Co-Processor (NCP) target application. Runs the Bluetooth stack dynamically and provides access to it via the Bluetooth API (BGAPI) using a UART connection. NCP mode makes it possible to run your application on a host controller or PC. - -- **Bluetooth – NCP Host**: Reference implementation of an NCP (Network Co-Processor) host, which typically runs on a central MCU without radio. It can connect to an NCP target via UART to access the Bluetooth stack of the target and to control it using BGAPI. - -- **Bluetooth AoA – NCP Locator(\*)**: Network Co-Processor (NCP) target application extended with CTE Receiver support. It enables Angle of Arrival (AoA) calculation. Use this application with Direction Finding host examples. - -- **Bluetooth AoA –Asset Tag(\*)**: Demonstrates a CTE (Constant Tone Extension) transmitter that can be used as an asset tag in a Direction Finding setup estimating Angle of Arrival (AoA). - -- **Bluetooth – SoC Application OTA DFU**: A minimal project structure that serves as a starting point for custom Bluetooth applications providing Over-the-Air device firmware update in the user application runtime. - -- **Bluetooth – SoC Application OTA DFU FreeRTOS**: Demonstrates the integration of FreeRTOS into Bluetooth applications. RTOS is added to the *Bluetooth - SoC Application OTA DFU* sample application that realizes over-the-air device firmware updates in user application scope. - -- **Bluetooth – SoC Application OTA DFU MicriumOS**: Demonstrates the integration of MicriumOS into Bluetooth applications. RTOS is added to the *Bluetooth - SoC Application OTA DFU* sample application that realizes over-the-air device firmware updates in user application scope. - -- **Bluetooth – SoC Blinky(\*)**: The classic blinky example using Bluetooth communication. Demonstrates a simple two-way data exchange over GATT. This can be tested with the Simplicity Connect mobile app. - -- **Bluetooth – SoC Certificate-Based Authentication and Pairing**: Demonstrates Certificate-Based Authentication and Pairing over Bluetooth LE. - -- **Bluetooth – SoC CSR Generator**: Certificate-generating firmware example. Software generates the device EC key pair, the signing request for the device certificate, and other related data. The generated data can be read out by the Central Authority. See *Bluetooth – SoC Certificate Based Authentication and Pairing.* - -- **Bluetooth – SoC DTM**: This example implements the direct test mode (DTM) application for radio testing. DTM commands can be called via UART. See [RF PHY Layer Evaluation in Bluetooth SDK v3.x and Higher](/bluetooth/{build-docspace-version}/bt-rf-phy-evaluation-using-dtm-sdk-v3x) for more information. - -- **Bluetooth – SoC Empty**: A minimal project structure that serves as a starting point for custom Bluetooth applications. The application starts advertising after boot and restarts advertising after a connection is closed. - -- **Bluetooth – SoC Interoperability Test(\*)**: A test procedure containing several test cases for Bluetooth Low Energy communication. This sample app (also provided as a demo) is meant to be used with the Simplicity Connect mobile app, through the "Interoperability Test" tile on the Develop view of the app. - -- **Bluetooth – SoC Thermometer(\*)**: Implements a GATT Server with the Health Thermometer Profile, which enables a Client device to connect and get temperature data. Temperature is read from the Si7021 digital relative humidity and temperature sensor of the WSTK or of the Thunderboard. - -- **Bluetooth – SoC Thermometer Client**: Implements a GATT Client that discovers and connects with up to four Bluetooth LE devices advertising themselves as Thermometer Servers. It displays the discovery process and the temperature values received via UART. - - >**Note**: Some radio boards will exhibit random pixels in the display when this example is running because they have a shared pin for sensor- and display-enabled signals. - -- **Bluetooth – SoC Thermometer FreeRTOS**: Demonstrates the integration of FreeRTOS into Bluetooth applications. RTOS is added to the Bluetooth - SoC Thermometer sample app. - -- **Bluetooth – SoC Thermometer Micrium OS**: Demonstrates the integration of Micrium RTOS into Bluetooth applications. RTOS is added to the Bluetooth - SoC Thermometer sample app. - -- **Bluetooth – SoC Throughput(\*)**: Tests the throughput capabilities of the device and can be used to measure throughput between two EFR32 devices, as well as between a device and a smartphone using the Simplicity Connect mobile app, through the Throughput demo tile. - -- **Bluetooth – SoC Voice(\*)**: Voice over Bluetooth Low Energy sample application. It is supported by Thunderboard Sense 2 and Thunderboard EFR32BG22 boards and demonstrates how to send voice data over GATT, which is acquired from the on-board microphones. - -- **Bluetooth – SoC iBeacon(\*)**: Sends non-connectable advertisements in iBeacon format. The iBeacon Service gives Bluetooth accessories a simple and convenient way to send iBeacons to smartphones. This example can be tested together with the Simplicity Connect mobile app. - -- **Bluetooth – SoC Thunderboard Sense 2(\*),** and **Thunderboard EFR32BG22(\*)**: Demonstrate the features of the Thunderboard Kit. These can be tested with the Simplicity Connect mobile app. - -## Dynamic Multiprotocol Examples - -See [Dynamic Multiprotocol Development with Bluetooth and Proprietary Protocols on RAIL](/bluetooth/{build-docspace-version}/multiprotocol-dynamic-ble-proprietary-on-rail) for more information. - -- **Bluetooth RAIL DMP – SoC Empty FreeRTOS**: A minimal project structure, used as a starting point for custom Bluetooth + Proprietary DMP (Dynamic Multiprotocol) applications. It runs on top of FreeRTOS and multiprotocol RAIL. - -- **Bluetooth RAIL DMP – SoC Empty Micrium OS**: A minimal project structure, used as a starting point for custom Bluetooth + Proprietary DMP (Dynamic Multiprotocol) applications. It runs on top of Micrium OS and multiprotocol RAIL. - -- **Bluetooth RAIL DMP – SoC Empty Standard FreeRTOS**: A minimal project structure, used as a starting point for custom Bluetooth + Standard DMP (Dynamic Multiprotocol) applications. It runs on top of FreeRTOS and multiprotocol RAIL utilizing IEE802.15.4 standard protocol. - -- **Bluetooth RAIL DMP – SoC Empty Standard Micrium OS**: A minimal project structure, used as a starting point for custom Bluetooth + Standard DMP (Dynamic Multiprotocol) applications. It runs on top of Micrium OS and multiprotocol RAIL, utilizing IEE802.15.4 standard protocol. - -- **Bluetooth RAIL DMP – SoC Light RAIL FreeRTOS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a Proprietary protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** sample app. - -- **Bluetooth RAIL DMP – SoC Light RAIL Micrium OS**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a Proprietary protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** sample app. - -- **Bluetooth RAIL DMP – SoC Light Standard FreeRTOS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a standard protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** Standards sample app. - -- **Bluetooth RAIL DMP – SoC Light Standard Micrium OS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a standard protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch Standards** sample app. - -### NCP Host Examples - -NCP host examples are located in \\app\bluetooth\example_host. - -- **bt\_host\_empty:** Minimal host-side project structure, used as a starting point for NCP host applications. Use it with the **Bluetooth – NCP** target application flashed to the radio board. - -- **bt\_host\_ota\_dfu:** Demonstrates how to perform an OTA DFU on a Silicon Labs Bluetooth Device. It requires a WSTK with a radio board flashed with NCP firmware to be used as the GATT client that performs the OTA. - -- **bt\_host\_uart\_dfu:** Demonstrates how to perform a UART DFU on a Silicon Labs Bluetooth Device running NCP firmware. - -- **bt\_host\_voice:** On a WSTK programmed with NCP firmware, it to connects to the **Bluetooth – SoC Voice** example, sets the correct configuration on it, receives audio via Bluetooth, and stores audio data into a file. - -- **bt\_aoa\_host\_locator:** A locator host sample app that works together with a **Bluetooth AoA – NCP Locator** target app. It receives IQ samples from the target and estimates the Angle of Arrival (AoA). For more information see [Application Development with Silicon Labs’ RTL Library](https://docs.silabs.com/rtl-lib/latest/direction-finding-solution-guide/). - -- **bt\_host\_positioning:** Connects to multiple **bt\_aoa\_host\_locator** sample apps (via MQTT) and estimates a position from Angles of Arrival (AoA). For more information, see *QS175: Application Development with Silicon Labs’ RTL Library.* - -- **bt\_host\_positioning\_gui:** Connects to the **bt\_host\_positioning** sample app (via MQTT), reads out the position estimations and displays the tags and locators on a 3D GUI. This sample app is python based. For more information, see [Application Development with Silicon Labs’ RTL Library](https://docs.silabs.com/rtl-lib/latest/direction-finding-solution-guide/). - -- **bt\_host\_throughput:** Tests the throughput capabilities of the device in NCP mode and can be used to measure throughput between two devices as well as between a device and a smartphone. - -- **bt\_host\_cpc\_hci\_bridge:** A background application to be run when HCI interface is exposed via CPC. This application retrieves the HCI commands/events from the CPC messages and forwards them toward the Bluetooth host running on the PC. Similarly, it forwards the HCI commands from the host toward the target over CPC. - -## Code Examples - -Additional examples are provided in repositories on GitHub. See [Code Examples](/bluetooth/{build-docspace-version}/bluetooth-examples-overview) for more information. +# More Demos and Examples + +Because starting application development from scratch is difficult, the Bluetooth SDK comes with a number of built-in demos and examples covering the most frequent use cases, as shown in the following figure. Demos are pre-built application images that you can run immediately. Software examples (example projects) can be modified before building the application image. See [Getting Started with Application Development](/bluetooth/{build-docspace-version}/bluetooth-getting-started-app-dev) for more information about configuring and customizing examples. + +Demos with the same name as examples are built from their respective example. Click **View Project Documentation** to see additional information about some examples. This is also displayed on a **readme** tab when you create a project based on the example. + +Use the **Demos** and **Example Projects** switches to filter on only examples or only demos. Demos are also noted by the blue Demo tag in the upper left of the card. The Solution Examples are primarily for use with multiprotocol applications. + +![Filtering examples and demos](resources/sld131-image15.png?darkModeUrl=resources/sld131-image15.png) + +>**Note**: The demos and examples you see are determined by the part selected. If you are using a custom solution with more than one part, click on the part you are working with to see only the items applicable to that part. + +## Demo and Example Descriptions + +The following examples are provided as part of the Bluetooth SDK. Examples with (\*) in their names have a matching pre-built demo. + +### Silicon Labs Gecko Bootloader Examples + +See *UG266: Silicon Labs Gecko Bootloader User’s Guide for GSDK 3.2 and Lower*, [Silicon Labs Gecko Bootloader User's Guide for GSDK 4.0 and Higher (series 1 and 2 devices)](/bluetooth/{build-docspace-version}/bootloader-user-guide-gsdk-4), or [Silicon Labs Gecko Bootloader User’s Guide for Series 3 and Higher](/bluetooth/{build-docspace-version}/bootloader-user-guide-series3-and-higher), and [Using the Gecko Bootloader with Silicon Labs Bluetooth Applications](/bluetooth/{build-docspace-version}/using-gecko-bootloader-with-bluetooth-apps). + +### Bluetooth Examples + +- **Bluetooth – RCP(\*)**: Radio Co-Processor (RCP) target application. Runs the Bluetooth Controller (i.e. the Link Layer only) and provides access to it using the standard HCI (Host-Controller Interface) over a UART connection. + +- **Bluetooth – RCP CPC(\*)**: Radio Co-Processor (RCP) target application. Runs the Bluetooth Controller (i.e. the Link Layer only) and provides access to it using the standard HCI (Host-Controller Interface) over CPC (Co-Processor Communication) protocol through a UART connection. + +- **Bluetooth – NCP(\*)**: Network Co-Processor (NCP) target application. Runs the Bluetooth stack dynamically and provides access to it via the Bluetooth API (BGAPI) using a UART connection. NCP mode makes it possible to run your application on a host controller or PC. + +- **Bluetooth – NCP Host**: Reference implementation of an NCP (Network Co-Processor) host, which typically runs on a central MCU without radio. It can connect to an NCP target via UART to access the Bluetooth stack of the target and to control it using BGAPI. + +- **Bluetooth AoA – NCP Locator(\*)**: Network Co-Processor (NCP) target application extended with CTE Receiver support. It enables Angle of Arrival (AoA) calculation. Use this application with Direction Finding host examples. + +- **Bluetooth AoA –Asset Tag(\*)**: Demonstrates a CTE (Constant Tone Extension) transmitter that can be used as an asset tag in a Direction Finding setup estimating Angle of Arrival (AoA). + +- **Bluetooth – SoC Application OTA DFU**: A minimal project structure that serves as a starting point for custom Bluetooth applications providing Over-the-Air device firmware update in the user application runtime. + +- **Bluetooth – SoC Application OTA DFU FreeRTOS**: Demonstrates the integration of FreeRTOS into Bluetooth applications. RTOS is added to the *Bluetooth - SoC Application OTA DFU* sample application that realizes over-the-air device firmware updates in user application scope. + +- **Bluetooth – SoC Application OTA DFU MicriumOS**: Demonstrates the integration of MicriumOS into Bluetooth applications. RTOS is added to the *Bluetooth - SoC Application OTA DFU* sample application that realizes over-the-air device firmware updates in user application scope. + +- **Bluetooth – SoC Blinky(\*)**: The classic blinky example using Bluetooth communication. Demonstrates a simple two-way data exchange over GATT. This can be tested with the Simplicity Connect mobile app. + +- **Bluetooth – SoC Certificate-Based Authentication and Pairing**: Demonstrates Certificate-Based Authentication and Pairing over Bluetooth LE. + +- **Bluetooth – SoC CSR Generator**: Certificate-generating firmware example. Software generates the device EC key pair, the signing request for the device certificate, and other related data. The generated data can be read out by the Central Authority. See *Bluetooth – SoC Certificate Based Authentication and Pairing.* + +- **Bluetooth – SoC DTM**: This example implements the direct test mode (DTM) application for radio testing. DTM commands can be called via UART. See [RF PHY Layer Evaluation in Bluetooth SDK v3.x and Higher](/bluetooth/{build-docspace-version}/bt-rf-phy-evaluation-using-dtm-sdk-v3x) for more information. + +- **Bluetooth – SoC Empty**: A minimal project structure that serves as a starting point for custom Bluetooth applications. The application starts advertising after boot and restarts advertising after a connection is closed. + +- **Bluetooth – SoC Interoperability Test(\*)**: A test procedure containing several test cases for Bluetooth Low Energy communication. This sample app (also provided as a demo) is meant to be used with the Simplicity Connect mobile app, through the "Interoperability Test" tile on the Develop view of the app. + +- **Bluetooth – SoC Thermometer(\*)**: Implements a GATT Server with the Health Thermometer Profile, which enables a Client device to connect and get temperature data. Temperature is read from the Si7021 digital relative humidity and temperature sensor of the WSTK or of the Thunderboard. + +- **Bluetooth – SoC Thermometer Client**: Implements a GATT Client that discovers and connects with up to four Bluetooth LE devices advertising themselves as Thermometer Servers. It displays the discovery process and the temperature values received via UART. + + >**Note**: Some radio boards will exhibit random pixels in the display when this example is running because they have a shared pin for sensor- and display-enabled signals. + +- **Bluetooth – SoC Thermometer FreeRTOS**: Demonstrates the integration of FreeRTOS into Bluetooth applications. RTOS is added to the Bluetooth - SoC Thermometer sample app. + +- **Bluetooth – SoC Thermometer Micrium OS**: Demonstrates the integration of Micrium RTOS into Bluetooth applications. RTOS is added to the Bluetooth - SoC Thermometer sample app. + +- **Bluetooth – SoC Throughput(\*)**: Tests the throughput capabilities of the device and can be used to measure throughput between two EFR32 devices, as well as between a device and a smartphone using the Simplicity Connect mobile app, through the Throughput demo tile. + +- **Bluetooth – SoC Voice(\*)**: Voice over Bluetooth Low Energy sample application. It is supported by Thunderboard Sense 2 and Thunderboard EFR32BG22 boards and demonstrates how to send voice data over GATT, which is acquired from the on-board microphones. + +- **Bluetooth – SoC iBeacon(\*)**: Sends non-connectable advertisements in iBeacon format. The iBeacon Service gives Bluetooth accessories a simple and convenient way to send iBeacons to smartphones. This example can be tested together with the Simplicity Connect mobile app. + +- **Bluetooth – SoC Thunderboard Sense 2(\*),** and **Thunderboard EFR32BG22(\*)**: Demonstrate the features of the Thunderboard Kit. These can be tested with the Simplicity Connect mobile app. + +## Dynamic Multiprotocol Examples + +See [Dynamic Multiprotocol Development with Bluetooth and Proprietary Protocols on RAIL](/bluetooth/{build-docspace-version}/multiprotocol-dynamic-ble-proprietary-on-rail) for more information. + +- **Bluetooth RAIL DMP – SoC Empty FreeRTOS**: A minimal project structure, used as a starting point for custom Bluetooth + Proprietary DMP (Dynamic Multiprotocol) applications. It runs on top of FreeRTOS and multiprotocol RAIL. + +- **Bluetooth RAIL DMP – SoC Empty Micrium OS**: A minimal project structure, used as a starting point for custom Bluetooth + Proprietary DMP (Dynamic Multiprotocol) applications. It runs on top of Micrium OS and multiprotocol RAIL. + +- **Bluetooth RAIL DMP – SoC Empty Standard FreeRTOS**: A minimal project structure, used as a starting point for custom Bluetooth + Standard DMP (Dynamic Multiprotocol) applications. It runs on top of FreeRTOS and multiprotocol RAIL utilizing IEE802.15.4 standard protocol. + +- **Bluetooth RAIL DMP – SoC Empty Standard Micrium OS**: A minimal project structure, used as a starting point for custom Bluetooth + Standard DMP (Dynamic Multiprotocol) applications. It runs on top of Micrium OS and multiprotocol RAIL, utilizing IEE802.15.4 standard protocol. + +- **Bluetooth RAIL DMP – SoC Light RAIL FreeRTOS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a Proprietary protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** sample app. + +- **Bluetooth RAIL DMP – SoC Light RAIL Micrium OS**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a Proprietary protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** sample app. + +- **Bluetooth RAIL DMP – SoC Light Standard FreeRTOS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a standard protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch** Standards sample app. + +- **Bluetooth RAIL DMP – SoC Light Standard Micrium OS(\*)**: A Dynamic Multiprotocol reference application demonstrating a light bulb that can be switched both via Bluetooth and via a standard protocol. Can be tested with the Simplicity Connect mobile app and the **RAIL – SoC Switch Standards** sample app. + +### NCP Host Examples + +NCP host examples are located in \\bluetooth_le_app\example_host. + +- **bt\_aoa\_host\_locator:** A locator host sample app that works together with a **Bluetooth AoA – NCP Locator** target app. It receives IQ samples from the target and estimates the Angle of Arrival (AoA). For more information see [Application Development with Silicon Labs’ RTL Library](https://docs.silabs.com/rtl-lib/latest/direction-finding-solution-guide/). + +- **bt\_cs\_host:** This is the host application for the Channel Sounding (CS) NCP target application. + +- **bt\_host\_cpc\_hci\_bridge:** A background application to be run when HCI interface is exposed via CPC. This application retrieves the HCI commands/events from the CPC messages and forwards them toward the Bluetooth host running on the PC. Similarly, it forwards the HCI commands from the host toward the target over CPC. + +- **bt\_host\_empty:** Minimal host-side project structure, used as a starting point for NCP host applications. Use it with the **Bluetooth – NCP** target application flashed to the radio board. + +- **bt\_host\_esl\_ap:** This Python example implements the functionality of an Access Point as specified by the Bluetooth Electronic Shelf Label Profile specification using an NCP ESL AP target. + +- **bt\_host\_ncp\_test:** This Network Co-Processor (NCP) host application serves 2 purposes. It demonstrates (1) how to use user NCP commands and (2) how to implement a simple application to test NCP performance using the default user commands. + +- **bt\_host\_ota\_dfu:** Demonstrates how to perform an OTA DFU on a Silicon Labs Bluetooth Device. It requires a WSTK with a radio board flashed with NCP firmware to be used as the GATT client that performs the OTA. + +- **bt\_host\_positioning:** Connects to multiple **bt\_aoa\_host\_locator** sample apps (via MQTT) and estimates a position from Angles of Arrival (AoA). For more information, see *QS175: Application Development with Silicon Labs’ RTL Library.* + +- **bt\_host\_throughput:** Tests the throughput capabilities of the device in NCP mode and can be used to measure throughput between two devices as well as between a device and a smartphone. + +- **bt\_host\_uart\_dfu:** Demonstrates how to perform a UART DFU on a Silicon Labs Bluetooth Device running NCP firmware. + +- **bt\_host\_voice:** On a WSTK programmed with NCP firmware, it to connects to the **Bluetooth – SoC Voice** example, sets the correct configuration on it, receives audio via Bluetooth, and stores audio data into a file. + +- **bt\_host\_positioning\_gui:** Connects to the **bt\_host\_positioning** sample app (via MQTT), reads out the position estimations and displays the tags and locators on a 3D GUI. This sample app is python based. For more information, see [Application Development with Silicon Labs’ RTL Library](https://docs.silabs.com/rtl-lib/latest/direction-finding-solution-guide/). + +## Code Examples + +Additional examples are provided in repositories on GitHub. See [Code Examples](/bluetooth/{build-docspace-version}/bluetooth-examples-overview) for more information. diff --git a/sld596-bluetooth-network-coprocessor-mode/03-ncp-host-development.md b/sld596-bluetooth-network-coprocessor-mode/03-ncp-host-development.md index 1b0f676..a5df451 100644 --- a/sld596-bluetooth-network-coprocessor-mode/03-ncp-host-development.md +++ b/sld596-bluetooth-network-coprocessor-mode/03-ncp-host-development.md @@ -1,223 +1,216 @@ -# NCP Host Development - -This section introduces the Bluetooth NCP Commander tool, which can be used to send BGAPI commands from a graphical user interface. It then walks through the process of building the PC Host examples provided in the Bluetooth SDK. And finally, it describes using Python for host side development. - -## Bluetooth NCP Commander - -Bluetooth NCP Commander is an easy-to-use tool that can be used for testing different stack features, by sending BGAPI commands to the target device. The tool has two versions: a version built into Simplicity Studio, which makes it easy to connect to your development kit and start testing, and a standalone version to test a board in an environment where Simplicity Studio cannot be installed, or if you want to test a custom board that can be accessed on UART interface, but not through a Simplicity Studio supported debug adapter using VCOM. - -### Built-in Version - -1. To open the built-in Bluetooth NCP Commander, select the target board in the **Debug Adapters** view, and check that the preferred SDK is set to **Gecko SDK Suite vn.n.n**. Select the **Compatible Tools** tab, and click **Launch** next to Bluetooth NCP Commander. - - ![Compatible Tools](resources/an1259-v14-tools-tab.png) - - Alternatively, you can open the built-in Bluetooth NCP Commander from the **Tools** menu. - - ![Tools dialog](resources/an1259-v14-tools-menu.png) - -2. Select the target device, and click **Connect**. - - ![Connection Manager](resources/an1259-v14-connection-manager.png) - -### Standalone Version - -1. To open the standalone tool, navigate to *C:\SiliconLabs\SimplicityStudio\v5\developer\adapter_packs\ncp_commander*, and start NcpCommander.exe. - -2. In the standalone tool, provide the UART interface settings, and then select the COM port on which the device can be accessed. - - ![Serial Connection Manager](resources/an1259-v14-serial-connection-manager.png) - -### Bluetooth NCP Commander Functions - -The following procedure covers most NCP Commander functions. - -1. After the device is connected, you should see the result of the ``sl_bt_system_get_identity_address`` command displayed in green: - - ![NCP Commander](resources/an1259-v14-ncp-commander-open.png) - -2. Unlike SoC examples, the NCP demo does not have a built-in GATT database. It expects the host to build the GATT database using the dynamic GATT database BGAPI commands. To create a basic GATT database, select the Local GATT menu, and click **Create Basic GATT**. This triggers a series of BGAPI commands that will build a basic database. You can modify this GATT database as you want. You can also change the device name here by changing the value of the Device Name characteristic. - - ![Create Local GATT](resources/an1259-v14-ncp-commander-create-local-gatt.png) - -3. To extend the database with new services, characteristics, and descriptors, click **Add Service**. You can then add new characteristics for the service. - - ![Commander add service](resources/an1259-v14-ncp-commander-add-service.png) - -4. To read out the GATT database from the device, click **Local GATT Database**. The smart console also supports API calls for creating entries. - - ![Commander API method](resources/an1259-v14-ncp-commander-api-method.png) - -5. To start advertising your device so that other devices can discover it and connect to it, in the Advertise menu click '**+**' (Create Set) to create an advertiser set. - - ![Commander start advertising](resources/an1259-v14-ncp-commander-start-advertising.png) - -6. To populate the advertisement payload with the device name, set the Advertising Data Type to **Generated data** and click **Start** to start advertising. - - ![Advertising Data Type](resources/an1259-v14-ncp-commander-start-advertising-2.png) - -7. When advertising, the NCP target example accepts Bluetooth connections. If you connect to the mainboard or with another central device (for example with your phone), you can see the events and commands on the log. - - ![Commander log view](resources/an1259-v14-ncp-commander-log-view.png) - -8. You can also issue commands manually. For example, you can issue the 'system hello' command at any time to verify that communication between the host and the device is working. The Smart Console provides auto-completion and documentation for the possible commands. To open/close the documentation, click the arrows at the right side of the input field. - - ![Commander issue commands](resources/an1259-v14-ncp-commander-issue-commands.png) - -9. To create periodic advertisement sets, select **Advertisement mode: Periodic**. To set the content of the packet, use the **Edit** option next to "Periodic Advertising Packets". - - ![Commander periodic advertising](resources/an1259-v14-ncp-commander-periodic-advertising.png) - - This opens a new dialog where you can edit the contents of the package. Click **Set Data** after the data is edited. - - ![Commander edit packet](resources/an1259-v14-ncp-commander-edit-packet.png) - -10. It is also possible to synchronize to periodic advertisement trains. To do this, click **Synchronization** on the left menu, input the Advertiser Address and advertising Set identifier, and click **Open Synchronization**. - - ![Commander synchronize streams](resources/an1259-v14-ncp-commander-synchronize-streams.png) - -11. NCP Commander also provides a simple scripting feature. You can create or import an existing script with the controls on the top right corner. You can use any BGAPI commands in the script, but there are no additional features, such as branching or error handling. - - ![Commander scripting](resources/an1259-v14-ncp-commander-scripting.png) - - You can export the commands sent in the Smart console with the **Export** control. This saves the sent commands to a file that can be imported back as a script. You can also export the raw script using the **Export** button under the editor. - - ![Commander export messages](resources/an1259-v14-ncp-commander-export-messages.png) - -### Host Provisioner with Bluetooth NCP Commander - -Bluetooth NCP Commander also supports Bluetooth mesh features. You can issue Bluetooth mesh commands manually in the command box of Smart Console or use the host provisioner feature from the left menu. You can use the feature to provision and configure mesh nodes and to manage mesh networks rather than using a Bluetooth Mesh mobile application. - -To use the Bluetooth Mesh features, create, build, and flash the device with an NCP example supporting Mesh features. Otherwise, the provisioner initialization attempt returns SL_STATUS_NOT_SUPPORTED (0x000f). - -![NCP example supporting Mesh features](resources/an1259-v14-mesh-example.png) - -In **Settings**, if the **Reset Mesh Node before Initializing as Provisioner** option is enabled, the host provisioner does a factory reset (the **node_reset** command) on the NCP target device before initializing the node. Clicking **Clear Data** next to **Remove all locally saved mesh data** removes the network and application keys that were configured during initialization. - -![mesh initialization](resources/an1259-v14-ncp-commander-mesh-initialization.png) - -1. To start using the host provisioner, select either **Provision** or **Networks & Nodes** on the left menu, and click **Initialize as Provisioner**. - - ![Initialize as Provisioner](resources/an1259-v14-ncp-commander-mesh-start-provisioning.png) - -2. To provision devices, select **Provision** on the left menu and click **Start Scan** in the right panel. The devices that are transmitting unprovisioned beacons are shown in the **Discovered Devices** section. If you do not have a network from a previous configuration or have reset the provisioner node, you must create a new network with **Create New Network**. - - ![mesh provision](resources/an1259-v14-ncp-commander-mesh-provision.png) - -3. Enter the name of the new network and click **Confirm**. - - ![create new network](resources/an1259-v14-ncp-commander-mesh-create-network.png) - -4. Click **Provision** next to the device you want to provision. - - ![provision](resources/an1259-v14-ncp-commander-mesh-provision-device.png) - -5. Before configuring devices, you may need to create application keys and groups. Application keys, groups, and other network settings can be managed in the **Settings** tab of the **Networks & Nodes** menu item. To create an application key, click **Create App Key**, name the key, and click **Confirm**. You can create as many application keys as you need. If you have created any application keys before, you can click **Get App Keys** to retrieve them. To create a group, click **Add Group**, name the group, and click **Confirm**. You can create as many groups as you need. - - ![create keys groups](resources/an1259-v14-ncp-commander-mesh-create-keys-groups.png) - -6. In the same tab, you can induce a full network-wide key refresh or exclude nodes. - - ![other settings](resources/an1259-v14-ncp-commander-mesh-other-settings.png) - -7. To configure a provisioned device, select **Networks & Nodes** on the left menu. The devices you provisioned are shown in the **Nodes (Provisioned Devices)** section of the **Settings** tab. Click **Configure** and a **Mesh Node** tab opens in which you can configure the device. - - ![configure provisioned device](resources/an1259-v14-ncp-commander-mesh-configure-provisioned-device.png) - -8. In the **Application Keys** section of the **Mesh Node** tab, select an application key from the drop-down list and then click **Add**. - - ![mesh device keys](resources/an1259-v14-ncp-commander-mesh-device-keys.png) - -9. Click **Get DCD** to configure all the Models available on your node(s), bind to app keys, set publishing or subscription to groups, fine tune parameters, and so on. - - ![node configuration](resources/an1259-v14-ncp-commander-mesh-node-configuration.png) - -10. To configure the Provisioner, the Models must first be initialized using **Initialize Client Models**. - - ![initialize models](resources/an1259-v14-ncp-commander-mesh-initialize-models.png) - -11. The Application Key must be bound to the Models in order for them to decrypt received messages. Press **Bind**. - - ![initialize models 2](resources/an1259-v14-ncp-commander-mesh-initialize-models-2.png) - -12. To subscribe the Models to the messages of the recently created Group (optional), select the chosen Group from the dropdown and click **Subscribe**. - - ![subscribe models](resources/an1259-v14-ncp-commander-mesh-subscribe-models.png) - -13. When configuration is complete, click **Done**. The **Show Nodes** tab is displayed, where you can **Get DCD** of the provisioned Node(s). - - ![Get DCD](resources/an1259-v14-ncp-commander-mesh-get-dc.png) - -14. After listing, you can **Get** or **Set** the Server states of the Node(s). - - ![get or set server states](resources/an1259-v14-ncp-commander-mesh-get-set-server-states.png) - -15. Click Set to set the current state of the selected Server of the selected Node. - - ![set server state](resources/an1259-v14-ncp-commander-mesh-set-server-state.png) - -16. Click **Get** to get the current state of the selected Server of the selected Node. - - ![get server state](resources/an1259-v14-ncp-commander-mesh-get-server-state.png) - -17. On the **Show Groups** tab, you can **Set** or **Get** the Server Model(s) states on a Group level. - - ![group level](resources/an1259-v14-ncp-commander-mesh-get-set-model-state.png) - -## Building the NCP Host Examples on Windows - -The Silicon Labs v3.x Bluetooth SDK contains a generic NCP Host example project for the PC. This example can be compiled on Windows or any POSIX OS. This section goes through the build process on Windows. - ->**Note**: The host example projects in the SDK use the dynamic GATT database feature. They are to be used with the **Bluetooth – NCP** target application. - -1. To build the examples properly, the MSYS2 development toolchain must be installed on your PC. Download MSYS2 at [MSYS2](https://www.msys2.org/). - -2. After MSYS2 is installed, update the package database as described at [MSYS2](https://www.msys2.org/). - -3. Start MSYS2 bash and install mingw-64 with the following command: - - ```C - pacman -S make mingw-w64-x86_64-gcc - ``` - -4. Close MSYS2 and start MSYS2 MinGW 64-bit. - - ![msys2 mingw 64-bit](resources/an1259-msys2-mingw-64-bit.png) - -5. Change to the NCP Host example folder, where \ varies by SDK version: - - ```C - cd c:\SiliconLabs\SimplicityStudio\v5\developer\sdks\gecko_sdk_suite\v3.x\app\bluetooth\example_host\bt_host_empty\ - ``` - - or - - ```C - cd c:\Users\\SimplicityStudio\SDKs\gecko_sdk\app - ``` - -6. Create an export of the example with the command `make export`. After the project files are exported, the export directory will be a working directory that is completely detached from the SDK but has the same folder structure inside. The benefit of using an export is that changes in the (config) files during development will not affect the SDK content, and multiple instances can coexist, for example for testing different variants. You can also use `make export EXPORT_DIR=/my/custom/export/path` to export the example to a custom directory. - -7. Within the export folder navigate to the */app/bluetooth/example_host/bt_host_empty* folder. - -8. If you want to add any service/characteristic to the GATT database, edit the */config/btconf/gatt_configuration.btconf* file. Edit it either with a text editor or drag-and-drop the file onto Simplicity Studio to edit it with the GATT Configurator. Do not forget to save the file after editing. - -9. Generate GATT database source files from the .*btconf* file by running `make gattdb` (in the */bt_host_empty* folder). Note: The generator script requires installing Python 3 and the Jinja2 package by calling `pip install jinja2`. - -10. Build the exported project with the command: `make`. (Run it in the */bt_host_empty* folder, where you can find the makefile). - -11. The build output is created in a new *exe* folder. Go to this folder with `cd exe`, and then run`bt_host_empty.exe`. The COM port and the IP address of the target are passed as command line parameters. The COM port should be the same as the one used by the JLink CDC UART Port, as shown in [NCP Host Development](./03-ncp-host-development). To see how to pass the different parameters, first run the exe with the `-h` (help) switch. - - ```C - .\bt_host_empty.exe -h - ``` - -12. Once the UART connection with the device is established, you should see the following: - - ![started advertising message](resources/an1259-figure-3-6.png) - -13. Now you can connect to the device over Bluetooth. - -## Using Python for Host Side Development - -You can also implement a host application using Python. A Python package is available at [PyBGAPI](https://pypi.org/project/pybgapi/). This package parses the API description file of the Bluetooth SDK and makes it possible to issue BGAPI commands and get BGAPI events in the Python environment. See the referred website for further documentation. +# NCP Host Development + +This section introduces the Bluetooth NCP Commander tool, which can be used to send BGAPI commands from a graphical user interface. It then walks through the process of building the PC Host examples provided in the Bluetooth SDK. And finally, it describes using Python for host side development. + +## Bluetooth NCP Commander + +Bluetooth NCP Commander is an easy-to-use tool that can be used for testing different stack features, by sending BGAPI commands to the target device. The tool has two versions: a version built into Simplicity Studio, which makes it easy to connect to your development kit and start testing, and a standalone version to test a board in an environment where Simplicity Studio cannot be installed, or if you want to test a custom board that can be accessed on UART interface, but not through a Simplicity Studio supported debug adapter using VCOM. + +### Built-in Version + +1. To open the built-in Bluetooth NCP Commander, select **Tools** tab on the left side, browse **Bluetooth NCP Commander** and click **Open Tool**. + +![Compatible Tools](resources/an1259-launch-Bluetooth-NCP-Commander.png) + +2. Select the target device, and click **Connect**. + + ![Connection Manager](resources/an1259-v14-connection-manager.png) + +### Standalone Version + +1. To open the standalone tool, navigate to *C:\Users\\\\\.silabs\slt\installs\archive\ncpcommander-vx.y.z*, and start NcpCommander.exe. + +2. In the standalone tool, provide the UART interface settings, and then select the COM port on which the device can be accessed. + + ![Serial Connection Manager](resources/an1259-v14-serial-connection-manager.png) + +### Bluetooth NCP Commander Functions + +The following procedure covers most NCP Commander functions. + +1. After the device is connected, you should see the result of the ``sl_bt_system_get_identity_address`` command displayed in green: + + ![NCP Commander](resources/an1259-v14-ncp-commander-open.png) + +2. Unlike SoC examples, the NCP demo does not have a built-in GATT database. It expects the host to build the GATT database using the dynamic GATT database BGAPI commands. To create a basic GATT database, select the Local GATT menu, and click **Create Basic GATT**. This triggers a series of BGAPI commands that will build a basic database. You can modify this GATT database as you want. You can also change the device name here by changing the value of the Device Name characteristic. + + ![Create Local GATT](resources/an1259-v14-ncp-commander-create-local-gatt.png) + +3. To extend the database with new services, characteristics, and descriptors, click **Add Service**. You can then add new characteristics for the service. + + ![Commander add service](resources/an1259-v14-ncp-commander-add-service.png) + +4. To read out the GATT database from the device, click **Local GATT Database**. The smart console also supports API calls for creating entries. + + ![Commander API method](resources/an1259-v14-ncp-commander-api-method.png) + +5. To start advertising your device so that other devices can discover it and connect to it, in the Advertise menu click '**+**' (Create Set) to create an advertiser set. + + ![Commander start advertising](resources/an1259-v14-ncp-commander-start-advertising.png) + +6. To populate the advertisement payload with the device name, set the Advertising Data Type to **Generated data** and click **Start** to start advertising. + + ![Advertising Data Type](resources/an1259-v14-ncp-commander-start-advertising-2.png) + +7. When advertising, the NCP target example accepts Bluetooth connections. If you connect to the mainboard or with another central device (for example with your phone), you can see the events and commands on the log. + + ![Commander log view](resources/an1259-v14-ncp-commander-log-view.png) + +8. You can also issue commands manually. For example, you can issue the 'system hello' command at any time to verify that communication between the host and the device is working. The Smart Console provides auto-completion and documentation for the possible commands. To open/close the documentation, click the arrows at the right side of the input field. + + ![Commander issue commands](resources/an1259-v14-ncp-commander-issue-commands.png) + +9. To create periodic advertisement sets, select **Advertisement mode: Periodic**. To set the content of the packet, use the **Edit** option next to "Periodic Advertising Packets". + + ![Commander periodic advertising](resources/an1259-v14-ncp-commander-periodic-advertising.png) + + This opens a new dialog where you can edit the contents of the package. Click **Set Data** after the data is edited. + + ![Commander edit packet](resources/an1259-v14-ncp-commander-edit-packet.png) + +10. It is also possible to synchronize to periodic advertisement trains. To do this, click **Synchronization** on the left menu, input the Advertiser Address and advertising Set identifier, and click **Open Synchronization**. + + ![Commander synchronize streams](resources/an1259-v14-ncp-commander-synchronize-streams.png) + +11. NCP Commander also provides a simple scripting feature. You can create or import an existing script with the controls on the top right corner. You can use any BGAPI commands in the script, but there are no additional features, such as branching or error handling. + + ![Commander scripting](resources/an1259-v14-ncp-commander-scripting.png) + + You can export the commands sent in the Smart console with the **Export** control. This saves the sent commands to a file that can be imported back as a script. You can also export the raw script using the **Export** button under the editor. + + ![Commander export messages](resources/an1259-v14-ncp-commander-export-messages.png) + +### Host Provisioner with Bluetooth NCP Commander + +Bluetooth NCP Commander also supports Bluetooth mesh features. You can issue Bluetooth mesh commands manually in the command box of Smart Console or use the host provisioner feature from the left menu. You can use the feature to provision and configure mesh nodes and to manage mesh networks rather than using a Bluetooth Mesh mobile application. + +To use the Bluetooth Mesh features, create, build, and flash the device with an NCP example supporting Mesh features. Otherwise, the provisioner initialization attempt returns SL_STATUS_NOT_SUPPORTED (0x000f). + +![NCP example supporting Mesh features](resources/an1259-v14-mesh-example.png) + +In **Settings**, if the **Reset Mesh Node before Initializing as Provisioner** option is enabled, the host provisioner does a factory reset (the **node_reset** command) on the NCP target device before initializing the node. Clicking **Clear Data** next to **Remove all locally saved mesh data** removes the network and application keys that were configured during initialization. + +![mesh initialization](resources/an1259-v14-ncp-commander-mesh-initialization.png) + +1. To start using the host provisioner, select either **Provision** or **Networks & Nodes** on the left menu, and click **Initialize as Provisioner**. + + ![Initialize as Provisioner](resources/an1259-v14-ncp-commander-mesh-start-provisioning.png) + +2. To provision devices, select **Provision** on the left menu and click **Start Scan** in the right panel. The devices that are transmitting unprovisioned beacons are shown in the **Discovered Devices** section. If you do not have a network from a previous configuration or have reset the provisioner node, you must create a new network with **Create New Network**. + + ![mesh provision](resources/an1259-v14-ncp-commander-mesh-provision.png) + +3. Enter the name of the new network and click **Confirm**. + + ![create new network](resources/an1259-v14-ncp-commander-mesh-create-network.png) + +4. Click **Provision** next to the device you want to provision. + + ![provision](resources/an1259-v14-ncp-commander-mesh-provision-device.png) + +5. Before configuring devices, you may need to create application keys and groups. Application keys, groups, and other network settings can be managed in the **Settings** tab of the **Networks & Nodes** menu item. To create an application key, click **Create App Key**, name the key, and click **Confirm**. You can create as many application keys as you need. If you have created any application keys before, you can click **Get App Keys** to retrieve them. To create a group, click **Add Group**, name the group, and click **Confirm**. You can create as many groups as you need. + + ![create keys groups](resources/an1259-v14-ncp-commander-mesh-create-keys-groups.png) + +6. In the same tab, you can induce a full network-wide key refresh or exclude nodes. + + ![other settings](resources/an1259-v14-ncp-commander-mesh-other-settings.png) + +7. To configure a provisioned device, select **Networks & Nodes** on the left menu. The devices you provisioned are shown in the **Nodes (Provisioned Devices)** section of the **Settings** tab. Click **Configure** and a **Mesh Node** tab opens in which you can configure the device. + + ![configure provisioned device](resources/an1259-v14-ncp-commander-mesh-configure-provisioned-device.png) + +8. In the **Application Keys** section of the **Mesh Node** tab, select an application key from the drop-down list and then click **Add**. + + ![mesh device keys](resources/an1259-v14-ncp-commander-mesh-device-keys.png) + +9. Click **Get DCD** to configure all the Models available on your node(s), bind to app keys, set publishing or subscription to groups, fine tune parameters, and so on. + + ![node configuration](resources/an1259-v14-ncp-commander-mesh-node-configuration.png) + +10. To configure the Provisioner, the Models must first be initialized using **Initialize Client Models**. + + ![initialize models](resources/an1259-v14-ncp-commander-mesh-initialize-models.png) + +11. The Application Key must be bound to the Models in order for them to decrypt received messages. Press **Bind**. + + ![initialize models 2](resources/an1259-v14-ncp-commander-mesh-initialize-models-2.png) + +12. To subscribe the Models to the messages of the recently created Group (optional), select the chosen Group from the dropdown and click **Subscribe**. + + ![subscribe models](resources/an1259-v14-ncp-commander-mesh-subscribe-models.png) + +13. When configuration is complete, click **Done**. The **Show Nodes** tab is displayed, where you can **Get DCD** of the provisioned Node(s). + + ![Get DCD](resources/an1259-v14-ncp-commander-mesh-get-dc.png) + +14. After listing, you can **Get** or **Set** the Server states of the Node(s). + + ![get or set server states](resources/an1259-v14-ncp-commander-mesh-get-set-server-states.png) + +15. Click Set to set the current state of the selected Server of the selected Node. + + ![set server state](resources/an1259-v14-ncp-commander-mesh-set-server-state.png) + +16. Click **Get** to get the current state of the selected Server of the selected Node. + + ![get server state](resources/an1259-v14-ncp-commander-mesh-get-server-state.png) + +17. On the **Show Groups** tab, you can **Set** or **Get** the Server Model(s) states on a Group level. + + ![group level](resources/an1259-v14-ncp-commander-mesh-get-set-model-state.png) + +## Building the NCP Host Examples on Windows + +Simplicity Studio SDK contains NCP Host example projects for PC. These examples can be compiled on Windows or any POSIX OS. This section goes through the build process on Windows. + +>**Note**: The host example projects in the SDK use the dynamic GATT database feature. They are to be used with the **Bluetooth – NCP** target application. + +1. To build the examples properly, the MSYS2 development toolchain must be installed on your PC. Download MSYS2 at [MSYS2](https://www.msys2.org/). + +2. After MSYS2 is installed, update the package database as described at [MSYS2](https://www.msys2.org/). + +3. Start MSYS2 bash and install mingw-64 with the following command: + + ```C + pacman -S make mingw-w64-x86_64-gcc + ``` + +4. Close MSYS2 and start MSYS2 MinGW 64-bit. + + ![msys2 mingw 64-bit](resources/an1259-msys2-mingw-64-bit.png) + +5. Create a new **Bluetooth - Host Empty** project in Simplicity Studio 6 + + ![studio6 host app generation](resources/an1259-studio6-host-app-generation.png) + +6. At the Target Device select the option **Part** and **WIN32** + ![studio6 select os](resources/an1259-studio6-select-os.png) + +7. Navigate to the project folder in MSYS2 MinGW 64-bit. + +8. Build the project in MSYS2 MinGW 64-bit + ```C + make -f bt_host_empty.Makefile + ``` +9. The build output is created in a new *build/debug/* folder. Navigate to this folder, and then run`bt_host_empty.exe` with the interface as an argument. + +10. Once the UART connection with the device is established, the following should appear: + +``` + MINGW64 ~/SimplicityStudio/v6_workspace_2226/bt_host_empty + $ ./build/debug/bt_host_empty.exe -u COM30 + [D] Timer function intialized + [I] NCP host initialised. + [I] Press Crtl+C to quit + + [I] Rebooting NCP target (0)... + [I] Bluetooth stack booted: v11.0.1+0e13429e + [I] Bluetooth public device address: 04:87:27:E7:07:5D + [I] Started advertising. +``` +10. The device advertises and ready for Bluetooth connection. + +## Using Python for Host Side Development + +You can also implement a host application using Python. A Python package is available at [PyBGAPI](https://pypi.org/project/pybgapi/). This package parses the API description file of the Bluetooth SDK and makes it possible to issue BGAPI commands and get BGAPI events in the Python environment. See the referred website for further documentation. diff --git a/sld596-bluetooth-network-coprocessor-mode/04-secure-ncp.md b/sld596-bluetooth-network-coprocessor-mode/04-secure-ncp.md index f9ef642..00e6146 100644 --- a/sld596-bluetooth-network-coprocessor-mode/04-secure-ncp.md +++ b/sld596-bluetooth-network-coprocessor-mode/04-secure-ncp.md @@ -1,45 +1,53 @@ -# Secure NCP - -Secure NCP secures communication between the NCP Host and target by encrypting the commands, events, and any data transmitted between the target and the host. - -## Target Side - -To enable this feature on the target side, install the NCP Security Interface component. - -![NCP Security Interface](resources/an1259-secure-ncp-target.png) - -By default, the NCP target boots without using this encryption. It will be requested by the Host part, and after the security is increased, only encrypted messages are sent and accepted by the target. - -## Host Side - -To build the NCP Host project with secure mode, use the following command: - -```C -make SECURITY=1 -``` - -This requires the openssl package to be installed. Install it to your MSYS2 environment with: - -```C -pacman -S mingw-w64-x86_64-openssl -``` - -After the project is built, the encryption can be enabled by calling the .exe file with the command line parameter `-s`: - -```C -.\empty.exe -s -``` - -```C -$ ./empty.exe -u COM21 -s -[I] NCP host initialised. -[I] Resetting NCP target... -[I] Press Ctrl+C to quit -[I] Start encryption -[I] Communication encrypted -[I] Bluetooth stack booted: v3.2.1-b216 -[I] Bluetooth public device address: 00:0B:57:A7:84:15 -[I] Started advertising. -``` - -Running the exe file without this option will start a normal NCP Host application without encryption. +# Secure NCP + +Secure NCP secures communication between the NCP Host and target by encrypting the commands, events, and any data transmitted between the target and the host. + +## Target Side + +To enable this feature on the target side, install the NCP Security Interface component. + +![NCP Security Interface](resources/an1259-secure-ncp-target.png) + +By default, the NCP target boots without using this encryption. It will be requested by the Host part, and after the security is increased, only encrypted messages are sent and accepted by the target. + +## Host Side + +1. Create a new **Bluetooth - Host Empty** project in Simplicity Studio 6 + + ![studio6 host app generation](resources/an1259-studio6-host-app-generation.png) + +2. At the *Target Device* select the option *Part* and the desired OS + ![studio6 select os](resources/an1259-studio6-select-os.png) + +3. Add `Secure NCP communication layer for host projects` component to the project +4. Secure mode requires the openssl package to be installed. It can be installed to the MSYS2 environment if necessary with: + +```C +pacman -S mingw-w64-x86_64-openssl +``` + +5. Build the project in MSYS2 MinGW 64-bit + ```C + make -f bt_host_empty.Makefile + ``` +6. The build output is created in a new *build/debug/* folder. After the project is built, the encryption can be enabled by calling the .exe file with the command line parameter `-s`: + +```C +.\bt_host_empty.exe -s +``` + +```C +$ ./build/debug/bt_host_empty.exe -u COM<*> -s +[D] Timer function intialized +[I] NCP host initialised. +[I] Press Crtl+C to quit + +[I] Rebooting NCP target (0)... +[I] Start encryption using OpenSSL 3.0 +[I] Communication encrypted +[I] Bluetooth stack booted: v11.0.1+0e13429e +[I] Bluetooth public device address: 04:87:27:E7:07:5D +[I] Started advertising. +``` + +Running the exe file without `-s` parameter will start a normal NCP Host application without encryption. diff --git a/sld596-bluetooth-network-coprocessor-mode/05-using-ncp-with-cpc.md b/sld596-bluetooth-network-coprocessor-mode/05-using-ncp-with-cpc.md index d35935d..88557e5 100644 --- a/sld596-bluetooth-network-coprocessor-mode/05-using-ncp-with-cpc.md +++ b/sld596-bluetooth-network-coprocessor-mode/05-using-ncp-with-cpc.md @@ -1,55 +1,74 @@ -# Using NCP with CPC (Co-Processor Communication) - -## Co-Processor Communication Overview - -The purpose of the Co-Processor Communication (CPC) Protocol is to act as a serial link multiplexer that allows data sent from multiple applications to be transported over a secure shared physical link. In CPC, data transfers between processors are segmented in sequential packets over endpoints. Transfers are guaranteed to be error-free and sent in order. - -Find more information about the CPC at [https://docs.silabs.com/gecko-platform/4.1/service/cpc/overview](https://docs.silabs.com/gecko-platform/4.1/service/cpc/overview). - -## Usage - -The CPC daemon acts as a bridge between the host and the target application. It was designed to make a reliable connection between two ends through UART or SPI. Reliability is achieved by an HDLC-like header and CPC. It offers multi-channel communication, and security is turned on by default. It is a connection-based protocol, so that if a message arrives incorrectly, it notifies the other end, which then can re-send that message. - -![CPC daemon](resources/an1259-cpc-daemon.png) - -The NCP host by default does not contain usage of CPC. You need to build the application with the command line option `CPC=1`. - -## Use Cases - -Adding the CPC functionality is recommended for the following use cases, as they cannot be used with the simple UART interface: - -- Using SPI as the transport layer: SPI communication is only supported with CPC. - -- DMP projects: the CPC protocol contains a multiplexer, which makes it possible to use the same interface for different applications. - -## Building the Target - -To make the target use CPC communication, replace the USART component in the **bt_ncp** sample application with **CPC Secondary - UART (USART)** or **CPC Secondary – SPI (USART)**. This adds all the necessary components to enable CPC communication on the target. Set the pins of the selected communication interface according to the hardware design of the project. - -The encryption of the communication is enabled by default. For developing and debugging, Silicon Labs recommends adding the **CPC SECURITY NONE** component so that the packet traces can be easier analyzed. - -![Secondary UART](resources/an1259-cpc-secondary-uart.png) - -## Host Side - -Perform the following steps: - -### Step 1: Build the CPC daemon - -Download the code for the CPC daemon and follow the instructions to build it from [https://github.com/SiliconLabs/cpc-daemon](https://github.com/SiliconLabs/cpc-daemon). - -After the build is finished, open the *cpcd.conf* file and set the **bus_type**, and configure the pins and bitrate according to the settings on the Secondary side. - -If the **CPC SECURITY NONE** component was added to the target, set **disable_encryption** to true. - -### Step 2: Build the host application - -Find the *ncp_host_bt.mk* file in the \/app/Bluetooth/component_host/ folder, and set `CPC_DIR` to the path of the CPC daemon folder on your machine. - -Next, go to the **bt_host_empty** sample application in \/app/Bluetooth/example_host/bt_host_empty, and build it with this command line option to enable CPC: `make CPC=1`. - -### Step 3: Run the application - -Start the CPC daemon `cpcd -c ./cpcd.conf`. - -Start the host application by passing the **instance_name** set in the *cpcd.conf* file: `./bt_host_empty -C cpcd_0`. +# Using NCP with CPC (Co-Processor Communication) + +## Co-Processor Communication Overview + +The purpose of the Co-Processor Communication (CPC) Protocol is to act as a serial link multiplexer that allows data sent from multiple applications to be transported over a secure shared physical link. In CPC, data transfers between processors are segmented in sequential packets over endpoints. Transfers are guaranteed to be error-free and sent in order. + +Find more information about the CPC at [https://docs.silabs.com/gecko-platform/latest/platform-cpc-overview/](https://docs.silabs.com/gecko-platform/latest/platform-cpc-overview/). + +## Usage + +The CPC daemon acts as a bridge between the host and the target application. It was designed to make a reliable connection between two ends through UART or SPI. Reliability is achieved by an HDLC-like header and CPC. It offers multi-channel communication, and security is turned on by default. It is a connection-based protocol, so that if a message arrives incorrectly, it notifies the other end, which then can re-send that message. + +![CPC daemon](resources/an1259-cpc-daemon.png) + +The NCP host by default does not contain usage of CPC. You need to build the application with **Host NCP CPC adapter (Linux only)** component. + +>**Note**: The Host NCP CPC adapter (Linux only) component is Experimental currently. + +## Use Cases + +Adding the CPC functionality is recommended for the following use cases, as they cannot be used with the simple UART interface: + +- Using SPI as the transport layer: SPI communication is only supported with CPC. + +- DMP projects: the CPC protocol contains a multiplexer, which makes it possible to use the same interface for different applications. + +## Building the Target + +To make the target use CPC communication, replace the USART component in the **bt_ncp** sample application with **CPC Secondary - UART (USART)** or **CPC Secondary – SPI (USART)**. This adds the necessary components to enable CPC communication on the target. Set the pins of the selected communication interface according to the hardware design of the project. + +In NCP setup **Bluetooth NCP Transport over CPC** component is required. + +>**Note**: The Bluetooth NCP Transport over CPC component is Experimental currently. + +![Add Target NCP CPC](resources/Studio6-target-app-CPC.png) + +The encryption of the communication is enabled by default. For developing and debugging, Silicon Labs recommends adding the **CPC SECURITY NONE** component so that the packet traces can be easier analyzed. + +![Secondary UART](resources/an1259-cpc-secondary-uart.png) + +## Host Side + +Perform the following steps: + +### Step 1: Build the CPC daemon + +Download the code for the CPC daemon and follow the instructions to build it from [https://github.com/SiliconLabs/cpc-daemon](https://github.com/SiliconLabs/cpc-daemon). + +After the build is finished, open the *cpcd.conf* file and set the **bus_type**, and configure the pins and bitrate according to the settings on the Secondary side. + +If the **CPC SECURITY NONE** component was added to the target, set **disable_encryption** to true. + +### Step 2: Build the host application + +1. Create a new **Bluetooth - Host empty** project in Simplicity Studio 6 + ![studio6 host app generation](resources/an1259-studio6-host-app-generation.png) + +2. At the *Target Device* select the option *Part* and *Linux* + ![studio6 select os](resources/an1259-studio6-select-os.png) + +3. Add *Host NCP CPC adapter (Linux only)* component + ![Add Host NCP CPC](resources/Studio6-host-app-CPC.png) +>**Note**: The Host NCP CPC adapter (Linux only) component is Experimental currently. +4. Build the project + ```C + make -f bt_host_empty.Makefile + ``` +5. The build output is created in a new *build/debug/* folder. + +### Step 3: Run the application + +Start the CPC daemon `cpcd -c ./cpcd.conf`. + +Start the host application by passing the **instance_name** set in the *cpcd.conf* file: `./bt_host_empty -C cpcd_0`. diff --git a/sld596-bluetooth-network-coprocessor-mode/06-example-project-walkthrough.md b/sld596-bluetooth-network-coprocessor-mode/06-example-project-walkthrough.md index 60e570d..f01c679 100644 --- a/sld596-bluetooth-network-coprocessor-mode/06-example-project-walkthrough.md +++ b/sld596-bluetooth-network-coprocessor-mode/06-example-project-walkthrough.md @@ -1,376 +1,361 @@ -# Example Project Walkthrough - -This page describes the structure of the example NCP Host and Target projects, and highlights the parts that can be important if you create your own project. - -## NCP Target - -This section focuses on the NCP-specific part of the **Bluetooth - NCP** SSv5 project. You can find a general project description in [Silicon Labs Bluetooth C Application Developers Guide](https://docs.silabs.com/bluetooth/latest/bluetooth-c-soc-dev-guide-sdk-v9x/). - -The **Bluetooth - NCP** example does not contain a GATT database. The dynamic GATT API can be used for building it. This is recommended because the target code does not need to be modified and synchronized with the Host code when the GATT database is updated. - -### Project File Structure - -A common directory and file structure are used across all examples in the Bluetooth SDK v3.x. The following figure shows this layout. - -![project file structure](resources/an1259-v10-bt-ncp-project.png) - -These files and directories are present in the root directory of the project: - -- *main.c* and *app.c/h* – the C application code - -- *bt_ncp.pintool* – the hardware configuration file and user interface - -- *bt_ncp.slcp* – the component configuration and user interface - -- *bt_ncp.slps* – the project properties XML file - -- *GNU ARM v\* – the build directory - -- *gecko.sdk_3.\* – the Bluetooth SDK source code - -- *config* – the C configuration files of the hardware and Bluetooth stack. This directory contains the output files of the Pin Tool and Component Manager. - -- *autogen* – the C configuration code of the application. This directory typically contains the stack definition and initialization C files, as well as the generated GATT database C declaration files (*gatt_db.c/h*). - -### Pin Tool - -1. Open the pin configuration tool (Pin Tool) on the project Configuration Tools tab. - - ![pin tool](resources/an1259-v04-pin-tool.png) - - You can also double-click the *\.pintool* file in the Project Explorer view, shown highlighted in the figure above. - -2. Use this tool to modify the pin configuration of the device, for example, you can reassign the pins used for USART communication to the appropriate layout for a custom board design. You do this by selecting the desired pin in the list and then selecting its functionality from the drop-down list. - - ![pin tool example](resources/an1259-figure-4-3.png) - -3. After clicking the selected item, the layout is updated. After saving the file, the configuration source codes are automatically generated. - - ![config source code generation](resources/an1259-figure-4-4.png) - -### Project Configurator/Component Editor - -You can install or uninstall components using the Project Configurator's Software Components tab. You can also configure installed components using the Component Editor. The following figures show how to change the NCP interface buffer sizes. - -1. Select the component from the list and click **Configure**. - - ![Configure](resources/an1259-v04-ncp-communications-component.png) - -2. The Component Editor opens in a new tab with the possible configuration options. You can view the corresponding source code by clicking **Open Source**. - - ![Open Source](resources/an1259-v04-ncp-interface-options.png) - -3. Apart from the application-specific NCP options, you can use the Project Configurator to configure the Bluetooth stack features that will be included in your project. Some advanced features are excluded from the stack by default, to save flash and memory. You can add the needed features, for example, the Adaptive Frequency Hopping (AFH) component, by clicking **Install**. - - ![Install](resources/an1259-v04-component-install.png) - -4. In many cases, you also need to change the default Bluetooth Core configuration, for example to enable more than four connections. To do so, browse for the Bluetooth Core component, and click **Configure**. - - ![Configure](resources/an1259-bluetooth-core-configure.png) - -### Enabling Hardware Flow Control - -In the sample applications, Hardware Flow Control is enabled by default. On the mainboard, hardware flow control can be enabled as described in this section. - -Important: If the hardware flow control settings are not the same in the SoC and mainboard, the NCP will not work. - -1. Open Simplicity Studio and, in the Debug Adapters view, right-click the target device. - -2. Select **Connect**. - -3. Right-click the device again and select **Launch Console**. - -4. Select the admin tab. - -5. Set flow control with the following command: - - ```C - WSTK> serial vcom config handshake rtscts - RTS handshake enabled - CTS handshake enabled - Serial configuration saved - ``` - -6. Check the configuration with the following command: - - ```C - WSTK> serial vcom - ----- Virtual COM port ----- - Stored port speed : 115200 - Active port speed : 115226 - Stored handshake : rtscts - Actual handshake : rtscts - RTS Asserted - Ready to Receive. - ``` - -The flow can be disabled by setting the handshake parameter to `none` in step 5 above. - -### Main Walkthrough - -This is a code snippet that corresponds to the `main` function. Because the Bluetooth stack and subsequent hardware are considered to be components, they are separated from the application processing that is entirely managed in *app.c/h*. - -![code snippet of main function](resources/an1259-figure-4-8.png) - -Once the USART and Bluetooth stack are initialized, the main loop continuously calls the component as well as the application state machine. The corresponding functions are `sl_system_process_action()` and `app_process_action()` respectively. - -The `sl_system_process_action()` handles Silicon Labs tasks and routines. It must *not be removed* from the loop. - -The default USART settings are mentioned in the Host example section. Make sure that the target and the host use the same configuration. The configuration can be adapted with the help of the Pin Tool and the Project Configurator. - -### Application Callback and Actions - -Use the `app_init()` function to call application-related initializations. - -Use the `app_process_action()` function to call application-specific tasks and routines. - -![application callback](resources/an1259-v08-callbacks.png) - -### NCP Code Walkthrough - -The USART communication handling is implemented in *ncp_usart.c*. Receiving any command from the Host generates an interrupt, and it will queue the received data in the command queue. Similarly, when a stack generates an event, it will be put into an event queue, which will be forwarded to the Host. These two queues will be processed in *ncp.c*, as described on the following figure. - -![NCP Code Walkthrough](resources/an1259-figure-4-10.png) - -### Sleep Modes - -The NCP example project does not enable deep sleep mode (EM2) by default, because UART needs EM1 or EM0 to be able to receive commands at any time. Deep sleep mode can be enabled, but in this case, it is essential to configure a wakeup pin so that the NCP Host can wake up the target before sending any BGAPI commands to it. Any available GPIO pin can be configured as a wakeup pin and the polarity is configurable. The following example shows how to configure pin PF6 as the wakeup pin using active-high polarity. - -To enable deep sleep mode, the UARTDRV Core component's **Enable reception when sleeping** parameter must be disabled. Otherwise the UART driver will prevent the device from going into EM2 (deep sleep) and it will stay in EM1 (sleep): - -![UARTDRV Core](resources/an1259-v02-uartdrv.png) - -To define a wakeup pin, the Bluetooth > Utility > Wake Lock component must be added to the project: - -![Wake Lock](resources/an1259-v04-wake-lock.png) - -Configure the Wake-Lock component as follows: - -- Enable the wake-lock (direction in) functionality - -- Set the polarity (active high in this case) - -- Assign the GPIO pin (PF6 in this example) - - ![Wake Lock Input](resources/an1259-v02-wake-lock-config.png) - -When the Host sets the wakeup pin to the configured active value, the NCP device will wake up from deep sleep and send out the event `sl_bt_evt_system_awake` to indicate to the host that it has woken up. The host must wait for this event before sending any BGAPI commands, otherwise they might be partially or completely missed. - -The remote wake-lock (direction: out) functionality can be used to wake up the host before the NCP target sends out an event. This way the host is also able to go into sleep mode, and it will be notified when it should wake up. - -## PC Host - -The PC host application project that comes with the SDK is written in C. The host-side source files for this project are found in folders, for GSDK 3.x: - -*c:\SiliconLabs\SimplicityStudio\v5\developer\sdks\gecko_sdk_suite\\\app\bluetooth\example_host\empty\* - -or, for GSDK 4.0 and higher: - -*c:\Users\\\SimplicityStudio\gecko_sdk\app\bluetooth\example_host* - -The projects comprise only a few source and header files. Note, however, that many other files are referenced from the SDK in the makefile. For example, many utility functions are implemented under: - -*\\app\bluetooth\common_host\* - -but the Bluetooth protocol folder is also heavily used as described later. To copy all the files related to the project into a single folder, take advantage of the export feature described in [Host Side](./04-secure-ncp.md#host-side). - -### BGAPI Support Files - -While the files in the previous section contain all of the application logic, the actual BGLib implementation code containing the BGAPI parser and packet generation functions is found elsewhere, in other subfolders. - -Default location in GSDK 3.x, where \ will vary by SDK version: - -- `c:\SiliconLabs\SimplicityStudio\v5\developer\sdks\gecko_sdk_suite\\protocol\bluetooth\inc\sl_bt_ncp_host.h` - -- `c:\SiliconLabs\SimplicityStudio\v5\developer\sdks\gecko_sdk_suite\\protocol\bluetooth\src\sl_bt_ncp_host.c` - -- `c:\SiliconLabs\SimplicityStudio\v5\developer\sdks\gecko_sdk_suite\\protocol\bluetooth\src\sl_bt_ncp_host_api.c` - -Default location in GSDK 4.0 and higher: - -- `c:\Users\\SimplicityStudio\SDKs\gecko_sdk\protocol\bluetooth\inc\sl_bt_ncp_host.h` - -- `c:\Users\\SimplicityStudio\SDKs\gecko_sdk\protocol\bluetooth\src\sl_bt_ncp_host.c` - -- `c:\Users\\SimplicityStudio\SDKs\gecko_sdk\protocol\bluetooth\src\sl_bt_ncp_host_api.c` - -The SDK’s specific arrangement of files is one possible way the BGAPI protocol can be used, but it is also possible to create your own library code that implements the protocol correctly with a different code architecture. The only requirement here is that the chosen implementation must be able to create BGAPI command packets correctly and send them to the module over UART. Similarly, it must be able to receive BGAPI response and event packets over UART and process them into whatever function calls are needed to trigger the desired application behavior. - -The header files contain primarily #define’d compiler macros and named constants that correspond to all of the various API methods and enumerations you may need to use. The *sl_bt_ncp_host.h* file also contains function declarations for the basic packet reception, processing, and transmission functions. - -The *sl_bt_ncp_host.c* file contains the implementation of the packet management functions. All functions defined here use only ANSI C code, to help ensure maximum cross-compatibility on different platforms. - ->**Note**: With structure packing, the SDK’s BGLib implementation makes heavy use of direct mapping of packet payload structures onto contiguous blocks of memory, to avoid additional parsing and RAM usage. This is accomplished with the PACKSTRUCT macro used extensively in the BGLib header files. It is important to ensure than any ported version of BGLib also correctly packs structures together (no padding on multi-byte struct member variables) in order to achieve the correct operation. - - With byte order, the BGAPI protocol uses little-endian byte ordering for all multi-byte integer values, which means directly-mapped structures will only work if the host platform also uses little-endian byte ordering. This covers most common platforms today, but some big-endian platforms exist and are actively used today (Motorola 6800, 68k, and so on). - -### Host Application Logic - -1. Initialize BGLIB. - - ```C - sl_bt_api_initialize_nonblock(ncp_host_tx, ncp_host_rx, ncp_host_lazy_peek); - ``` - -2. Initialize UART. - - ```C - handle_ptr = &handle; - HOST_COMM_API_INITIALIZE_NONBLOCK(uartTx, uartRx, uartRxPeek); - status = uartOpen(handle_ptr, (int8_t *)uart_port, uart_baud_rate, - uart_flow_control, DEFAULT_UART_TIMEOUT); - if (status < HANDLE_VALUE_MIN) { - app_log_error("Failed to open serial connection (%d)" - APP_LOG_NL, status); - exit(EXIT_FAILURE); - } - uartFlush(handle_ptr); - ``` - -3. Reset NCP Target to ensure it gets into a defined state. Once the chip successfully boots, the `sl_bt_evt_system_boot_id` event should be received. - - ```C - // This command is equivalent with sl_bt_system_reboot - uint8_t reboot_command[] = { 0x20, 0x00, 0x01, 0x1f }; - - if (boot_retry_count < NCP_REBOOT_RETRY_COUNT) { - app_log_info("Rebooting NCP target (%d)..." APP_LOG_NL, boot_retry_count); - boot_retry_count++; - (void)host_comm_tx(sizeof(reboot_command), reboot_command); - sl_status_t sc = app_timer_start(timer, - NCP_REBOOT_TIMEOUT_RETRY_MS, - on_boot_timer_expire, - NULL, - false); - app_assert_status(sc); - } else { - app_assert(false, "NCP target unreachable."); - } - ``` - -4. The `sl_bt_step` function will be called from the main loop. It checks for any NCP Target events and forwards them to the handler function. - - ```C - // Poll Bluetooth stack for an event and call event handler - static void sl_bt_step(void) - { - sl_bt_msg_t evt; - // Pop (non-blocking) a Bluetooth stack event from event queue. - sl_status_t status = sl_bt_pop_event(&evt); - if (status != SL_STATUS_OK) { - return; - } - sl_bt_on_event(&evt); - } - ``` - -5. Process the incoming NCP target events. - - ```C - /**************************************************************************//** - * Bluetooth stack event handler. - * This overrides the default weak implementation. - * - * @param[in] evt Event coming from the Bluetooth stack. - *****************************************************************************/ - void sl_bt_on_event(sl_bt_msg_t *evt) - { - sl_status_t sc; - bd_addr address; - 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: - // Extract unique ID from BT Address. - sc = sl_bt_gap_get_identity_address(&address, &address_type); - app_assert_status(sc); - app_log_info("Bluetooth %s address: %02X:%02X:%02X:%02X:%02X:%02X" APP_LOG_NL, - 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]; - 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); - - // Generate data for advertising - 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 advertising data\n", - (int)sc); - - // Set advertising interval to 100ms. - sc = sl_bt_advertiser_set_timing( - advertising_set_handle, - 160, // min. adv. interval (milliseconds * 1.6) - 160, // max. adv. interval (milliseconds * 1.6) - 0, // adv. duration - 0); // max. num. adv. events - app_assert_status(sc); - // Start general advertising and enable connections. - sc = sl_bt_legacy_advertiser_start(advertising_set_handle, - sl_bt_legacy_advertiser_connectable); - app_assert_status(sc); - app_log_info("Started advertising." APP_LOG_NL); - break; - - // ------------------------------- - // This event indicates that a new connection was opened. - case sl_bt_evt_connection_opened_id: - app_log_info("Connection opened." APP_LOG_NL); - break; - - // ------------------------------- - // This event indicates that a connection was closed. - case sl_bt_evt_connection_closed_id: - app_log_info("Connection closed." APP_LOG_NL); - - // Generate data for advertising - 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 advertising data\n", - (int)sc); - - // Restart advertising after client has disconnected. - sc = sl_bt_legacy_advertiser_start(advertising_set_handle, - sl_bt_legacy_advertiser_connectable); - app_assert_status(sc); - app_log_info("Started advertising." APP_LOG_NL); - break; - - /////////////////////////////////////////////////////////////////////////// - // Add additional event handlers here as your application requires! // - /////////////////////////////////////////////////////////////////////////// - - // ------------------------------- - // Default event handler. - default: - break; - } - } - ``` +# Example Project Walkthrough + +This page describes the structure of the example NCP Host and Target projects, and highlights the parts that can be important if you create your own project. + +## NCP Target + +This section focuses on the NCP-specific part of the **Bluetooth - NCP** SSv6 project. You can find a general project description in [Silicon Labs Bluetooth C Application Developers Guide](https://docs.silabs.com/bluetooth/latest/bluetooth-c-soc-dev-guide-sdk-v9x/). + +The **Bluetooth - NCP** example does not contain a GATT database. The dynamic GATT API can be used for building it. This is recommended because the target code does not need to be modified and synchronized with the Host code when the GATT database is updated. + +### Project File Structure + +A common directory and file structure are used across the examples in the Bluetooth SDK. The following figure shows this layout. + +![project file structure](resources/an1259-v10-bt-ncp-project.png) + +These files and directories are present in the root directory of the project: + +- *main.c* and *app.c/h* – the C application code + +- *bt_ncp.pintool* – the hardware configuration file and user interface + +- *bt_ncp.slcp* – the component configuration and user interface + +- *bt_ncp.slps* – the project properties XML file + +- *simplicity_sdk_.\* – the Bluetooth SDK source code + +- *config* – the C configuration files of the hardware and Bluetooth stack. This directory contains the output files of the Pin Tool and Component Manager. + +- *autogen* – the C configuration code of the application. This directory typically contains the stack definition and initialization C files, as well as the generated GATT database C declaration files (*gatt_db.c/h*). + +### Pin Tool + +1. Open the pin configuration tool (Pin Tool) on the project Configuration Tools tab. + + ![pin tool](resources/an1259-v04-pin-tool.png) + + You can also double-click the *\.pintool* file in the Project Explorer view, shown highlighted in the figure above. + +2. Use this tool to modify the pin configuration of the device, for example, you can reassign the pins used for USART communication to the appropriate layout for a custom board design. You do this by selecting the desired pin in the list and then selecting its functionality from the drop-down list. + + ![pin tool example](resources/an1259-figure-4-3.png) + +3. After clicking the selected item, the layout is updated. After saving the file, the configuration source codes are automatically generated. + + ![config source code generation](resources/an1259-figure-4-4.png) + +### Project Configurator/Component Editor + +You can install or uninstall components using the Project Configurator's Software Components tab. You can also configure installed components using the Component Editor. The following figures show how to change the NCP interface buffer sizes. + +1. Select the component from the list and click **Configure**. + + ![Configure](resources/an1259-v04-ncp-communications-component.png) + +2. The Component Editor opens in a new tab with the possible configuration options. You can view the corresponding source code by clicking **Open Source**. + + ![Open Source](resources/an1259-v04-ncp-interface-options.png) + +3. Apart from the application-specific NCP options, you can use the Project Configurator to configure the Bluetooth stack features that will be included in your project. Some advanced features are excluded from the stack by default, to save flash and memory. You can add the needed features, for example, the Adaptive Frequency Hopping (AFH) component, by clicking **Install**. + + ![Install](resources/an1259-v04-component-install.png) + +4. In many cases, you also need to change the default Bluetooth Core configuration, for example to enable more than four connections. To do so, browse for the Bluetooth Core component, and click **Configure**. + + ![Configure](resources/an1259-bluetooth-core-configure.png) + +### Enabling Hardware Flow Control + +In the sample applications, Hardware Flow Control is enabled by default. On the mainboard, hardware flow control can be enabled as described in this section. + +Important: If the hardware flow control settings are not the same in the SoC and mainboard, the NCP will not work. + +1. Open Simplicity Studio and, in the Debug Adapters view, right-click the target device. + +2. Select **Connect**. + +3. Right-click the device again and select **Launch Console**. + +4. Select the admin tab. + +5. Set flow control with the following command: + + ```C + WSTK> serial vcom config handshake rtscts + RTS handshake enabled + CTS handshake enabled + Serial configuration saved + ``` + +6. Check the configuration with the following command: + + ```C + WSTK> serial vcom + ----- Virtual COM port ----- + Stored port speed : 115200 + Active port speed : 115226 + Stored handshake : rtscts + Actual handshake : rtscts + RTS Asserted - Ready to Receive. + ``` + +The flow can be disabled by setting the handshake parameter to `none` in step 5 above. + +### Main Walkthrough + +This is a code snippet that corresponds to the `main` function. Because the Bluetooth stack and subsequent hardware are considered to be components, they are separated from the application processing that is entirely managed in *app.c/h*. + +![code snippet of main function](resources/an1259-figure-4-8.png) + +Once the USART and Bluetooth stack are initialized, the main loop continuously calls the component as well as the application state machine. The corresponding functions are `sl_main_process_action()` and `app_process_action()` respectively. + +The `sl_main_process_action()` handles Silicon Labs tasks and routines. It must *not be removed* from the loop. + +The default USART settings are mentioned in the Host example section. Make sure that the target and the host use the same configuration. The configuration can be adapted with the help of the Pin Tool and the Project Configurator. + +### Application Callback and Actions + +Use the `app_init()` function to call application-related initializations. + +Use the `app_process_action()` function to call application-specific tasks and routines. + +![application callback](resources/an1259-v08-callbacks.png) + +### NCP Code Walkthrough + +The USART communication handling is implemented in *ncp_usart.c*. Receiving any command from the Host generates an interrupt, and it will queue the received data in the command queue. Similarly, when a stack generates an event, it will be put into an event queue, which will be forwarded to the Host. These two queues will be processed in *ncp.c*, as described on the following figure. + +![NCP Code Walkthrough](resources/an1259-figure-4-10.png) + +### Sleep Modes + +The NCP example project does not enable deep sleep mode (EM2) by default, because UART needs EM1 or EM0 to be able to receive commands at any time. Deep sleep mode can be enabled, but in this case, it is essential to configure a wakeup pin so that the NCP Host can wake up the target before sending any BGAPI commands to it. Any available GPIO pin can be configured as a wakeup pin and the polarity is configurable. The following example shows how to configure pin PF6 as the wakeup pin using active-high polarity. + +To enable deep sleep mode, the UARTDRV Core component's **Enable reception when sleeping** parameter must be disabled. Otherwise the UART driver will prevent the device from going into EM2 (deep sleep) and it will stay in EM1 (sleep): + +![UARTDRV Core](resources/an1259-v02-uartdrv.png) + +To define a wakeup pin, the Bluetooth > Utility > Wake Lock component must be added to the project: + +![Wake Lock](resources/an1259-v04-wake-lock.png) + +Configure the Wake-Lock component as follows: + +- Enable the wake-lock (direction in) functionality + +- Set the polarity (active high in this case) + +- Assign the GPIO pin (PF6 in this example) + + ![Wake Lock Input](resources/an1259-v02-wake-lock-config.png) + +When the Host sets the wakeup pin to the configured active value, the NCP device will wake up from deep sleep and send out the event `sl_bt_evt_system_awake` to indicate to the host that it has woken up. The host must wait for this event before sending any BGAPI commands, otherwise they might be partially or completely missed. + +The remote wake-lock (direction: out) functionality can be used to wake up the host before the NCP target sends out an event. This way the host is also able to go into sleep mode, and it will be notified when it should wake up. + +## PC Host + +The PC host application project that comes with the SDK is written in C. The host-side source files for this project are copied / linked after a host project is generated from Simplicity Studio 6. + +The projects comprise only a few source and header files. Note, however, that many other files are referenced from the SDK in the makefile. +For further details about the host side application please refer to [Host Side build](./04-secure-ncp.md#host-side). + +### BGAPI Support Files + +While the files in the previous section contain all of the application logic, the actual BGLib implementation code containing the BGAPI parser and packet generation functions is found elsewhere, in other subfolders. + +Default location for SiSDK 2025.12.x and above: + +- `C:\Users\\.silabs\slt\installs\conan\p\\p\protocol\bluetooth\inc\sl_bt_ncp_host.h` + +- `C:\Users\\.silabs\slt\installs\conan\p\\p\protocol\bluetooth\src\sl_bt_ncp_host.c` + +- `C:\Users\\.silabs\slt\installs\conan\p\\p\protocol\bluetooth\src\sl_bt_ncp_host_api.c` + +The SDK’s specific arrangement of files is one possible way the BGAPI protocol can be used, but it is also possible to create your own library code that implements the protocol correctly with a different code architecture. The only requirement here is that the chosen implementation must be able to create BGAPI command packets correctly and send them to the module over UART. Similarly, it must be able to receive BGAPI response and event packets over UART and process them into whatever function calls are needed to trigger the desired application behavior. + +The header files contain primarily #define’d compiler macros and named constants that correspond to all of the various API methods and enumerations you may need to use. The *sl_bt_ncp_host.h* file also contains function declarations for the basic packet reception, processing, and transmission functions. + +The *sl_bt_ncp_host.c* file contains the implementation of the packet management functions. All functions defined here use only ANSI C code, to help ensure maximum cross-compatibility on different platforms. + +>**Note**: With structure packing, the SDK’s BGLib implementation makes heavy use of direct mapping of packet payload structures onto contiguous blocks of memory, to avoid additional parsing and RAM usage. This is accomplished with the PACKSTRUCT macro used extensively in the BGLib header files. It is important to ensure than any ported version of BGLib also correctly packs structures together (no padding on multi-byte struct member variables) in order to achieve the correct operation. + + With byte order, the BGAPI protocol uses little-endian byte ordering for all multi-byte integer values, which means directly-mapped structures will only work if the host platform also uses little-endian byte ordering. This covers most common platforms today, but some big-endian platforms exist and are actively used today (Motorola 6800, 68k, and so on). + +### Host Application Logic + +1. Initialize BGLIB. + + ```C + sl_bt_api_initialize_nonblock(ncp_host_tx, ncp_host_rx, ncp_host_lazy_peek); + ``` + +2. Initialize UART. + + ```C + handle_ptr = &handle; + HOST_COMM_API_INITIALIZE_NONBLOCK(uartTx, uartRx, uartRxPeek); + status = uartOpen(handle_ptr, (int8_t *)uart_port, uart_baud_rate, + uart_flow_control, DEFAULT_UART_TIMEOUT); + if (status < HANDLE_VALUE_MIN) { + app_log_error("Failed to open serial connection (%d)" + APP_LOG_NL, status); + exit(EXIT_FAILURE); + } + uartFlush(handle_ptr); + ``` + +3. Reset NCP Target to ensure it gets into a defined state. Once the chip successfully boots, the `sl_bt_evt_system_boot_id` event should be received. + + ```C + // This command is equivalent with sl_bt_system_reboot + uint8_t reboot_command[] = { 0x20, 0x00, 0x01, 0x1f }; + + if (boot_retry_count < NCP_REBOOT_RETRY_COUNT) { + app_log_info("Rebooting NCP target (%d)..." APP_LOG_NL, boot_retry_count); + boot_retry_count++; + (void)host_comm_tx(sizeof(reboot_command), reboot_command); + sl_status_t sc = app_timer_start(timer, + NCP_REBOOT_TIMEOUT_RETRY_MS, + on_boot_timer_expire, + NULL, + false); + app_assert_status(sc); + } else { + app_assert(false, "NCP target unreachable."); + } + ``` + +4. The `sl_bt_step` function will be called from the main loop. It checks for any NCP Target events and forwards them to the handler function. + + ```C + // Poll Bluetooth stack for an event and call event handler + void sl_bt_step(void) + { + sl_bt_msg_t evt; + + // Run the Bluetooth host stack processing step + sl_bt_run(); + + // Check the length of the next event, if any, and verify that the application + // can process it. To prevent data loss, the event will be kept in the stack's + // queue if the application cannot process it at the moment. + size_t event_len = sli_bgapi_device_peek_event_len(&sli_bt_bgapi_device); + if ((event_len == 0) || (!sl_bt_can_process_event(event_len))) { + return; + } + ``` + +5. Process the incoming NCP target events. + + ```C + /**************************************************************************//** + * Bluetooth stack event handler. + * This overrides the default weak implementation. + * + * @param[in] evt Event coming from the Bluetooth stack. + *****************************************************************************/ + void sl_bt_on_event(sl_bt_msg_t *evt) + { + sl_status_t sc; + bd_addr address; + 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: + // Extract unique ID from BT Address. + sc = sl_bt_gap_get_identity_address(&address, &address_type); + app_assert_status(sc); + app_log_info("Bluetooth %s address: %02X:%02X:%02X:%02X:%02X:%02X" APP_LOG_NL, + 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]; + 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); + + // Generate data for advertising + 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 advertising data\n", + (int)sc); + + // Set advertising interval to 100ms. + sc = sl_bt_advertiser_set_timing( + advertising_set_handle, + 160, // min. adv. interval (milliseconds * 1.6) + 160, // max. adv. interval (milliseconds * 1.6) + 0, // adv. duration + 0); // max. num. adv. events + app_assert_status(sc); + // Start general advertising and enable connections. + sc = sl_bt_legacy_advertiser_start(advertising_set_handle, + sl_bt_legacy_advertiser_connectable); + app_assert_status(sc); + app_log_info("Started advertising." APP_LOG_NL); + break; + + // ------------------------------- + // This event indicates that a new connection was opened. + case sl_bt_evt_connection_opened_id: + app_log_info("Connection opened." APP_LOG_NL); + break; + + // ------------------------------- + // This event indicates that a connection was closed. + case sl_bt_evt_connection_closed_id: + app_log_info("Connection closed." APP_LOG_NL); + + // Generate data for advertising + 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 advertising data\n", + (int)sc); + + // Restart advertising after client has disconnected. + sc = sl_bt_legacy_advertiser_start(advertising_set_handle, + sl_bt_legacy_advertiser_connectable); + app_assert_status(sc); + app_log_info("Started advertising." APP_LOG_NL); + break; + + /////////////////////////////////////////////////////////////////////////// + // Add additional event handlers here as your application requires! // + /////////////////////////////////////////////////////////////////////////// + + // ------------------------------- + // Default event handler. + default: + break; + } + } + ``` diff --git a/sld596-bluetooth-network-coprocessor-mode/08-adding-a-new-service-to-the-ncp-example-with-dynamic-gatt-api.md b/sld596-bluetooth-network-coprocessor-mode/08-adding-a-new-service-to-the-ncp-example-with-dynamic-gatt-api.md index 1c4eb85..3155c1e 100644 --- a/sld596-bluetooth-network-coprocessor-mode/08-adding-a-new-service-to-the-ncp-example-with-dynamic-gatt-api.md +++ b/sld596-bluetooth-network-coprocessor-mode/08-adding-a-new-service-to-the-ncp-example-with-dynamic-gatt-api.md @@ -1,117 +1,113 @@ -# Adding New Attributes to the GATT Database - -This page describes how to add a custom Bluetooth service to the **NCP** example using the dynamic GATT API. The service added here has one characteristic to receive data. When the central device (tablet/phone) writes this characteristic, the peripheral (starter kit – NCP Target) forwards this data to the NCP Host. The NCP Host prints out the actual data to the PC console. - -![new service to NCP](resources/an1259-new-service-to-NCP-empty.png) - -To implement this application, you need to make these changes: - -- Modify the GATT database in the Host project - -- Handle the GATT change event (sl_bt_evt_gatt_server_attribute_value) in the Host project - -## Adding New Attributes Using the Configuration File - -Beginning with SDK version 3.3, the NCP host sample applications contains a .btconf file with a basic GATT configuration. This configuration can be edited with the GATT Configurator. Although PC host examples are not handled by Simplicity Studio, .btconf files can still be edited individually. Open the Simplicity IDE perspective in Simplicity Studio and drag-and-drop the .btconf file onto the editor area. GATT Configurator will automatically open. Edit the file as described in [GATT Configurator User’s Guide for Bluetooth SDK v3.x](https://docs.silabs.com/bluetooth/latest/gatt-configurator-users-guide-ble-btmesh/) and save it. To be compatible with the code snippets, create a custom service and then add a custom characteristic with the following properties: - -- ID: my_data - -- Read, Write, Indicate - -- Value length: 20 bytes - -Once the .btconf file is saved it must be turned into source code by running `make gattdb`. Run this command in the root folder of your example, where you can find the makefile. Note that the generator script requires installing Python 3 and the Jinja2 package by calling `pip install jinja2`. - -![make gattdb](resources/an1259-v08-make-code-snippet.png) - -The output (gatt_db.c / gatt_db.h) is located in the autogen folder. These values will be used as parameters for the dynamic GATT APIs. The database will be created (that is, built on the NCP target with the dynamic GATT API) automatically in the initialization phase before the boot event is sent to the application. The application is still able update the GATT database with the dynamic GATT commands, as described in the next section. - ->**Note**: If your database contains included services, the included ones need to be defined before the ones including them. - -## Adding New Attributes Using the Dynamic GATT API - -The GATT database can be extended with the APIs provided by the Dynamic GATT Configurator component. For more details, see the Bluetooth API reference manual on [docs.silabs.com](https://docs.silabs.com/), section "GATT Database." - -In the code snippet below, the custom service and characteristic is added to the database. The service will be a primary service, defined with a 16-byte long UUID, and it will be advertised. - -The characteristic has the following properties: - -- Read, Write, Indicate - -- Valuelength: 20 bytes - -- Valuemax length: 20 bytes - -- 16-bytelong UUID - -The service and the characteristic can be added any time after the boot event was received, but adding them in the boot event handler is suggested. - -```C -uint8_t uuid_service[16] = {…} //define your 128bit service UUID, you can use a random number -uint8_t uuid_characteristic[16] = {…} //define your 128bit characteristic UUID - -//create a session for the database update -sl_bt_gattdb_new_session(&session); -//add our service to the database, as an advertised primary service -sl_bt_gattdb_add_service(session, sl_bt_gattdb_primary_service, SL_BT_GATTDB_ADVERTISED_SERVICE, 16, - uuid_service, &service); -//define the following properties: read, write, indicate -property = (SL_BT_GATTDB_CHARACTERISTIC_READ | SL_BT_GATTDB_CHARACTERISTIC_INDICATE | - SL_BT_GATTDB_CHARACTERISTIC_WRITE); -//add our characteristic to the service -sl_bt_gattdb_add_uuid128_characteristic(session, service, property, 0, 0, uuid_characteristic, - sl_bt_gattdb_fixed_length_value, 20, 20, &value, &characteristic); -//activate the new service -sl_bt_gattdb_start_service(session, service); -//activate the new characteristic -sl_bt_gattdb_start_characteristic(session, characteristic); -//store the handle of the characteristic for future reference -gattdb_my_data = characteristic; -//save changes and close the database editing session -sl_bt_gattdb_commit(session); -``` - ->**Note**: The handle returned while adding a service or characteristic is not always the final one. It is only valid until `sl_bt_gattdb_commit` is called. You can get the actual final handle with the API call `sl_bt_gatt_server_find_attribute()`. - -## Responding to the GATT Change Event - -1. Add the callback function that reacts to the GATT change. In this case, it prints out the content of the characteristic. - - ```C - void AttrValueChanged_my_data(uint8array *value) - { - uint8_t i; - for (i = 0; i < value->len; i++){ - app_log("my_data[%d] = 0x%x \r\n",i,value->data[i]); - } - app_log("\r\n"); - } - ``` - -2. Add the `sl_bt_evt_gatt_server_attribute_value_id` event to the switch case. - - ```C - case sl_bt_evt_gatt_server_attribute_value_id: - // Check if the event is because of the my_data changed by the remote GATT client - if ( gattdb_my_data == evt->data.evt_gatt_server_attribute_value.attribute ){ - // Call my handler - AttrValueChanged_my_data(&(evt->data.evt_gatt_server_attribute_value.value)); - } - break; - ``` - ->**Note**: If you edited the .btconf file, `gattdb_my_data` is defined in *gatt_db.h*. If you used the dynamic GATT API, `gattdb_my_data` is defined in the application as in the provided code snippet. - -Now you can rebuild the host application. See the build process with MinGW in [Building the NCP Host Examples on Windows](./03-ncp-host-development.md#building-the-ncp-host-examples-on-windows). - -## Testing - -1. Start the host application from the *\exe* folder. - -2. Once the PC is connected to WSTK (via UART), the WSTK starts advertising on Bluetooth. - -3. If you connect via tablet/phone you can write the newly created `my_data` characteristic in the GATT. For this, you can use the Simplicity Connect app provided by Silicon Labs. - -4. Browse to the `my_data` characteristic and write something to it. The data will be printed by the host application. - - ![my data characteristic](resources/an1259-my-data-characteristic.png) +# Adding New Attributes to the GATT Database + +This page describes how to add a custom Bluetooth service to the **NCP** example using the dynamic GATT API. The service added here has one characteristic to receive data. When the central device (tablet/phone) writes this characteristic, the peripheral (starter kit – NCP Target) forwards this data to the NCP Host. The NCP Host prints out the actual data to the PC console. + +![new service to NCP](resources/an1259-new-service-to-NCP-empty.png) + +To implement this application, you need to make these changes: + +- Modify the GATT database in the Host project + +- Handle the GATT change event (sl_bt_evt_gatt_server_attribute_value) in the Host project + +## Adding New Attributes Using the Configuration File + +Beginning with SDK version 3.3, the NCP host sample applications contains a .btconf file with a basic GATT configuration. This configuration can be edited with the GATT Configurator as described in [GATT Configurator User’s Guide for Bluetooth SDK v3.x](https://docs.silabs.com/bluetooth/latest/gatt-configurator-users-guide-ble-btmesh/). To be compatible with the code snippets, create a custom service and then add a custom characteristic with the following properties: + +- ID: my_data + +- Read, Write, Indicate + +- Value length: 20 bytes + +The output (gatt_db.c / gatt_db.h) is located in the autogen folder. These values will be used as parameters for the dynamic GATT APIs. The database will be created (that is, built on the NCP target with the dynamic GATT API) automatically in the initialization phase before the boot event is sent to the application. The application is still able update the GATT database with the dynamic GATT commands, as described in the next section. + +>**Note**: If your database contains included services, the included ones need to be defined before the ones including them. + +## Adding New Attributes Using the Dynamic GATT API + +The GATT database can be extended with the APIs provided by the Dynamic GATT Configurator component. For more details, see the Bluetooth API reference manual on [docs.silabs.com](https://docs.silabs.com/), section "GATT Database." + +In the code snippet below, the custom service and characteristic is added to the database. The service will be a primary service, defined with a 16-byte long UUID, and it will be advertised. + +The characteristic has the following properties: + +- Read, Write, Indicate + +- Valuelength: 20 bytes + +- Valuemax length: 20 bytes + +- 16-bytelong UUID + +The service and the characteristic can be added any time after the boot event was received, but adding them in the boot event handler is suggested. + +```C +uint8_t uuid_service[16] = {…} //define your 128bit service UUID, you can use a random number +uint8_t uuid_characteristic[16] = {…} //define your 128bit characteristic UUID + +//create a session for the database update +sl_bt_gattdb_new_session(&session); +//add our service to the database, as an advertised primary service +sl_bt_gattdb_add_service(session, sl_bt_gattdb_primary_service, SL_BT_GATTDB_ADVERTISED_SERVICE, 16, + uuid_service, &service); +//define the following properties: read, write, indicate +property = (SL_BT_GATTDB_CHARACTERISTIC_READ | SL_BT_GATTDB_CHARACTERISTIC_INDICATE | + SL_BT_GATTDB_CHARACTERISTIC_WRITE); +//add our characteristic to the service +sl_bt_gattdb_add_uuid128_characteristic(session, service, property, 0, 0, uuid_characteristic, + sl_bt_gattdb_fixed_length_value, 20, 20, &value, &characteristic); +//activate the new service +sl_bt_gattdb_start_service(session, service); +//activate the new characteristic +sl_bt_gattdb_start_characteristic(session, characteristic); +//store the handle of the characteristic for future reference +gattdb_my_data = characteristic; +//save changes and close the database editing session +sl_bt_gattdb_commit(session); +``` + +>**Note**: The handle returned while adding a service or characteristic is not always the final one. It is only valid until `sl_bt_gattdb_commit` is called. You can get the actual final handle with the API call `sl_bt_gatt_server_find_attribute()`. + +## Responding to the GATT Change Event + +1. Add the callback function that reacts to the GATT change. In this case, it prints out the content of the characteristic. + + ```C + void AttrValueChanged_my_data(uint8array *value) + { + uint8_t i; + for (i = 0; i < value->len; i++){ + app_log("my_data[%d] = 0x%x \r\n",i,value->data[i]); + } + app_log("\r\n"); + } + ``` + +2. Add the `sl_bt_evt_gatt_server_attribute_value_id` event to the switch case. + + ```C + case sl_bt_evt_gatt_server_attribute_value_id: + // Check if the event is because of the my_data changed by the remote GATT client + if ( gattdb_my_data == evt->data.evt_gatt_server_attribute_value.attribute ){ + // Call my handler + AttrValueChanged_my_data(&(evt->data.evt_gatt_server_attribute_value.value)); + } + break; + ``` + +>**Note**: If you edited the .btconf file, `gattdb_my_data` is defined in *gatt_db.h*. If you used the dynamic GATT API, `gattdb_my_data` is defined in the application as in the provided code snippet. + +Now you can rebuild the host application. See the build process with MinGW in [Building the NCP Host Examples on Windows](./03-ncp-host-development.md#building-the-ncp-host-examples-on-windows). + +## Testing + +1. Start the host application from the *\build\debug* folder. + +2. Once the PC is connected to WSTK (via UART), the WSTK starts advertising on Bluetooth. + +3. If you connect via tablet/phone you can write the newly created `my_data` characteristic in the GATT. For this, you can use the Simplicity Connect app provided by Silicon Labs. + +4. Browse to the `my_data` characteristic and write something to it. The data will be printed by the host application. + + ![my data characteristic](resources/an1259-my-data-characteristic.png) diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-host-app-CPC.png b/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-host-app-CPC.png new file mode 100644 index 0000000..8d47eeb Binary files /dev/null and b/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-host-app-CPC.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-target-app-CPC.png b/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-target-app-CPC.png new file mode 100644 index 0000000..d2fb199 Binary files /dev/null and b/sld596-bluetooth-network-coprocessor-mode/resources/Studio6-target-app-CPC.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-figure-4-8.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-figure-4-8.png index 4f1d190..f564bb7 100644 Binary files a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-figure-4-8.png and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-figure-4-8.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-launch-Bluetooth-NCP-Commander.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-launch-Bluetooth-NCP-Commander.png new file mode 100644 index 0000000..cb6bf17 Binary files /dev/null and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-launch-Bluetooth-NCP-Commander.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-host-app-generation.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-host-app-generation.png new file mode 100644 index 0000000..7644aaa Binary files /dev/null and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-host-app-generation.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-select-os.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-select-os.png new file mode 100644 index 0000000..cc33e3d Binary files /dev/null and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-studio6-select-os.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v10-bt-ncp-project.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v10-bt-ncp-project.png index b70f7b0..ce9dd07 100644 Binary files a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v10-bt-ncp-project.png and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v10-bt-ncp-project.png differ diff --git a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v14-connection-manager.png b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v14-connection-manager.png index f7e234f..dd43548 100644 Binary files a/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v14-connection-manager.png and b/sld596-bluetooth-network-coprocessor-mode/resources/an1259-v14-connection-manager.png differ