Telink Matter Developer Guide
Overview
Currently, Telink has several chips that support the Matter protocol. In this document, the TLSR9528A is used as an example to introduce how to use Matter.
Matter Introduction
Emergence of Matter
-
Challenges
The issue of "fragmentation" in IoT products not only troubles consumers and developers but also hinders the further development of smart home hardware products. Currently, the tech giants leading the development of IoT products each have their own independent smart home ecosystems, such as Amazon Alexa, Apple HomeKit, and Google Home.
-
For Consumers
When selecting smart products, consumers need to consider not only the product's functions, features and price,but also whether it is compatible with their existing home ecosystem. This creates difficulties in their selection process and inconvenience in usage.
-
For Businesses
Third-party developers must consider before developing which ecosystem their product needs to support to meet the needs of their target users. If developers are not content with limiting their product to a single ecosystem and want to meet the diverse needs of different consumers and expand their market share, they may need to modify existing devices to support more ecosystems or develop new devices that support multiple smart ecosystems. Both options can post significant challenges. On one hand, they have to spend more time and effort on software adaptation for different smart ecosystems; on the other hand, they may even need to modify the underlying hardware or peripheral design to meet the requirements of certain ecosystems.
Therefore, all parties hope to form a commonly accepted and followed "standard" to solve the above "fragmentation" issue, facilitating the development of smart home brands and manufacturers, and making it easier for consumers to choose. To meet this common need, many IoT ecosystem builders, including Amazon, Apple, and Google, joined forces with the Zigbee Alliance in December 2019 to announce the formation of the Connected Home over IP (CHIP) project working group, dedicated to creating a new smart home protocol based on an open-source ecosystem. In May 2021, as the Zigbee Alliance was renamed the Connectivity Standards Alliance, the project working group negotiated and formulated the draft of this local area network application layer standard protocol and renamed CHIP to Matter.
Matter Overview
Matter devices will operate at a unified application layer and rely solely on the TCP/IP and UDP protocols formed by the IPv6 standard in the transmission layer, thus being compatible with different physical media and data link standards. Since an IP network is a mesh structure, Matter will also exhibit a mesh topology. (composed of sub-networks of different communication technologies).
In the first version of the Matter protocol scheduled for official release this fall, it will initially support device-to-device communication over Ethernet, Wi-Fi, and Thread networks; and use Bluetooth Low Energy (BLE) technology as the entry channel for Matter devices to join the network, simplifying the configuration steps of Matter devices. The Thread protocol is based on IEEE 802.15.4 technology, and devices in its network cannot directly communicate with Wi-Fi or Ethernet devices. Therefore, a Thread border router needs to be added to the Matter topology to enable Matter devices in the Thread network to interconnect with devices in other networks. For example, a Matter device that only supports the Thread network can communicate with a device that only supports the Wi-Fi network (such as an iPhone) through a Border Router (such as HomePod Mini).
In the Matter network, there will be a unified data model and interaction model. The Matter protocol treats the network as a shared resource, without exclusive network ownership and access rights, allowing multiple different protocol networks to coexist in the same IP network group. In the past, two smart devices needed to be in the same physical network to communicate with each other, but the Matter protocol will build multiple virtual networks, allowing smart devices in different physical networks to communicate with each other. A virtual network here is a collection of Matter devices, called a Fabric. In practice, a Fabric often corresponds to a network formed by a smart ecosystem.
A physical device is called a Node (equivalent to an Accessory in HomeKit), and a Node can be added to one or more Fabrics. Under the Node, logical functional units called Endpoints represent different functional modules, such as Endpoint 1 and Endpoint 2 in the figure below representing different functional modules of an air conditioner; Endpoint 0 is a reserved root endpoint used to describe device characteristics. Endpoints use several Clusters (inherited from the Zigbee Cluster Library, ZCL) to represent specific functions, such as switches, wind power, temperature measurement, and temperature control. The interaction between Matter devices is completed through communication between an Endpoint of one device and an Endpoint of another device.
In addition, the network constructed by the Matter protocol has the following features:
-
Multi-Admin, the ability to support adding Matter devices to different ecosystems simultaneously, managed by administrators in different Fabrics, thus achieving broad compatibility.
-
Sharing Matter vendor and device information through the Distributed Compliance Ledger (DCL). Each ecosystem can query the information needed during Matter network provisioning, OTA, etc., from the DCL.
-
Allowing users to control local devices without connecting to the cloud.
-
Existing non-Matter smart devices also have the opportunity to be added to the Matter Fabric through Matter Bridge devices. The Matter Bridge device communicates with non-Matter devices, virtualizing non-Matter devices into corresponding Endpoints, just like a Node with multiple different functional Endpoints, allowing Matter devices in the Matter network to communicate with non-Matter devices.
Matter Functions
The Matter protocol mainly targets the smart home market, supporting the following types of devices:
-
Lighting devices such as lights and switches
-
Air handling devices such as heating and cooling
-
Security devices such as detectors and alarms
-
Access control devices such as access controls and door locks
-
Audio-visual entertainment devices such as speakers and TVs
-
Window covering devices such as windows and curtains
-
Network relay devices such as hotspots and bridges
With the development and evolution of the Matter protocol, more smart devices will be supported in the future.
The Future of Matter
The high attention Matter has received is not just because of its advanced concepts and standards but also due to the commitments of three smart home giants. At the inception of the Matter project, Amazon, Apple, and Google promised that devices using this protocol would be compatible with their ecosystems. After the launch of the Matter protocol, IoT product developers will be able to develop once and have products that support multiple ecosystem access protocols (such as Amazon Alexa, Apple HomeKit, and Google Home), greatly simplifying developers' work and enabling smart devices to seamlessly connect to any Matter-compatible smart ecosystem. Consumers will also find it easier to choose products without worrying about compatibility with their existing ecosystem.
Telink Matter Overview
Telink Semiconductor actively participates in the development of Matter device functions, testing and certification of Matter devices, and the interpretation of Matter standards in Chinese. As a provider of low-power, high-performance wireless connectivity SoC chip solutions, we have launched a Matter Over Thread solution and a Matter Over Wi-Fi solution based on the TLSR9 series chips, which can be used to develop Matter Thread and Matter Wi-Fi end devices.
Telink Matter Currently Supported Applications
Currently, Telink Matter supports the following examples:
1) connectedhomeip/example/lighting-app/telink
lighting-app bulb application
2) connectedhomeip/example/light-switch-app/telink
light-switch-app switch application
To make it easier for customers to experience the above applications, we provide pre-built lighting-app firmware, light-switch-app firmware and corresponding chip-tool tools, which can be found through the cloud drive address below:
https://drive.weixin.qq.com/s?k=AKwA0AfNAA8vmdyx0L
Repositories and Branches Used
The latest Docker Image is still being updated, which includes the Zephyr environment needed to compile Matter applications. View it for further information:
https://hub.docker.com/r/connectedhomeip/chip-build-telink
The custom branch telink_matter of Matter has been merged into the official master branch, so the following repository is available for users:
https://github.com/project-chip/connectedhomeip
Purpose of This Document
This document provides a complete guide to the Telink Matter solution, including environment setup, Matter device firmware building and burning, border router setup (including RCP building and burning), chip-tool building and usage, helping users understand Telink Matter related information and better experience the functions of Telink Matter applications.
Requirements
Required Hardware and Tools
1) Telink Evaluation Board as Matter device;
2) Telink Evaluation Board as RCP;
3) Raspberry Pi 4 as part of the border router, 4GB RAM version recommended;
4) SD Card for Raspberry Pi 4, at least 16GB;
5) Host PC with Ubuntu v20.04 LTS, used as a build machine and host for the Matter device;
6) Telink Programmer for burning the Matter device and RCP firmware;
7) Wi-Fi Router acting as a Wi-Fi access point;
TLSR9528 Evaluation Board Introduction
Button Functions
The four mechanical buttons on the TLSR9528 evaluation board are laid out and function as follows:
Button Number | Corresponding PIN | Function | Description |
---|---|---|---|
SW2 | PD2 | Factory Reset | Press button 1 three times to clear the current Thread network provisioning and return to an unconfigured state |
SW3 | PD6 | Trigger BLE Broadcast | Enter pairing mode, the device starts BLE broadcasting and becomes discoverable |
SW4 | PD7 | Light Control | For bulbs: allows manual ON/OFF control. For switches: controls the ON/OFF state of connected bulbs |
SW5 | PF6 | Form Thread Network | The device joins the Thread network with default configuration, for testing purposes only |
LED Status
White LED indicates the current network status of the device:
Status | Description |
---|---|
Short white flashes | Device not configured to a Thread network, Thread not enabled |
Frequent white flashes | Device configured, Thread enabled, device attempting to join Thread network |
Long white flashes | Device configured and joined Thread network as a child |
Red and Green LEDs indicate the light status:
-
On
Brightness 0 - 255 (maximum value)
-
Off
Connecting UART Module for Serial Output
The UART module helps us obtain serial debugging information from the Matter device. We can connect the pins as follows:
UART Module | TLSR9528 Evaluation Board |
---|---|
TXD | PB3(pin 1 of J3) |
RXD | PB2(pin 22 of J3) |
GND | GND(e.g.pin 3 of J15 or pin 23 of J17) |
Baud rate: 115200 Bits/second;
Data bits: 8;
Parity: None;
Stop bits: 1.
Power Supply Methods
1) Using USB Power
- Insert the jumper marked in the red box in the picture.
2) Using Built-in VBAT PINs
Without a USB cable, the TLSR9528 evaluation board can be powered using built-in PINs.
- Remove the jumper marked by the red box in the figure.
- Connect the VBAT pin of J17 to a 3.3V power supply.
- Ground the GND pin of J17.
TL3218X Evaluation Board Introduction
Button Functions
The four mechanical buttons on the TL3218X evaluation board have the following layout and function:
Button Number | Corresponding PIN | Function | Description |
---|---|---|---|
SW3 | PB3 | Factory Reset | Press button 1 three times to clear the current Thread network provisioning and return to an unconfigured state |
SW4 | PB5 | Trigger BLE Broadcast | Enter pairing mode, the device starts BLE broadcasting and becomes discoverable |
SW5 | PB6 | Light Control | For bulbs: allows manual ON/OFF control. For switches: controls the ON/OFF state of connected bulbs |
SW6 | PB7 | Form Thread Network | The device joins the Thread network with default configuration, for testing purposes only |
LED Status
White light indicates the current network status of the device:
Status | Description |
---|---|
Short white flashes | Device not provisioned to a Thread network, Thread not enabled |
Frequent white flashes | Device provisioned, Thread enabled, device attempting to join Thread network |
Long white flashes | Device provisioned and joined Thread network as a child |
Blue and Red LEDs indicate the light status:
-
On
Brightness 0 - 255 (maximum value)
-
Off
Connecting UART Module for Serial Output
The UART module helps us obtain serial debugging information from the Matter device. We can connect the pins as follows:
UART Module | TL3218X Evaluation Board |
---|---|
TXD | PE1(pin 4 of J7) |
RXD | PE0(pin 2 of J7) |
GND | GND(e.g.pin 1 of J8 or pin 37 of J9) |
Baud rate: 115200 Bits/second;
Data bits: 8;
Parity: None;
Stop bits: 1.
Power Supply Methods
1) Using Type-C Power
- Insert the jumper marked in the red box in the picture.
2) Using Built-in VBAT PINs
Without a USB cable, the TL3218X evaluation board can be powered using built-in PINs.
- Connect the VBAT pin to a 3.3V power supply.
- Ground the GND pin of the evaluation board.
TL7218X Evaluation Board Introduction
Button Functions
The four mechanical buttons on the TL7218X evaluation board have the following layout and function:
Button Number | Corresponding PIN | Function | Description |
---|---|---|---|
SW3 | PD5 | Factory Reset | Press button 1 three times to clear the current Thread network provisioning and return to an unconfigured state |
SW4 | PD4 | Trigger BLE Broadcast | Enter pairing mode, the device starts BLE broadcasting and becomes discoverable |
SW5 | PD7 | Light Control | For bulbs: allows manual ON/OFF control. For switches: controls the ON/OFF state of connected bulbs |
SW6 | PD6 | Form Thread Network | The device joins the Thread network with default configuration, for testing purposes only |
LED Status
White light indicates the current network status of the device:
Status | Description |
---|---|
Short white flashes | Device not provisioned to a Thread network, Thread not enabled |
Frequent white flashes | Device rovisioned, Thread enabled, device attempting to join Thread network |
Long white flashes | Device rovisioned and joined Thread network as a child |
Blue and Green LEDs indicate the light status:
-
On
Brightness 0 - 255 (maximum value)
-
Off
Connecting UART Module for Serial Output
The UART module helps us obtain serial debugging information from the Matter device. We can connect the pins as follows:
UART Module | TL7218X Evaluation Board |
---|---|
TXD | PB3(pin 5 of J6) |
RXD | PB2(pin 10 of J6) |
GND | GND(e.g.pin 38 of J8 or pin 38 of J9) |
Baud rate: 115200 Bits/second;
Data bits: 8;
Parity: None;
Stop bits: 1.
Power Supply Methods
1) Using Type-C Power
- Insert the jumper marked in the red box in the picture.
2) Using Built-in VBAT PINs
Without a USB cable, the TL7218X evaluation board can be powered using built-in PINs.
- Connect the VBAT pin of the evaluation board to a 3.3V power supply.
- Ground the GND pin of the evaluation board.
TLSR9118 Evaluation Board Introduction
Button Functions
The four mechanical buttons on the TLSR9118 evaluation board have the following layout and function:
Button Number | Corresponding PIN | Function | Description |
---|---|---|---|
SW7 | GPIO4 | Factory Reset | Press button 1 three times to clear the current Thread network provisioning and return to an unconfigured state |
SW9 | GPIO5 | Light Control | For bulbs: allows manual ON/OFF control. For switches: controls the ON/OFF state of connected bulbs |
SW2 | GPIO6 | Trigger BLE Broadcast | Enter pairing mode, the device starts BLE broadcasting and becomes discoverable |
SW1 | GPIO7 | Form Wi-Fi Network | The device joins the Wi-Fi network with default configuration, for testing purposes only |
LED Status
LED1 always on
LED2 indicates the current network status of the device:
Status | Description |
---|---|
LED2 short on and flashes | Device not provisioned into a Wi-Fi network, Wi-Fi not enabled |
LED2 frequent flashes | Device provisioned, device attempting to join Wi-Fi network |
LED2 long on and flashes | Device provisioned and joined Wi-Fi network |
LED3 indicates the status of the light:
-
On
Brightness 0 - 255 (maximum value)
-
Off
Connecting Virtual Serial Module For Serial Output
The TLSR9118 development board is equipped with a Type-C USB interface that can be used for serial connections and to obtain debugging information from Matter devices. Typically, this interface is recognized as a ttyUSB device.
Baud rate: 115200 Bits/second;
Data bits: 8;
Parity: None;
Stop bits: 1.
Power Supply Methods
1) Using Type-C Power
2) Using Built-in PINs to power
Without a USB cable, the TLSR9118 evaluation board can be powered using built-in PINs.
- Connect the VBUS pin of the evaluation board to a 5V power supply.
- Ground the GND pin of the evaluation board.
Experience the Implementation and Function of Matter
Environment Setup (Manual)
Install Zephyr Project Environment
Before proceeding with the following steps, perform an APT update and upgrade:
sudo apt update
sudo apt upgrade
(1) Install dependencies
wget https://apt.kitware.com/kitware-archive.sh
sudo bash kitware-archive.sh
sudo apt install --no-install-recommends git cmake ninja-build gperf \
ccache dfu-util device-tree-compiler \
python3-dev python3-pip python3-setuptools python3-tk python3-wheel xz-utils file \
make gcc gcc-multilib g++-multilib libsdl2-dev
Zephyr currently requires the following minimum versions of the main dependencies: CMake (3.20.0), Python3 (3.6), Devicetree compiler (1.4.6).
cmake --version
python3 --version
dtc --version
Before proceeding to the next step, please verify the installed versions on your system. Otherwise, switch the APT image to a stable and up-to-date one, or manually update these dependencies.
(2) Install west
pip3 install west
echo 'export PATH=~/.local/bin:"$PATH"' >> ~/.bashrc
source ~/.bashrc
Ensure that ~/.local/bin is in the $PATH
environment variable.
(3) Get Zephyr source code
west init ~/zephyrproject
cd ~/zephyrproject
west update
west blobs fetch hal_telink
west zephyr-export
Running west init and west update in mainland China to get the Zephyr source code may take extra time, and some projects may not update from external servers.
Please look for alternative methods to download the latest source code.
(4) Install additional Python dependencies required by Zephyr
pip3 install --user -r ~/zephyrproject/zephyr/scripts/requirements.txt
(5) Install toolchain
Download the Zephyr toolchain to a local directory, which may take extra time in mainland China.
Execute the following command to download Zephyr SDK v0.17.0:
wget https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.17.0/zephyr-sdk-0.17.0_linux-x86_64_minimal.tar.xz
Verify the downloaded toolchain archive.
wget -O - https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.17.0/sha256.sum | shasum --check --ignore-missing
Add execution permission.
chmod +x zephyr-sdk-0.17.0_linux-x86_64_minimal.tar.xz
Extract the archive to the specified path.
tar xvf zephyr-sdk-0.17.0_linux-x86_64_minimal.tar.xz ~/zephyr-sdk-0.17.0
You can download and install the Zephyr SDK in the following recommended paths:
$HOME/zephyr-sdk[-x.y.z]
$HOME/.local/zephyr-sdk[-x.y.z]
$HOME/.local/opt/zephyr-sdk[-x.y.z]
$HOME/bin/zephyr-sdk[-x.y.z]
/opt/zephyr-sdk[-x.y.z]
/usr/zephyr-sdk[-x.y.z]
/usr/local/zephyr-sdk[-x.y.z]
[-x.y.z] is the version of the SDK you downloaded, for example, -0.16.1.
Note
After installation, the SDK folder cannot be moved.
Install only the riscv64 toolchain.
cd ~/zephyr-sdk-0.17.0
./setup.sh -t riscv64-zephyr-elf -h -c
To download Zephyr Full SDK v0.17.0:
wget https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.17.0/zephyr-sdk-0.17.0_linux-x86_64.tar.xz
wget -O - https://github.com/zephyrproject-rtos/sdk-ng/releases/download/v0.17.0/sha256.sum | shasum --check --ignore-missing
tar xvf zephyr-sdk-0.17.0_linux-x86_64.tar.xz ~/zephyr-sdk-0.17.0
cd zephyr-sdk-0.17.0
./setup.sh -t riscv64-zephyr-elf -h -c
(6) Verify installation completion
Before proceeding to install the Matter project environment, build the Hello World example to verify the Zephyr project environment installation.
cd ~/zephyrproject/zephyr
west build -p auto -b <build_target> zephyr/samples/hello_world -d build_helloWorld
Note
build_target is the name of the development board you intend to use, e.g. tlsr9518adk80d
, tlsr9528a
, tl3218x
or tl7218x
.
Use the west build
command in the Zephyr root directory folder to build the hello_world example. After the build is complete, you can find a file named zephyr.bin in the build_helloWorld/zephyr folder.
(7) Add Zephyr environment script to Shell
Note
Please append the Zephyr environment configuration script to ~/.bashrc
, otherwise you may encounter west build
errors in subsequent builds.
echo "source ~/zephyrproject/zephyr/zephyr-env.sh" >> ~/.bashrc
Then execute the following command to update the shell environment immediately:
source ~/.bashrc
(8) Add Telink Zephyr remote repository and pull the specified commit source code.
cd ~/zephyrproject/zephyr
git remote add telink https://github.com/telink-semi/zephyr
git fetch telink develop
git checkout develop_v3.3
cd ..
west update
west blobs fetch hal_telink
(9) (Optional) If you want to switch to another branch or commit after completing all the above steps, just execute the following commands:
git fetch telink
git checkout <your_target_branch_or_commitid>
cd ..
west update
west blobs fetch hal_telink
Obtaining Matter Source Code
This section introduces the steps to get the specified commit on the Matter master branch, matching the Zephyr code pulled in the previous section.
(1) Install dependencies:
sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \
libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev \
python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev
(2) Clone the Matter project:
Clone the Matter project to a local directory, such as /home/${YOUR_USERNAME}/workspace/matter.
git clone https://github.com/project-chip/connectedhomeip
Where ${YOUR_USERNAME} is your username folder
(3) Switch to master branch (optional, specified commit) and update submodules.
cd ./connectedhomeip
git checkout master
./scripts/checkout_submodules.py --platform telink,linux
(4) Run the bootloader
Execute bootstrap to prepare the Matter environment. The first run usually takes a long time.
source scripts/bootstrap.sh
Note
Every time you switch commit or change the environment, you may need to rerun the bootloader.
This step will generate a hidden folder called .environment in the Matter root directory connectedhomeip. In mainland China, it may take extra time or encounter failures.
If there are any issues with the Matter build environment, you can try:
1) Remove the environment (in the Matter project root directory):
rm -rf .environment
2) Redo the bootloader:
source scripts/bootstrap.sh
(5) (Optional) If you need to switch to another branch or commit, execute the following command
git fetch origin
git checkout <your_target_branch_or_commitid>
git submodule update --init --recursive
rm -rf .environment
source scripts/bootstrap.sh
You can find more information here: https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/BUILDING.md
Compile Firmware
Flash Memory Layout
For the TLSR9528A using 2MB flash firmware, the flash partition is as follows (the rest of the flash partition files are in the same directory):
...
&flash {
reg = <0x20000000 0x200000>;
/delete-node/ partitions;
partitions {
compatible = "fixed-partitions";
#address-cells = <1>;
#size-cells = <1>;
boot_partition: partition@0 {
label = "mcuboot";
reg = <0x00000000 0x13000>;
};
slot0_partition: partition@13000 {
label = "image-0";
reg = <0x13000 0xec000>;
};
factory_partition: partition@ff000 {
label = "factory-data";
reg = <0xff000 0x1000>;
};
dac_keypair_partition: partition@100000 {
label = "dac-keypair";
reg = <0x100000 0x1000>; //store dac and key pair.
};
descriptor_partition: partition@101000 {
label = "sboot-descriptor";
reg = <0x101000 0x2000>;
};
storage_partition: partition@103000 {
label = "storage";
reg = <0x103000 0xf000>;
};
slot1_partition: partition@112000 {
label = "image-1";
reg = <0x112000 0xec000>;
};
vendor_partition: partition@1fe000 {
label = "vendor-data";
reg = <0x1fe000 0x2000>;
};
};
};
...
Note
The information in the table is for reference only, please download the latest Matter code to confirm the most accurate memory usage.
Device Configuration
If one or more devices are configured as FTD (Full Thread Devices), such as bulbs, device-to-device communication can occur without the need for a border router.
Note
By default, all devices are configured as MTD (Minimal Thread Device).
The configuration file for the application is located:
examples/app/telink/prj.conf
MTD configuration example:
## OpenThread configs
CONFIG_OPENTHREAD_MTD=y
CONFIG_OPENTHREAD_FTD=n
FTD configuration example:
## OpenThread configs
CONFIG_OPENTHREAD_MTD=n
CONFIG_OPENTHREAD_FTD=y
Compiling
Do the following in the Matter root directory, or in /root/chip if using a Docker image:
(1) Launch the Matter environment:
source scripts/activate.sh
(2) Go to the example directory:
cd examples/*app*/telink
app:lighting-app or light-switch-app
(3) If a build already exists, delete the directory generated during the original build:
rm -rf build/
(4) Build example:
west build -b <build_target>
build_target is the name of the development board you intend to use, for example, tlsr9518adk80d
, tlsr9528a
, tl3218x
, tl7218x
, or tlsr9118bdk40d
.
And, you need to specify -DFLASH_SIZE
in the compile command according to the flash size of the board you are using, for example, if you are using a B92 board with 2MB flash, the compile command will be:
west build -b tlsr9528a -- -DFLASH_SIZE=2m
You can find the target build file named zephyr.bin in the build/zephyr directory.
Note
Please make sure that the gn
build tool is installed and configured on your PC, otherwise a build error may occur. Also, please remember to execute zephyr-env.sh
under the zephyr project path, otherwise, a west build
does not exist error may occur.
Compiling chip-tool
(1) Start the Matter environment:
source scripts/activate.sh
(2) Go to the example directory:
cd examples/chip-tool
(3) If a build already exists, delete the directory generated during the original build:
rm -rf out/
(4) Build chip-tool
gn gen out
ninja -C out
The completed build can be found at {MATTER_CHIP_TOOL_EXAMPLE_FOLDER}/out/chip-tool.
For more information related to chip-tool, click the following link to check: https://github.com/project-chip/connectedhomeip/blob/master/examples/chip-tool/README.md
Firmware Burning
Matter Over Thread Device
For Matter Over Thread devices, the implementation of this burn-in description applies to both Windows and Ubuntu platforms. Taking the B92 EVB as an example, the hardware that needs to be prepared in order to burn in a piece of B92 EVB are at least:
1) A B92 EVB evaluation board;
2) A Burning EVk burner;
3) Two Mini-USB cables;
If you need to burn multiple B92 EVB evaluation boards at the same time, please prepare multiple sets of hardware. In addition, a USB Hub with sufficient interfaces may be required.
(1) BDT and LinuxBDT Downloading
BDT is a burning and debugging tool that can be obtained from the following link:
Windows 10: http://wiki.telink-semi.cn/tools_and_sdk/Tools/BDT/BDT.zip
Ubuntu 20.04: http://wiki.telink-semi.cn/tools_and_sdk/Tools/BDT/LinuxBDT.tar.bz2
(2) BDT Connection Method
Please follow the diagram below for hardware connection. The diagram shows the status after completing the hardware connection:
Note
Be sure to use the default jumper configuration.
(3) Using BDT on Windows Platform
1) Connect the burner to the computer's USB port using a USB cable.
2) Download the BDT burning software, extract it to a local folder, and double-click the executable file "Telink BDT.exe". If everything is normal, you can see the following window display, and the device information of the connected burner can be seen in the system title bar (see the red box in the figure).
3) Select the corresponding chip.
-
If the
TLSR9528
chip is used, selectB92_3V3
. -
If the
TL3218X
chip is used, selectTL321X
. -
If the
TL7218X
chip is used, selectTL721X
.
4) Click the "SWS" button in the toolbar. If you see the information in the figure below, it means that all hardware connections are correct.
5) Set the size of the Flash erase area. Click the "Setting" button in the toolbar. In the pop-up "Setting" window, you can see that the default size of the Flash erase area is 512kB.
Set the size of the Flash erase area to "2040", as shown below:
Note
For the TLSR9528 development board with external 2MB Flash, the last 8kB of Flash space is reserved for saving important SoC information, so a maximum of 2040 KB of Flash area can be erased.
6) Click the Erase button in the toolbar and wait for the Flash erase operation to complete.
7) Select the BIN file to be burned. Click the Open sub-menu in the File menu, and select the BIN file to be burned in the pop-up file selection dialog box. The selected BIN file will be displayed in the status bar at the bottom.
8) Click the Download button in the toolbar and wait for the Flash burning to complete.
For more detailed descriptions of the commands, refer to the documentation in the BDT\doc
folder.
(4) Frequently Asked Questions about the BDT on Windows Platform
1) After the burner is inserted into the computer, it can be recognized correctly by Windows Device Manager, but the burner tool software does not recognize it, i.e., you can't see the device information of the burner in the title bar of the system (see Figure 3.2). Please check whether the computer is using AMD platform processor, change a computer with Intel platform processor and try again.
2) The most common problem is that after clicking the SWS button in the toolbar, the error message in the figure below appears:
There are two main reasons:
-
Hardware connections are incorrect. Please double-check all hardware connections by referring to the previous instructions to make sure there are no missing or incorrect connections.
-
The burner firmware version is too low. Follow the steps below to check the version of the burner firmware:
1) Click the Upgrade submenu under the Help menu.
2) In the Upgrade Evk window that pops up, click the Read FW version button. The firmware version number of the burner will be displayed in the Firmware Version field next to it, as shown in the figure below. If the firmware version number is too low, it can be confirmed that the communication error is caused by the low firmware version. Please continue with the following steps to complete the firmware upgrade.
3) Click the Load... button in the window, find the latest burner firmware in the fw subdirectory of the config directory in the BDT tool directory, as shown in the following figure for the Firmware_v4.4.bin file.
4) Click the Upgrade button to complete the burner firmware upgrade.
5) Plug and unplug the burner's USB cable to re-power up the burner.
(5) LinuxBDT on Ubuntu Platform Step by Step
On Ubuntu 20.04, open a terminal and download LinuxBDT
.
wget https://wiki.telink-semi.cn/tools_and_sdk/others/Telink-BDT-Linux-X64-V1.6.4.zip
Extract the Telink-BDT-Linux-X64-V1.6.4.zip
downloaded locally:
unzip Telink-BDT-Linux-X64-V1.6.4.zip
Open the linux_release
folder and use the graphical burn debugging tool bdt_gui
or the command line bdt
to manipulate Burning EVK to burn the B92 EVB.
The usage of bdt_gui
is similar to that of BDT.exe on the windows platform, so the following focuses on the steps to use the command line bdt
.
1) Connect the burner to the USB port of the computer with a Mini-USB cable
2) Test whether the connection between Burning EVK and the destination board B92 EVB is normal or not
Go to the root directory of the burning tool LinuxBDT
and execute the following command.
./bdt b92 sws
You can view the connected burner and the B92 EVB as shown below:
3) Activate MCU
When there is firmware running on the B92 EVB, erasing or burning directly with the Burning EVK burner may result in a "Swire err!" error. To avoid similar errors, execute the following command to activate the MCU first.
./bdt b92 ac
4) Erase Flash Sector
In order to avoid that the size occupied by the old firmware is larger than the new firmware, resulting in the existence of previous data residue on the flash after the new firmware is brushed in, please execute the following erase command first. If it is in unlock state, you need to unlock it first, otherwise the erase fails.
./bdt b92 wf 0 -s 2040k -e -f
-
MCU Type --
B92
-
Optional Command --
wf
(for write flash) -
Starting address to be erased --
0
-
Optional Command --
-s
(Specifies the sector size to be erased) -
The sector size to be erased --
2040k
(64k, 128k, 256k, 512k...) -
Optional Command --
-e
(erase flash) -
Optional Command --
-f
(unlock flash)
Wait for about tens of seconds, and when the erase is successful, it will show:
5) Download firmware to MCU's Flash
./bdt b92 wf 0 -i ~/Lighting_B92.bin
-
MCU Type--
B92
-
Optional Command --
wf
(for write flash) -
Starting address to be written to --
0
-
Optional Command --
-i
(Specify the firmware to be written to) -
Path to the firmware to be written to -- such as
Lighting_B92.bin
Execute the above command to flash the selected firmware into the flash, and the output will be as follows after success:
6) Reset MCU
./bdt b92 rst -f
-
MCU Type--
B92
-
Optional Command --
rst
(for reset) -
Optional Command --
-f
(for Flash or OTP)
The output after successful use of the above reset command is as follows:
After resetting the B92 EVB evaluation board, the entire MCU will be re-powered and will then start running the firmware that has just been burned.
For a more detailed description of the commands, refer to the documentation in the LinuxBDT/doc
folder.
Matter Over Wi-Fi Device
(1) Hardware Connection Method
1) You need to prepare the following hardware.
Order | Name | Number |
---|---|---|
1 | Telink W91 development board | 1 |
2 | Plastic Antenna | 1 |
3 | USB线 Cable (USB-C/USB to USB-C) | 1 |
2) Connect the W91 development board to the computer via the USB-C/USB port. The development board uses the USB-C interface, and a single USB cable can complete the connection.
To view the device's logs, set the baud rate to 115200
Note
Some USB-C ports cannot transfer data, please connect the device directly to the computer.
3) You will need to connect the jumper as shown below.
(2) Burning Procedure
1) Make sure you have the following installation packages ready.
2) In the installation directory, select sctool_gui.exe
and start Telink Flash Tool
:
3) Set the serial port and baud rate:
Com Port
is used to select the correct UART port for the IoT device, andBaudRate
sets the communication rate of the port, ranging from 115200 to 2M.- Select the appropriate
Com Port
and setBaudRate
to 2000000 as shown below:
Note
If the correct Com Port
is not detected, you may need to install the CP210x driver.
4) Set the Map
file.
- Open
Map
path:
-
Create a new
map
file and open it in Notepad. Modify theoffset
,size
andenable
parameters. Such as:- `offset = 0x80000000` - `size = 0x3D0900` - `enable = 1`
-
Name the file
zephyr.map
and select thebin
file you want to burn.
5) Erase operation:
- As shown below, click
Erase
, then clickStart
, and confirm the erase status at the bottom:
6) Burning
- Follow these steps: Click Program, then click Start. When the program is complete, the message "Operation completed successfully" will appear, click OK.
Border Router Configuration
Hardware and Firmware Required for Border Router
OTBR border router needs to consist of the following two components:
(1) Raspberry Pi 4: Raspberry Pi 4, 4GB RAM version recommended.
The Raspberry Pi prebuilt image can be found in the cloud drive below:
https://drive.weixin.qq.com/s?k=AKwA0AfNAA8wYik1M0
The user name of the preconfigured image is pi and the password is raspberry. (pi: raspberry)
(2) Radio Co-Processor: RCP is responsible for Thread communication and is implemented by a TLSR9528A evaluation board.
The RCP firmware is also in the cloud drive address above:
- b92-zephyr-rcp-usb-cdc.bin -- for B92 dongle, USB connection
Raspberry Pi Image Burning For Border Router
Raspberry Pi images can be burned under Windows with balenaEtcher as follows:
(1) Download balenaEtcher, here is the download address:
https://github.com/balena-io/etcher/releases
(2) Download the required version, unzip it and run balenaEtcher.exe.
(3) Insert the Mirco SD card into the card reader and then insert the card reader into the Windows computer.
Note
Please make sure the capacity of the Mirco SD card used is 16G or above.
(4) In balenaEtcher's interface, click Burn from file and select rpi_ot_br_posix.iso.
(5) Click Select Disk Destination to select the drive letter where the Micro SD card is located.
(6) Click Burn now!, wait for the image writing to complete, you can see the following interface after completion.
How the Raspberry Pi Connects to the RCP
Depending on the hardware used as the RCP, the connection between the Raspberry Pi and the RCP is different.
B92 Dongle as RCP
If you are using the B92 dongle as the RCP, simply connect the B92 dongle to the Raspberry Pi via USB after making the following configurations.
+ OTBR_AGENT_OPTS="-I wpan0 -B eth0 spinel+hdlc+uart:///dev/ttyACM0 trel://eth0"
- OTBR_AGENT_OPTS="-I wpan0 -B eth0 spinel+hdlc+uart:///dev/ttyAMA1?uart-flow-control trel://eth0"
Thread Network Establishment and Provisioning via BLE
Build a Thread Network and Get Dataset
(1) Enter the IP address of the Raspberry Pi in the browser, click the Form button, the default settings do not need to be changed, click FORM to establish the Thread network.
(2) You can check the status under Status after the Thread network is built.
(3) Get DATASET. please login to Raspberry Pi by SSH (username in the preconfigured image: pi, password: raspberry) and execute the following command:
$sudo ot-ctl dataset active -x
DATASET is a string of hexadecimal characters of the form similar to the following, save it.
Note
Each time a new Thread network is formed, the DATASET above will be regenerated. Even if the parameters set for each Thread network generation are the same, the portion between...0708fd0b448cf7918bcf051000...is different.
Network Configuration Procedure
(1) Check the status of the network connection between the host computer and the Raspberry Pi before performing the network configuration on the host computer.
-
If the host and the Raspberry Pi are forwarded by a router with a firewall, temporarily disable the firewall on the router, especially its function of disabling port listening, port scanning, and so on.
-
If you use the carrier's fiber modem as a router, it may result in an mDNS service undiscoverable error. Try connecting the host computer directly to the Raspberry Pi with a network cable using a different router that only has DHCP service enabled.
-
Ensure that the host is a standalone Ubuntu host; if a virtual machine such as VirtualBox on Windows is used as the host, it will need to be provided and configured with an additional Bluetooth adapter.
(2) Check that the Matter firmware version matches that of the chip-tool.
The same Zephyr environment is required to compile the firmware for the Matter device and the chip-tool, otherwise errors will occur when doing the configuration.
Note
If you want to use your own builds of chip-tool and Matter device firmware, ensure that they are built using the same connectedhomeip project directory of commit to avoid compatibility issues.
(3) For Matter Over Thread devices, configure the following commands in a shell on the host:
./chip-tool pairing ble-thread ${NODE_ID} hex:${DATASET} ${PIN_CODE} ${DISCRIMINATOR}
For Matter Over Wi-Fi devices, configure the following commands in a shell on the host:
./chip-tool pairing ble-Wi-Fi ${NODE_ID} ${Wi-Fi_SSID} ${Wi-Fi_PASSWORD} ${PIN_CODE} ${DISCRIMINATOR}
Note
To run chip-tool you need to exit the image and check the execution permission of chip-tool.
NODE_ID can be any non-zero value that has not been used since the initialization of the RCP and will be used by chip-tool to manipulate a specific Matter device.
DATASET is the string obtained on the Raspberry Pi.
Wi-Fi_SSID is the Wi-Fi name.
Wi-Fi_PASSWORD is the Wi-Fi password.
Example:
(4) After the Matter device is powered up, the white light blinks and enters the BLE broadcast state. Entering the above command in the shell on the host and running it will cause the Matter device to start pairing and network distribution with the border router where the RCP is located.
This process will continue for a while, and if all goes well and the Matter device joins the Thread network, you will be able to see a message similar to the one below from the host's shell:
Control with chip-tool
After the network provisioning succeeded, the Matter device can be controlled using chip-tool, and several of the main control commands are listed below.
Switch the Light On and Off
./chip-tool onoff command_name [param1 param2 ...]
-
command_name is the name of the command, here switch lights can be used on, off and toggle
-
[param1 param 2 ...] are the multiple parameters used, in this case the node ID
<node_id>
and the endpoint ID<endpoint_id>
are used for switching the light on and off. -
<node_id>
is the node ID used by the previous device for network provisioning, which can be represented by a shell variable like ${NODE_ID}. -
<endpoint_id>
is the ID of the endpoint that implements the OnOff Cluster
Example of the light on command:
./chip-tool onoff on ${NODE_ID} 1
Example of the light off command:
./chip-tool onoff off ${NODE_ID} 1
Example of the light toggle command:
./chip-tool onoff toggle ${NODE_ID} 1
Viewing the Light Status
The standard command to read attribute is:
./chip-tool onoff read attribute-name [param1 param2 ...]
-
attribute-name is the name of the attribute to be read
-
[param1 param 2 ...] are the multiple parameters used
Example of a command to read the light status:
./chip-tool onoff read on-off ${NODE_ID} 1
-
Attribute name is on-off
-
The two parameters here are the node ID and the endpoint ID
View Brightness
Again use the command to read the attribute, the standard command to read the attribute is:
./chip-tool onoff read attribute-name [param1 param2 ...]
-
attribute-name is the name of the attribute to be read
-
[param1 param 2 ...] are the multiple parameters used
Example of a command to read the brightness attribute:
./chip-tool levelcontrol read current-level ${NODE_ID} 1
-
The attribute name is current-level
-
The two parameters here are the node ID and the endpoint ID
Modify Brightness
The standard command is:
./chip-tool levelcontrol move-to-level <level> <transition_time> <option_mask> <option_override> <node_id> <endpoint_id>
-
<level>
is the brightness level -
<transition_time>
is the transition time -
<option_mask>
is option mask -
<option_override>
is option override -
<node_id>
is the node ID that was used when the device was previously network provisioned -
<endpoint_id>
is the ID of the endpoint that implemented the LevelControl Cluster
Example command to change the brightness:
./chip-tool levelcontrol move-to-level 32 0 0 0 ${NODE_ID} 1
Connecting Light and Switch
For a light switch and a lighting bulb commissioned into the same Matter network, binding can be achieved through the following steps.
(1) Use chip-tool to provision the Access Control List (ACL) to the Access Control Cluster. Add appropriate per-device ACL entries for each lighting bulb. Execute the following command:
./chip-tool accesscontrol write acl <acl_data> <node_id> <endpoint_id>
-
<acl_data>
is ACL data formatted as a JSON array. -
<node_id>
is the ID of the node to receive the ACL. -
<endpoint_id>
is the ID of the endpoint that implements the accesscontrol Cluster.
Example command:
./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": [<light-switch-node-id>], "targets": [{"cluster": 6, "endpoint": 1, "deviceType": null}, {"cluster": 8, "endpoint": 1, "deviceType": null}]}]' <lighting-node-id> 0
In the above command:
-
<lighting-node-id>
is the node ID that was previously used by bulb device for networking, which can be represented by a shell variable like ${NODE_ID}. -
<light-switch-node-id>
is the node ID that was used by the switching device for networking, and needs to be expressed as a number here. -
{"fabricIndex": 1, "privilege": 5, "authMode": 2, ‘subjects’: [112233], "targets": null} is the access control list for communicating with chip-tool.
-
{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [
<light-switch-node-id>
], "targets": [{"cluster": 6, "endpoint": 1, "deviceType": null}, {"cluster": 8, "endpoint": 1, "deviceType": null}]} is a bound access control list(cluster NO.6 is On/Off cluster,cluster NO.8 is Level Control cluster).
This command adds permission to the lighting application device, allowing it to receive commands from the switching device.
(2) Add a binding table to the switch to notify device endpoints:
./chip-tool binding write binding <binding_data> <node_id> <endpoint_id>
-
<binding_data>
is the binding data formatted as a JSON array. -
<node_id>
is the ID of the node to receive the binding. -
<endpoint_id>
is the ID of the endpoint that implements the binding Cluster.
Command example:
#### if there is only one lighting device
./chip-tool binding write binding '[{"fabricIndex": 1, "node": <lighting-node-id>, "endpoint": 1, "cluster": 6}]' <light-switch-node-id> 1
#### if there is more than one lighting device, add all nodeid
./chip-tool binding write binding '[{"fabricIndex": 1, "node": <lighting-node-id_1>, "endpoint": 1, "cluster": 6}, {"fabricIndex": 1, "node": <lighting-node-id_2>, "endpoint": 1, "cluster": 6}]' <light-switch-node-id> 1
In the above command:
-
<light-switch-node-id>
is the node ID that was previously used by the switching device for networking, which can be represented by a shell variable like ${SWITCH_NODE_ID}. -
<lighting-node-id>
is the node ID previously used by the bulb device for networking, it needs to be expressed in numbers here, if there is more than one bulb devices, add the node IDs used by all the bulb devices in turn in [] according to the example. -
{"fabricIndex". 1, "node". <lighting-node-id>, "endpoint". 1, "cluster". 6}
is the binding On/Off Cluster.
Experience the OTA Function
Enable the OTA Mmodule
The OTA module is enabled by default only in the ota-requestor-app example, to enable the OTA module in other Telink Matter examples, you need to follow the steps below:
- Set "CONFIG_CHIP_OTA_REQUESTOR=y" in the corresponding
prj.conf
configuration file.
After enabling the OTA module with the above configuration, compile to get the firmware:
-
zephyr.bin - the bin file burned to the development board
-
zephyr-ota.bin - bin file for OTA Provider
All bin files have the same SW version. For testing OTA, "zephyr-ota.bin" should have a higher SW version than the base SW. Set "CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2" in the corresponding prj.conf
configuration file.
OTA Usage
(1) Building Linux OTA Provider
./scripts/examples/gn_build_example.sh examples/ota-provider-app/linux out/ota-provider-app chip_config_network_layer_ble=false
(2) Running Linux OTA Provider
./chip-ota-provider-app -f zephyr-ota.bin
The zephyr-ota.bin here is the firmware to be upgraded.
(3) Open another terminal and use chip-tool to prepare the Linux OTA Provider.
./chip-tool pairing onnetwork ${OTA_PROVIDER_NODE_ID} 20202021
In this command:
- ${OTA_PROVIDER_NODE_ID} is the node id of the Linux OTA Provider, similar to the NODE_ID of the lighting-app, which should be a non-zero value that has not been used before.
(4) Configure the ACL for ota-provider-app to allow access
./chip-tool accesscontrol write acl '[{"fabricIndex": 1, "privilege": 5, "authMode": 2, "subjects": [112233], "targets": null}, {"fabricIndex": 1, "privilege": 3, "authMode": 2, "subjects": null, "targets": null}]' ${OTA_PROVIDER_NODE_ID} 0
- The ${OTA_PROVIDER_NODE_ID} here is the node id of the Linux OTA Provider.
(5) Use chip-tool to notify ota-provider-app to start the OTA process.
./chip-tool otasoftwareupdaterequestor announce-otaprovider ${OTA_PROVIDER_NODE_ID} 0 0 0 ${DEVICE_NODE_ID} 0
In this command:
-
${OTA_PROVIDER_NODE_ID} is the node id of the Linux OTA Provider.
-
${DEVICE_NODE_ID} is the node id of the paired device
How to Develop Based on/Utilizing Open Source SDK on Github
Architecture
-
Application: contain the business logic for a particular Matter device and serve as the interface for user interaction
-
ZCL Data Model: a data modeling layer that connects the application to its surroundings, drawing on the ZCL (ZigBee Cluster Library) data format in Matter
-
Matter Library: responsible for communication of Matter information, encryption/decryption, interaction with data models, network provisioning management, etc.
-
Matter Platform Layer: connect the Matter software library to specific hardware platform
-
Zephyr RTOS: provide a real-time operating system environment for running Matter applications
-
Zephyr Bluetooth Subsystem: implement the BLE protocol in the Zephyr environment
-
HCI Driver: A Telink-provided Zephyr-compatible driver that interfaces with hardware to enable BLE communication
-
Zephyr Thread Subsystem: implement OpenThread function, allowing Thread-based communication within the Zephyr ecosystem
-
IEEE802154 Driver: a Telink-provided Zephyr-compatible driver used by OpenThread to manage communications at the IEEE 802.15.4 level
-
RF driver: RF driver provided by Telink to facilitate communication between Zephyr OpenThread and BLE.
Data Model
Here is the introduction of the Matter data model using the example of a bulb device with the function of light switching and brightness adjusting.
-
Node indicates a physical device, in this case a bulb device is a node.
-
Endpoint represents a logical functional unit of a device class, and communication is accomplished by the interaction of the local endpoints with the endpoints on the device. Each node has many endpoints, and in each endpoint there are many Clusters, which describe the function of the endpoint. The figure shows a bulb as an example. Endpoint 0 is required to be reserved to provide some basic functionality of the entire Matter node, such as Basic Information Cluster (provides some basic information about the node, such as firmware version, manufacturer, etc.), Access Control Cluster (allows to configure access control list for this node), Network Commissioning Cluster (allows to provision into the network on this node, e.g. Wi-Fi, Ethernet, Thread network). In Endpoint 1 there are two Clusters, On/Off and Level Control, which together comprise the functionality of Endpoint 1.
-
Cluster is used to realize specific functions, and different Clusters can be combined to realize different functions. The two Clusters in the figure: On/Off to realize the function of switching on/off the light, and Level Control to realize the function of adjusting the brightness. There are some attributes, commands and events defined in Cluster.
-
Cluster uses a Client/Sever communication model. Attributes are usually at the Server, describing the attributes of the device, such as the state of the light on/off, the brightness of the lights, and so on.
-
Client and Server can control each other by preset commands, usually in the mode of Client initiating request and Server answering. For example, On/Off Cluster uses On command to control the light on and Off command to control the light off. And Level Control Cluster also has commands such as MoveToLevel and Move.
-
In some cases, when an attribute on the Server changes, the Server will actively notifies the Client via an Event in order to synchronize the state.
Code Logic and Highlight Source Code
Initialization Function
The initialization in AppTaskCommon::InitCommonParts(void) can be roughly divided into 3 parts.
The first part of the code is as follows, which mainly focuses on hardware related initialization. The InitCommonParts(void) function prints out the software version information at the beginning, then initializes the LED used to display the system status, followed by the initialization of the PWM and buttons, and finally the initialization of the function button timer.
CHIP_ERROR AppTaskCommon::InitCommonParts(void)
{
...
CHIP_ERROR err;
LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING);
/* if use user mode ,should disable the hardware init to avoid conflict*/
##if APP_LIGHT_USER_MODE_EN
##if INDEPENDENT_FACTORY_RESET_BUTTON
IndependentFactoryReset(); // Open the factory_reset button separately.
##endif
##else
InitLeds();
UpdateStatusLED();
InitPwms();
InitButtons();
##endif
// Initialize function button timer
k_timer_init(&sFactoryResetTimer, &AppTask::FactoryResetTimerTimeoutCallback, nullptr);
k_timer_user_data_set(&sFactoryResetTimer, this);
...
}
The second part of the code is as follows:
CHIP_ERROR AppTask::Init()
{
...
// Initialize CHIP server
##if CONFIG_CHIP_FACTORY_DATA
ReturnErrorOnFailure(mFactoryDataProvider.Init());
SetDeviceInstanceInfoProvider(&mFactoryDataProvider);
SetDeviceAttestationCredentialsProvider(&mFactoryDataProvider);
SetCommissionableDataProvider(&mFactoryDataProvider);
// Read EnableKey from the factory data.
MutableByteSpan enableKey(sTestEventTriggerEnableKey);
err = mFactoryDataProvider.GetEnableKey(enableKey);
if (err != CHIP_NO_ERROR)
{
LOG_ERR("mFactoryDataProvider.GetEnableKey() failed. Could not delegate a test event trigger");
memset(sTestEventTriggerEnableKey, 0, sizeof(sTestEventTriggerEnableKey));
}
##else
SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
##endif
// Init ZCL Data Model and start server
static CommonCaseDeviceServerInitParams initParams;
static SimpleTestEventTriggerDelegate sTestEventTriggerDelegate{};
VerifyOrDie(sTestEventTriggerDelegate.Init(ByteSpan(sTestEventTriggerEnableKey)) == CHIP_NO_ERROR);
##if CONFIG_CHIP_OTA_REQUESTOR
static OTATestEventTriggerHandler sOtaTestEventTriggerHandler{};
VerifyOrDie(sTestEventTriggerDelegate.AddHandler(&sOtaTestEventTriggerHandler) == CHIP_NO_ERROR);
##endif
(void) initParams.InitializeStaticResourcesBeforeServerInit();
initParams.appDelegate = &sCallbacks;
initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate;
ReturnErrorOnFailure(chip::Server::GetInstance().Init(initParams));
...
}
When the CONFIG_CHIP_FACTORY_DATA configuration item is enabled, the factory data will be used to provide the information required for the device proving process (e.g., PAI and DAC), as well as other device information, as described in Chapter 3 "Vendor Data", and in the FactoryDataProvider.cpp code in the src/platform/telink directory.
The third part of the code is as follows:
CHIP_ERROR AppTaskCommon::InitCommonParts(void)
{
...
##if APP_SET_DEVICE_INFO_PROVIDER
gExampleDeviceInfoProvider.SetStorageDelegate(&Server::GetInstance().GetPersistentStorage());
chip::DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider);
##endif
ConfigurationMgr().LogDeviceConfig();
PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE));
##if APP_SET_NETWORK_COMM_ENDPOINT_SEC
emberAfEndpointEnableDisable(kNetworkCommissioningEndpointSecondary, false);
##endif
PlatformMgr().SetDelegate(new PlatformMgrDelegate);
// Add CHIP event handler and start CHIP thread.
// Note that all the initialization code should happen prior to this point to avoid data races
// between the main and the CHIP threads.
PlatformMgr().AddEventHandler(ChipEventHandler, 0);
err = chip::Server::GetInstance().GetFabricTable().AddFabricDelegate(new AppFabricTableDelegate);
if (err != CHIP_NO_ERROR)
{
LOG_ERR("AppFabricTableDelegate fail");
return err;
}
return CHIP_NO_ERROR;
}
ConfigurationMgr().LogDeviceConfig() prints out the device configuration information in the log, such as the following printout.
I: 510 [DL] Device Configuration:
I: 514 [DL] Serial Number: TEST_SN
I: 519 [DL] Vendor Id: 65521 (0xFFF1)
I: 523 [DL] Product Id: 32773 (0x8005)
I: 527 [DL] Product Name: not-specified
I: 532 [DL] Hardware Version: 0
I: 537 [DL] Setup Pin Code (0 for UNKNOWN/ERROR): 20202021
I: 544 [DL] Setup Discriminator (0xFFFF for UNKNOWN/ERROR): 3840 (0xF00)
I: 552 [DL] Manufacturing Date: (not set)
I: 556 [DL] Device Type: 65535 (0xFFFF)
The PrintOnboardingCodes() function outputs a QR code and a manual pairing code for use in the network provisioning, a practical example of which is shown below.
I: 563 [SVR]SetupQRCode: [MT:6FCJ142C00KA0648G00]
I: 568 [SVR]Copy/paste the below URL in a browser to see the QR Code:
I: 575 [SVR]https://project-chip.github.io/connectedhomeip/qrcode.html?data=MT%3A6FCJ142C00KA0648G00
I: 585 [SVR]Manual pairing code: [34970112332]
The PlatformMgr().AddEventHandler() function registers a callback function: AppTask::ChipEventHandler(), for responding to specific device events.
Callback Function
The Matter code has a lot of callback functions reserved, which has the benefit of maximizing the support for code extensions without modifying the source code. Here we take lighting-app as an example to introduce the important callback functions involved in the data model in the code, which is implemented in the file "examples/lighting-app/telink/src/ZclCallback.cpp".
The callback function is MatterPostAttributeChangeCallback() and its default implementation is in the file src/app/util/generic-callback-stubs.cpp. As shown in the following code, the default implementation provided by Matter is an empty function that does not contain any code. When the user provides code for a new implementation, the new callback function will replace the default implementation.
void __attribute__((weak)) MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size, uint8_t * value)
{}
The callback function MatterPostAttributeChangeCallback() is called whenever the content of an attribute (which can be any Cluster attribute) has been updated. In lighting-app, we have implemented the following callback function that serves to synchronize the latest state of the attribute to the hardware. For example, after the user updates the value of the OnOff attribute of the On/Off Cluster through the chip-tool, the LED state on the development board needs to be updated correspondingly, and this action is accomplished in the callback function (specifically, the following code calls the GetAppTask().SetInitiateAction() function). Similarly, if the user updates the attribute value of the Current Level of the Level Control Cluster via chip-tool, the following code also updates the brightness of the LED by calling GetAppTask().SetInitiateAction().
If the user needs to respond to changes in the state of other attributes, code can be added to this callback function to handle it.
void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & attributePath, uint8_t type, uint16_t size,
uint8_t * value)
{
static HsvColor_t hsv;
static XyColor_t xy;
ClusterId clusterId = attributePath.mClusterId;
AttributeId attributeId = attributePath.mAttributeId;
if (clusterId == OnOff::Id && attributeId == OnOff::Attributes::OnOff::Id)
{
ChipLogDetail(Zcl, "Cluster OnOff: attribute OnOff set to %u", *value);
GetAppTask().SetInitiateAction(*value ? AppTask::ON_ACTION : AppTask::OFF_ACTION,
static_cast<int32_t>(AppEvent::kEventType_DeviceAction), value);
}
else if (clusterId == LevelControl::Id && attributeId == LevelControl::Attributes::CurrentLevel::Id)
{
if (GetAppTask().IsTurnedOn())
{
ChipLogDetail(Zcl, "Cluster LevelControl: attribute CurrentLevel set to %u", *value);
GetAppTask().SetInitiateAction(AppTask::LEVEL_ACTION, static_cast<int32_t>(AppEvent::kEventType_DeviceAction), value);
}
else
{
ChipLogDetail(Zcl, "LED is off. Try to use move-to-level-with-on-off instead of move-to-level");
}
}
else if (clusterId == ColorControl::Id)
{
/* Ignore several attributes that are currently not processed */
if ((attributeId == ColorControl::Attributes::RemainingTime::Id) ||
(attributeId == ColorControl::Attributes::EnhancedColorMode::Id) ||
(attributeId == ColorControl::Attributes::ColorMode::Id))
{
return;
}
/* XY color space */
if (attributeId == ColorControl::Attributes::CurrentX::Id || attributeId == ColorControl::Attributes::CurrentY::Id)
{
if (attributeId == ColorControl::Attributes::CurrentX::Id)
{
xy.x = *reinterpret_cast<uint16_t *>(value);
}
else if (attributeId == ColorControl::Attributes::CurrentY::Id)
{
xy.y = *reinterpret_cast<uint16_t *>(value);
}
ChipLogDetail(Zcl, "New XY color: %u|%u", xy.x, xy.y);
GetAppTask().SetInitiateAction(AppTask::COLOR_ACTION_XY, static_cast<int32_t>(AppEvent::kEventType_DeviceAction),
(uint8_t *) &xy);
}
/* HSV color space */
else if (attributeId == ColorControl::Attributes::CurrentHue::Id ||
attributeId == ColorControl::Attributes::CurrentSaturation::Id ||
attributeId == ColorControl::Attributes::EnhancedCurrentHue::Id)
{
if (attributeId == ColorControl::Attributes::EnhancedCurrentHue::Id)
{
hsv.h = (uint8_t) (((*reinterpret_cast<uint16_t *>(value)) & 0xFF00) >> 8);
hsv.s = (uint8_t) ((*reinterpret_cast<uint16_t *>(value)) & 0xFF);
}
else if (attributeId == ColorControl::Attributes::CurrentHue::Id)
{
hsv.h = *value;
}
else if (attributeId == ColorControl::Attributes::CurrentSaturation::Id)
{
hsv.s = *value;
}
ChipLogDetail(Zcl, "New HSV color: hue = %u| saturation = %u", hsv.h, hsv.s);
GetAppTask().SetInitiateAction(AppTask::COLOR_ACTION_HSV, static_cast<int32_t>(AppEvent::kEventType_DeviceAction),
(uint8_t *) &hsv);
}
/* Temperature Mireds color space */
else if (attributeId == ColorControl::Attributes::ColorTemperatureMireds::Id)
{
ChipLogDetail(Zcl, "New Temperature Mireds color = %u", *(uint16_t *) value);
GetAppTask().SetInitiateAction(AppTask::COLOR_ACTION_CT, static_cast<int32_t>(AppEvent::kEventType_DeviceAction),
value);
}
else
{
ChipLogDetail(Zcl, "Ignore ColorControl attribute (%u) that is not currently processed!", attributeId);
}
}
}
Example Code
Two currently supported examples:
-
examples/lighting-app/telink
-
examples/light-switch-app/telink
File | Description |
---|---|
src/AppTask.cpp | Contain the application's main loop and event handler |
src/ZclCallbacks.cpp | Contain the event handler of ZCL data model's callback function |
prj.conf | Contain Zephyr configurations for specific examples |
CMakeLists.txt | Contains a list of source code to be generated and its path |
Hardware Platform Code
Code related to the Telink B92 evaluation board:
- examples/patform/telink
File | Description |
---|---|
project_include/OpenThreadConfig.h | Contain the definition of OpenThread's configuration |
util/src/ButtonManager.cpp | Contain the code responsible for setting up the TLSR9528A buttons |
util/src/LEDManager.cpp | LED Manager Related Code |
util/src/ThreadUtil.cpp | Code related to provisioning into Thread network with static keys |
Matter Configuration Code
Matter's configuration code:
- config/telink
File | Description |
---|---|
app/enable-gnu-std.cmake | Contain CMake, which is responsible for supporting the gnu++17 standard |
chip-gn/ | Contain a folder of gn-specific files to build the Telink Matter SDK |
chip-module/CMakeLists.txt | CMake configuration file containing setup rules and dependencies for the Telink Matter SDK. Also contains mapping of gn settings to CMake to link the SDK with Zephyr |
chip-module/Kconig | Contain Telink-specific configurations for Matter SDK's Zephyr, and also Matter's general Zepyhr configurations |
Matter Platform Code
Matter's platform code:
- src/platform/telink
File | Description |
---|---|
../../crypto/ | Contain folders with source code required for hardware encryption |
BLEManagerImpl.cpp | Contain the code for the BLE Manager for Matter SDK implementation, based on the Telink single-connect BLE SDK |
BUILD.gn | gn files for builds |
../Zephyr | Zephyr platform layer |
Matter Development Explained
Starting at 07:10:40 in the live replay of the Matter China Developer Conference, there is a detailed introduction to Matter development, and a simple Hello Matter Sensor implementation is presented at the end.
PC viewing address: https://wvk.h5.xeknow.com/sl/3x3C8A
To watch on mobile, please scan the QR code below:
Appendix 1 - Ecological Configuration
Google Matter Demo
Google Matter Demo Overview
This section uses the lighting-app for Telink Matter as an example to add the B92 EVK development board as a Matter device to the Google Nest Hub Gen2.
Users can control the lights on the development board through the Google Home App on the Google phone, and the controllable content is the light on and off, and the brightness of the lights.
Hardware Required for Google Matter
-
TLSR9528A as Matter light device
-
Google Nest Hub Gen2 as Border Router for the Matter network
-
Wireless Router that can Connect to Google Server provides Wi-Fi access point to provide data validation for Google Nest Hub Gen2
-
Google Pixel 6 Mobile Phone as Commissioner, the platform where the user controls the light into the network and switches them on and off
Software Required for Google Matter
-
Google Mobile System Android 13 and updated with the latest security patches
-
Google Nest Hub Gen 2nd Gen firmware version 1.56.324896
-
Google Home software version 2.2.60.2
-
Telink Matter lighting-app firmware
Google Matter Topology
Google Matter Connection Steps
(1) Power up the wireless router and configure the Wi-Fi network parameters.
Note
At this point the wireless router needs to be configured with a VPN in order to properly access www.google.com
(2) Turn on Google phone bluetooth, connect Google phone and Google Nest Hub Gen2 to the same router's Wi-Fi network, add Google Nest Hub Gen2 in Google Home App.
Google Nest Hub Gen2 Configuration Tutorial https://support.google.com/googlenest/answer/7029485?hl=en&co=GENIE.Platform%3DAndroid&oco=0
(3) Connect the B92 EVK development board to the power supply, and the serial port of the development board is connected to the computer through the USB-TTL tool, and then power up the development board.
Connect the development board PB2 to USB-TTL TXD and PB3 to USB-TTL RXD. Set serial port to 115200 8N1, then open MobaXterm on PC to monitor device logs.
(4) When the red light of the development board is observed to be short on and blinking, find the URL of the device QR code from MobaXterm (see the red box in the figure).
(5) Copy the URL to your browser to get the QR code.
(6) Open the Google Home App with the + sign in the upper left corner of the main interface.
(7) Select Set up device.
(8) Select New device.
(9) Select a home to join.
(10) Select the Matter-enabled device type.
(11) Scan the QR code on the browser.
(12) Wait for commissioning completes between the device and the Google Nest Hub Gen2.
(13) Set the device name.
(14) Successfully add Matter device to Google Nest Hub Gen2, 2nd floor light is the newly added B92 EVK development board.
(15) Enter the control interface to control the light on/off and the brightness.
Apple Matter Demo
Apple Matter Demo Overview
This section uses Telink Matter's lighting-app as an example to add the B92 EVK development board as a Matter light device to the Apple HomePod Mini. Users can control the light on the development board through the Home App on the iPhone, and the controllable content is the light on and off, and the brightness of the light.
Hardware Required for Apple Matter
-
TLSR9528A as Matter light device
-
Apple HomePod Mini as a Border Router for the Matter network
-
Wireless Router provides Wi-Fi access point to provide data verification for Apple HomePod Mini
-
iPhone as Commissioner, platform for users to control lights into the network, on and off
Software Required for Apple Matter
-
iPhone mobile system iOS 16.1.2
-
Apple HomePod Mini firmware version 16.2
-
Telink Matter lighting-app firmware
Apple Matter Topology
Apple Matter Connection Steps
(1) Power up the wireless router and configure the Wi-Fi network parameters.
(2) Turn on your iPhone's bluetooth and connect your iPhone to a configured Wi-Fi network and power up your Apple HomePod Mini. Wait for the white light on the top trackpad to start rotating, then bring your iPhone close to the Apple HomePod Mini. the hover window in the image appears, tap Settings.
(3) Place the Apple HomePod Mini into the viewfinder frame.
(4) Wait for Apple HomePod Mini setup to complete.
(5) Follow the phone prompts to successfully add Apple HomePod Mini to Home App.
(6) Connect the B92 EVK development board to the power supply and the serial port of the development board to the computer, then power up the development board.
Connect the development board PB2 to USB-TTL TXD and PB3 to USB-TTL RXD. Set serial port to 115200 8N1, then open MobaXterm on PC to monitor device logs.
(7) When the red light of the development board is observed to be short on and blinking, find the URL of the device QR code from MobaXterm (see the red box in the figure).
(8) Copy the URL to your browser to get the QR code.
(9) Open Apple Home App, in the upper right corner of the main interface + sign, select add or scan accessory.
(10) Scan the QR code on the browser.
(11) Click Add to "Apple Family".
(12) A pop-up window appears, click Add Still.
(13) Set the device name.
(14) Successfully add B92 EVK to Apple HomePod Mini, light-1 is the newly added Matter light device.
(15) Enter the control interface to control the light on/off and the brightness.
Amazon Matter Demo
Amazon Matter Demo Overview
This section uses the lighting-app for Telink Matter as an example to add the B92 EVK development board as a Matter device to Amazon Echo.
Users can control the lights on the development board through the Amazon Alexa App on Google's phone, and the controllable content is the light on and off, and the brightness of the light.
Hardware Required for Amazon Matter
-
TLSR9528A as a Matter light device
-
Amazon Echo as a Border Router for the Matter network
-
Wireless Router provides Wi-Fi access point to provide data verification for Amazon Echo
-
Google Pixel 6 Mobile Phone as Commissioner, platform for users to control light into the network, on and off
Software Required for Amazon Matter
-
Google Mobile System Android 13 and updated with the latest security patches
-
Amazon Echo software version 0011040824196
-
Amazon Alexa APP version 2024.20
-
Telink Matter lighting-app firmware
Amazon Matter Topology
Amazon Matter Connection Steps
(1) Power up the wireless router and configure the Wi-Fi network parameters.
(2) Turn on Google mobile phone, and add Amazon Echo to the Amazon Alexa App.
(3) Connect the B92 EVK development board to the power supply and the serial port of the development board to the computer, then power up the development board.
Connect the development board PB2 to USB-TTL TXD and PB3 to USB-TTL RXD. Set serial port to 115200 8N1, then open MobaXterm on PC to monitor device logs.
(4) When the white light of the development board is observed to be short on and blinking, locate the URL of the device's QR code from MobaXterm (see the red box in the figure).
(5) Copy the URL to your browser to get the QR code.
(6) Open the Amazon Alexa App with the "+" sign in the upper left corner of the main screen.
(7) Select Add Device.
(8) Select Matter Device.
(9) Select YES, there is a Matter logo.
(10) After ensuring that the device is in the broadcast state, select YES and the device is in power on.
(11) Select Scan QR Code
(12) Scan the QR code on the browser.
(13) Select YES, the device is Matter compatible.
(14) Wait for commissioning completes between the device and Amazon Echo.
(15) Set the device name and device room, both of which can be skipped.
(16) Successfully add Matter device to Amazon Echo, first light is the newly added B92 EVK development board.
(17) Enter the control interface to control the light on/off and the brightness.
Samsung Matter Demo
Samsung Matter Demo Overview
This section uses the lighting-app for Telink Matter as an example to add the B92 EVK development board as a Matter device to the SmartThings Station.
Users can control the lights on the development board through the SmartThings App on Google's phone, and the controllable content is the light on and off, and the brightness of the light.
Hardware Required for Samsung Matter
-
TLSR9528A as a Matter light device
-
SmartThings Station as a Border Router for the Matter network
-
Wireless router provides Wi-Fi access point to provide data verification for SmartThings Station
-
Google Pixel 6 Mobile Phone as Commissioner, the platform where the user controls the lights into the network and switches them on and off
Software Required for Samsung Matter
-
Google Mobile System Android 13 and updated with the latest security patches
-
SmartThings Station Hub firmware version 000.053.00019
-
SmartThings APP version 1.8.18.21
-
Telink Matter lighting-app firmware
Samsung Matter Topology
Samsung Matter Connection Steps
(1) Open the SmartThings App, select + in the upper right corner, and choose Add device.
(2) Select Partner devices, click Add.
(3) Seelct Matter.
(4) Scan the QR code and select Continue.
(5) Wait for the connection to complete, set the device name and room.
(6) Now the device can be controlled by the SmartThings App
Appendix 2 - Environment Setup (Docker)
Ubuntu version 20.04 LTS is required. In Chapter 3 of the main text, we described how to manually build Matter's engineering environment, and in this appendix we'll continue with the steps to build a master branching environment using Docker.
Install Dependencies
sudo apt-get install git gcc g++ pkg-config libssl-dev libdbus-1-dev \
libglib2.0-dev libavahi-client-dev ninja-build python3-venv python3-dev \
python3-pip unzip libgirepository1.0-dev libcairo2-dev libreadline-dev
Install Docker
Run the Docker container (it will take some time on the first run):
For the Matter master branch, use the following command:
docker run -it --rm -v $PWD:/host -w /host ghcr.io/project-chip/chip-build-telink:$(wget -q -O - https://raw.githubusercontent.com/project-chip/connectedhomeip/master/.github/workflows/examples-telink.yaml 2> /dev/null | grep chip-build-telink | awk -F: '{print $NF}')
Compatible versions of the Docker image can be found in the following files in the Matter project directory:
.github/workflows/examples-telink.yaml
Or, check out the record on GitHub: https://github.com/project-chip/connectedhomeip/blob/master/.github/workflows/examples-telink.yaml
Build the Matter Engineering Environment
(1) Get the Matter Project
Download the Matter project to a local directory such as /home/${YOUR_USERNAME}/workspace/matter.
git clone https://github.com/project-chip/connectedhomeip
(2) Switch to the specified commit on the master branch and update the submodule
cd ./connectedhomeip
git checkout 68068cbe663add7c7be8b2ff6c016e9a03b287fb
git submodule update --init --recursive
(3) Run the bootloader
Execute bootstrap and preparing the environment for Matter usually take a long time the first time you run it.
source scripts/bootstrap.sh
Note
You may have to re-run the bootloader each time you switch commit and change the environment.
This step will generate a hidden folder called .environment in the Matter root directory connectedhomeip. In mainland China it may take extra time or fail.
If you have any problems with the Matter environment building, try:
1) Remove the environment (in the root directory of the Matter project):
rm -rf .environment
2) Redo the bootloader again:
source scripts/bootstrap.sh
Matter Building Example
(1) Activate the Matter environment
source scripts/activate.sh
(2) Go to the example directory
cd examples/${app}/telink
${app}
: lighting-app or light-switch-app, etc.
(3) Delete if a build previously existed
rm -rf build/
(4) Building example
west build -b <build_target>
<build_target>
is the name of the development board you intend to use, e.g. tlsr9518adk80d
, tlsr9528a
, tl3218x
or tl7218x
.
And, you need to specify -DFLASH_SIZE
in the compile command according to the flash size of the board you are using, for example, if you are using a B92 board with 2MB flash, the compile command will be:
west build -b tlsr9528a -- -DFLASH_SIZE=2m
You can find the target build file named zephyr.bin in the build/zephyr folder.
Appendix 3 - CD Certificate
For some vendors who use their own PAA certificate, it is needed to generate their own Certification Declaration(CD), for equipment passing the certification test before the CSA certification.
Step 1: Use the chip-cert tool, source code path: connectedhomeip/src/tools/chip-cert, and use the following command to generate a chip-cert:
source scripts/activate.sh
gn gen src/tools/chip-cert/out/host
ninja -C src/tools/chip-cert/out/host chip-cert
Step 2: Use the chip-cert tool to generate the authentication certificate.
./src/tools/chip-cert/out/host/chip-cert gen-cd \
-C credentials/test/certification-declaration/Chip-Test-CD-Signing-Cert.pem \
-K credentials/test/certification-declaration/Chip-Test-CD-Signing-Key.pem \
--out telink_cd.bin \
-f 1 \
-V 1141 \
-p 8005 \
-d 0100 \
-c "ZIG0000000000000000" \
-l 0 \
-i 0 \
-n 0001 \
-t 1
The parameters that the vendor may need to set are:
Command | Description |
---|---|
-V 1141 | Vendor ID, vendor identification, 0x1411 is the Telink VID |
-p 8005 | Product ID, product identification, set based on specific products |
-d 0100 | Device ID (Device Identifier), an identifier based on product type for specific devices, stipulated in detail within the Matter standard. For instance, the value 0x100 in the example corresponds to a dimmable bulb. |
-t 1 | Certification-type, there are three types of certificates specified in the Matter protocol: -t 0 - used in development and testing phases, Matter's default type -t 1 - for temporary use, this type can be used when passing the certification -t 2 - after the certification is passed, you will get the official certificate from the CSA. |
The generated authentication certificate is in bin format. You can verify the legitimacy of the certificate with the following command:
./src/tools/chip-cert/out/host/chip-cert print-cd ./telink_cd.bin
Step 3: Replace the authentication certificate(CD) in Matter project
First convert the binary certificate into an array format
xxd -i telink_cd.bin > telink_cd.h
In the current Matter project, the authentication certificate is stored in the array defined by the macro CHIP_DEVICE_CONFIG_CERTIFICATION_DECLARATION. Simply replace this macro with the generated telink_cd.h file.
The path of the macro definition "CHIP_DEVICE_CONFIG_CERTIFICATION_DECLARATION": connectedhomeip/src/platform/telink/CHIPDevicePlatformConfig.h
Appendix 4 - Factory Data
Factory data is a set of device parameters written to non-volatile memory during the manufacturing process. This section describes the process of creating and writing factory data using Telink Matter.
The factory data parameter set includes different types of information, such as about device certificate, encryption key, device identifier, and hardware. All of these parameters are vendor-specific and must be added to the device's persistent memory during the manufacturing process. The factory data parameters will be read at device startup and they can then be used in the Matter stack and in user applications (e.g. in the network provisioning process).
All factory data parameters are protected from software modification. The data parameter set of the firmware must remain unchanged during the life cycle of the device. When implementing the firmware, you must ensure that the factory data is not rewritten or overwritten during a device firmware update or restoration of factory settings, except in certain vendor-defined cases.
For Telink platform, factory data is stored by default in a separate partition of the internal flash memory.
Overview
You can implement the Factory Data Component Table in a number of ways, as long as the final HEX/BIN file contains all the mandatory components defined in the table.
In this section, Generate Factory Data and Build an Example Application Using Factory Data describe one of the implementations of a factory dataset created by the Telink platform maintainer.
At the end of this process, you will have a hex and binary file containing the factory data partition in CBOR
format.
The Factory Data Accessor is a component that reads and parses factory data parameters from the device's persistent storage and creates an interface that makes them all available to the Matter stack and the user application.
The default implementation of the factory data accessor assumes that factory data stored in device flash memory is provided in CBOR
format. However, instead of using the Telink script to generate the factory dataset, it is also possible to implement another parser and factory data accessor. If the newly provided implementation is consistent with that specified in the Factory Data Provider then this is possible.
Note
This function does not yet provide encryption and security for factory data partitions.
Factory Data Component Table
The following table lists the parameters of the factory dataset:
Key name | Full name | Length | Format | Conformance | Description |
---|---|---|---|---|---|
count | number of factory binaries | 4 B | uint32 | optional | The number of generated partition binaries to produce. The default value is 1. |
output | output directory | N/A | ASCII string | optional | Store the output path of generated data. |
spake2-path | spake2 path | N/A | ASCII string | mandatory | Provide Spake2+ toolpath |
chip-tool-path | chip tool path | N/A | ASCII string | mandatory | Provide chip-tool path |
chip-cert-path | chip cert path | N/A | ASCII string | mandatory | Provide chip-cert path |
overwrite | overwrite | N/A | bool | optional | This parameter allows generating new factory data and overwriting the output catalog if it exists. |
in-tree | in Matter tree | N/A | bool | optional | Use it only when building factory data from Matter source code. |
enable-key | enable key | N/A | byte string | optional | Use only during certification testing and should not be present on production equipment. |
passcode | SPAKE passcode | 4 B | uint32 | optional | The pairing password is a 27-bit unsigned integer that is used as proof of ownership during pairing. Its value must be limited to values from "0x0000001" to '0x5F5E0FE' (decimal "00000001" to 99999998"), excluding the following invalid password values: 00000000 , 11111111 , 22222222 , 33333333 , 44444444 , 55555555 , 66666666 , 77777777 , 88888888 , 99999999 , 12345678 , 87654321 . |
spake2-it | SPAKE2+ iteration counter | 4 B | uint32 | mandatory | The SPAKE2+ Iteration Counter is the number of PBKDF2 (Key Derivation Function) interactions in the encryption process used during the generation of the SPAKE2+ authentication program. |
discriminator | Discriminator | 2 B | uint16 | mandatory | A 12-bit value that matches the same name field in the setup code. The identification code is used during the discovery process. |
commissioning-flow | commisioning flow | 4 B | uint32 | optional | Device provisioning process, 0:Standard, 1:User-Intent, 2:Custom. Default value is 0, options are [0, 1, 2]. |
discovery-mode | discovery mode | 4 B | uint32 | optional | Configurable network device network discovery technology. 0:Wi-Fi-SoftAP, 1:BLE, 2:On-network. defaults to BLE, options [0, 1, 2] |
vendor-id | vendor ID | 2 B | uint16 | mandatory | The ID assigned by CSA to organizations responsible for manufacturing devices. |
vendor-name | vendor name | <1, 32> B | ASCII string | mandatory | A human-readable vendor name that provides a simple string containing the device vendor identifier for application and Matter stack purposes. |
product-id | product ID | 2 B | uint16 | mandatory | A unique ID assigned by the equipment supplier to identify the product. It defaults to the CSA-assigned ID used to designate non-production or test products. |
product-name | product name | <1, 32> B | ASCII string | mandatory | A human-readable product name that provides a simple string containing the product identification for application and Matter stack purposes. |
hw-ver | hardware version | 2 B | uint16 | mandatory | Hardware version number that specifies the version number of the device's hardware. The meaning of the value and the version control scheme are defined by the vendor. |
hw-ver-str | hardware version string | <1, 64> B | uint16 | mandatory | A hardware version string parameter that specifies the hardware version of the device as a more user-friendly value than the hardware version integer value. The meaning of the value and the version control scheme are defined by the vendor. |
mfg-date | manufacturing date | <8, 10> B | ISO 8601 | mandatory | Manufacturing Date specifies the date on which the device was manufactured. The date format used is ISO 8601, e.g. YYYY-MM-DD . |
serial-num | serial number | <1, 32> B | ASCII string | mandatory | The Serial Number parameter defines a unique number for the manufacturing equipment. The maximum length of the serial number is 32 characters. |
enable-rotating-device-id | enable rotating device id | N/A | bool | optional | Enable rotating device ids in the generated binaries |
rd-id-uid | rotating device ID unique ID | <16, 32> B | byte string | mandatory | The unique ID of the rotating device ID, consisting of a randomly generated 128-bit (or longer) octet string. This parameter shall be prevented from being read or written over the air after the initial introduction of the device and shall remain fixed for the life of the device. |
cert | certificate path | N/A | ASCII string | optional | The input certificate file is in PEM format. |
key | certificate key path | N/A | ASCII string | optional | Input key file in PEM format. |
cert-dclrn | certificate declaration path | N/A | ASCII string | mandatory | Certificate statement file in DER format. |
dac-cert | DAC certificate path | N/A | ASCII string | optional | The input DAC certificate file is in PEM format. |
dac-key | DAC certificate key path | N/A | ASCII string | optional | The input DAC private key file is in PEM format. |
cn-prefix | common name prefix | N/A | ASCII string | optional | The common name prefix of the body of the generated certificate. |
lifetime | certificate lifetime | 4 B | uint32 | optional | The expiration date of the generated certificate. The default value is 4294967295 (if not specified), which indicates that the certificate has no explicitly defined expiration date. |
valid-from | certificate start date | <8, 19> B | ISO 8601 | optional | The start date of the certificate validity period in the format YYYY-MM-DD [ HH:MM:SS ]. The default is the current date. |
paa | PAA | N/A | bool | optional | Use the input certificate cert as the PAA certificate. |
pai | PAI | N/A | bool | optional | Use the input certificate cert as the PAI certificate. |
product-label | product label | N/A | ASCII string | optional | Product Label. |
product-url | product url | N/A | ASCII string | optional | Product URL. |
part_number | part number | N/A | ASCII string | optional | Provide readable product numbers. |
offset | factory partition offset | 4 B | uint32 | mandatory | Partition Offset-Address in the device's NVM memory where the factory data will be stored |
size | factory partition size | 2 B | uint16 | mandatory | Maximum partition size |
Factory Data Format
The factory dataset must be saved to a hex or binary file that can be written to the flash memory of the Matter device.
In the Telink example, the factory dataset is represented in CBOR
format and stored in a hex or binary file. The file is then burned to a device.
All parameters of the factory dataset are either mandatory or optional:
-
Mandatory parameters must always be provided, as they are required by the example to perform the provisioning into the Matter network.
-
Optional parameters can be used for development and testing purposes. For example, the user data parameter contains all data required by a specific manufacturer and not included in the mandatory parameters.
The following format is used in the factory dataset:
-
uint16
anduint32
-- These are the numeric formats for two-byte-length unsigned integers and four-byte-length unsigned integers, respectively. The values are stored in big-endian order in a hex file -
Byte string
-- This parameter represents a sequence of integers between 0 and 255 inclusive, without any encoding. Since the JSON format does not allow byte strings, thehex:
prefix is added to the parameter and it is converted to a hexadecimal string.
For example, an ASCII string abba
is represented in the JSON file as hex:hex:61626261
, and then stored in the hex file as 0x61626261
.
The length of a hexadecimal string in a JSON file is twice the size of the byte string plus the prefix.
-
ASCII string
is a string representation in ASCII without null termination. -
The
ISO 8601
format is a date format representing a date provided inYYYY-MM-DD
orYYYYMMDD
format. -
All certificates stored in factory data are provided in X.509 format.
Enable Factory Data Support
By default, factory data support is disabled in all Telink examples and Telink devices use predefined parameters from the Matter core that you should not change.
To get started with factory data stored in flash memory and the Telink Platform and the Telink Platform's Factory Data Provider, build an example using the following option:
west build -- -DCONFIG_CHIP_FACTORY_DATA=y
Generate Factory Data
This section introduces generating factory data using the following Telink Python script.
Dependencies
Before using the Builder tool, make sure you have the following tools.
(1) Building Matter Tool
1) Generate chip-tool, spake2p and chip-cert at path/to/connectedhomeip/build/out/host
using the following command
cd path/to/connectedhomeip
source scripts/activate.sh
gn gen build/out/host
ninja -C build/out/host
2) Add tool path to $PATH
export PATH="$PATH:path/to/connectedhomeip/build/out/host"
(2) Prepare the Factory Data Partition on the Device
The factory data partition is a region in the device's persistent storage that holds factory data sets. This region is configured in the DeviceTrees file.
- For the Matter v1.1-branch branch, the configuration file is in the Matter project at path:
connectedhomeip/src/platform/telink/tlsr9518adk80d.overlay
- For Matter master branch, the configuration file is in the Matter project.
However, the declaration of partitions is extracted from tlsr9528a.overlay
and written as tlsr9528a_2m_flash.overlay
and tlsr9528a_4m_flash.overlay
respectively. Then, you can choose the appropriate configuration file according to the Flash size of the selected chip.
To prepare a customized example of factory data support, add or modify a partition named factory-data
in the tlsr9528a-common.dtsi
, tlsr9518adk80d.overlay
or Xm_flash.overlay
file. The partition size should be a multiple of a flash page (for the B91 SoC, a single page size is equal to 4kB).
Refer to the factory data partition in Flash Memory Layout as an example, detailed in the Xm_flash.overlay
file.
The factory-data
partition size is set to one flash page size (4kB).
Script Use
To use this script, complete the following steps:
(1) Go to the connectedhomeip
root directory.
(2) Run the script with the -h
option to see all possible options:
python scripts/tools/telink/mfg_tool.py -h
(3) Prepare a parameter list:
1) Fill in all mandatory parameters:
--serial-num --vendor-id, --product-id, --vendor-name, --product-name, --mfg-date, --hw-ver, --hw-ver-str, --enable-rotating-device-id, --spake2-path, --chip-tool-path, --chip-cert-path, --offset, --size
2) Add the output file path:
--output <output_dir>
3) Add the certificate statement path (required):
-cd <path to Certificate Declaration in der format>
4) Specify which certificate to use:
- User:
--dac-cert <path to DAC certificate in pem format>
--dac-key <path to DAC key in pem format>
--cert <path to PAI certificate in pem format>
--key <path to PAI key in pem format>
--pai
- Generate DAC and PAI:
--cert <path to PAA certificate in pem format>
--key <path to PAA key in pem format>
--paa
5) Use one of the following options to add a new unique ID for the rotating device ID:
- Provide an existing ID:
--rdid--uid <rotating device ID unique ID>
- Generate a new ID and provide:
--enable-rotating-device-id
6) (Optional) Specify your own password:
--passcode <passcode>
7) (Optional) Specify your own authentication code:
--discriminator <discriminator>
8) (Optional) Add a request to overwrite an existing output file:
--overwrite
9) Specify the partition offset and size:
--offset <partition_address_in_memory>
--size <partition_size>
In this command:
-
<partition_address_in_memory>
is the address in the persistent storage area of the device where the partition dataset will be stored. -
<partition_size>
is the size of the partition in the persistent storage area of the device. Check new data against this value to see if it is the right size.
Note
-
Used for Matter v1.1-branch branch:
--offset 0x104000 --size 0x1000
-
Used for the latest Matter master branch (2MB flash):
--offset 0x107000 --size 0x1000
(4) Run the script with the prepared parameter list:
python3 mfg_tool.py <arguments>
For example, the final call to the Python script looks similar to the following usage:
$ python3 scripts/tools/telink/mfg_tool.py \
--vendor-id 0xFFF2 --product-id 0x8001 \
--serial-num AABBCCDDEEFF11223344556677889900 \
--vendor-name "Telink Semiconductor" \
--product-name "not-specified" \
--mfg-date 2022-12-12 \
--hw-ver 1 \
--hw-ver-str "prerelase" \
--enable-rotating-device-id \
--pai \
--key credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Key.pem \
--cert credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Cert.pem \
-cd credentials/test/certification-declaration/Chip-Test-CD-FFF2-8001.der \
--spake2-path build/out/host/spake2p \
--chip-tool-path build/out/host/chip-tool \
--chip-cert-path build/out/host/chip-cert \
--offset 0x107000 --size 0x1000 \
--out ./factory_data_for_2mb_flash
As a result of the above example, the files listed below will be created:
factory_data_for_2mb_flash
├── device_sn.csv
└── fff2_8001
└── aabbccddeeff11223344556677889900
├── factory_data.bin
├── factory_data.hex
├── internal
│ ├── DAC_cert.der
│ ├── DAC_cert.pem
│ ├── DAC_key.pem
│ ├── DAC_private_key.bin
│ ├── DAC_public_key.bin
│ └── pai_cert.der
├── onb_codes.csv
├── pin_disc.csv
├── qrcode.png
└── summary.json
(5) (Optional example) Generate 5 factory partitions [Optional parameter: --count]
$ python3 scripts/tools/telink/mfg_tool.py --count 5 -v 0xFFF2 -p 0x8001 \
--serial-num AABBCCDDEEFF11223344556677889900 \
--vendor-name "Telink Semiconductor" \
--product-name "not-specified" \
--mfg-date 2022-12-02 \
--hw-ver 1 \
--hw-ver-str "prerelase" \
--enable-rotating-device-id \
--pai \
--key credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Key.pem \
--cert credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Cert.pem \
-cd credentials/test/certification-declaration/Chip-Test-CD-FFF2-8001.der \
--spake2-path build/out/host/spake2p \
--chip-tool-path build/out/host/chip-tool \
--chip-cert-path build/out/host/chip-cert \
--offset 0x107000 --size 0x1000 \
--out ./factory_data_for_2mb_flash
As a result of the above example, the files listed below will be created:
factory_data_for_2mb_flash
├── device_sn.csv
└── fff2_8001
├── aabbccddeeff11223344556677889900
│ ├── factory_data.bin
│ ├── factory_data.hex
│ ├── internal
│ │ ├── DAC_cert.der
│ │ ├── DAC_cert.pem
│ │ ├── DAC_key.pem
│ │ ├── DAC_private_key.bin
│ │ ├── DAC_public_key.bin
│ │ └── pai_cert.der
│ ├── onb_codes.csv
│ ├── pin_disc.csv
│ ├── qrcode.png
│ └── summary.json
├── aabbccddeeff11223344556677889901
│ ├── factory_data.bin
│ ├── factory_data.hex
│ ├── internal
│ │ ├── DAC_cert.der
│ │ ├── DAC_cert.pem
│ │ ├── DAC_key.pem
│ │ ├── DAC_private_key.bin
│ │ ├── DAC_public_key.bin
│ │ └── pai_cert.der
│ ├── onb_codes.csv
│ ├── pin_disc.csv
│ ├── qrcode.png
│ └── summary.json
├── aabbccddeeff11223344556677889902
│ ├── factory_data.bin
│ ├── factory_data.hex
│ ├── internal
│ │ ├── DAC_cert.der
│ │ ├── DAC_cert.pem
│ │ ├── DAC_key.pem
│ │ ├── DAC_private_key.bin
│ │ ├── DAC_public_key.bin
│ │ └── pai_cert.der
│ ├── onb_codes.csv
│ ├── pin_disc.csv
│ ├── qrcode.png
│ └── summary.json
└── aabbccddeeff11223344556677889903
├── factory_data.bin
├── factory_data.hex
├── internal
│ ├── DAC_cert.der
│ ├── DAC_cert.pem
│ ├── DAC_key.pem
│ ├── DAC_private_key.bin
│ ├── DAC_public_key.bin
│ └── pai_cert.der
├── onb_codes.csv
├── pin_disc.csv
├── qrcode.png
└── summary.json
Note
By default, overwriting existing output directories is disabled. This means that you cannot create a new directory with the same name in the same location as an existing file. To allow overwriting, add the --overwrite
option to the Python script's parameter list.
Build an Example Application Using Factory Data
You can manually generate factory data sets using the instructions described in the Generate Factory Data section above. You can also use the Telink platform build system, which uses the Kconfig option to automatically create the factory data content.
To enable automatic generation of factory datasets, go to the catalog for the example application and build it using the following option:
west build -- -DCONFIG_CHIP_FACTORY_DATA=y -DCONFIG_CHIP_FACTORY_DATA_BUILD=y
Alternatively, you can add the Kconfig setting of CONFIG_CHIP_FACTORY_DATA_BUILD=y
to the prj.conf
file of the example application.
Note that if you encounter a ModuleNotFoundError at this step, try the build again after updating the dependencies by executing the following command in the connectedhomeip directory:
.environment/pigweed-venv/bin/python3 -m pip install -r scripts/setup/requirements.telink.txt
A successful build will result in firmware for the application with factory data partitioning turned on, and a separate factory dataset binary, and you will need to burn them separately.
Each factory data parameter has a default value. These are described in the Kconfig file. To set a new value for a factory data parameter, provide it as a list of build parameters, or by using the interactive Kconfig interface.
Provide Factory Data Parameters as Generated Parameter List
This way of providing factory data can be used with third-party build scripts, as it uses only one command. The factory data feature can be turned on with an additional option to the west command:
west build -- -DCONFIG_CHIP_FACTORY_DATA=y --DCONFIG_CHIP_FACTORY_DATA_BUILD=y --DCONFIG_CHIP_DEVICE_DISCRIMINATOR=0xF11
Alternatively, you can add the relevant Kconfig option lines to the prj.conf
file of the example application.
Separate Burning of Application Firmware and Factory Datasets
Our application firmware and factory dataset are binary BIN files that can be burned into the device's flash finger using the BDT tool and Telink burning key.
It is important to note that you need to choose the burn address of the factory dataset according to the actual flash partition set in the above section.
For burning, just use the Telink BDT tool's multi-address burning:
(1) Select Multi-address download in Tool.
(2) Here is an example of the firmware on the v1.1-branch, where the offset value of the factory data is 0x104000
:
Set Factory Data
One way to merge the separate factory data sets into the firmware of the example application is to use the Telink platform build system described in Build an Example Application Using Factory Data, and build the example application with the following additional option -DCONFIG_CHIP_FACTORY_DATA_ MERGE_WITH_FIRMWARE=y
:
$ west build -- \
-DCONFIG_CHIP_FACTORY_DATA=y \
-DCONFIG_CHIP_FACTORY_DATA_BUILD=y \
-DCONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=y
To better understand the requirement scenarios corresponding to the above setup items, see the table below:
Scenario | Requirement | Description |
---|---|---|
Scenario(1) | There is no need to configure the factory dataset or turn on the application firmware for factory data partitioning | The hard-coded values in the code will be used as the vendor's data. |
Scenario(2) | Needed, and there is already factory dataset but it is only needed to turn on the application firmware in the factory data partitioning | The factory data set is not merged into the final firmware binary. The partition image must be burned in some other way or a runtime error will be reported at boot time because the factory data accessor expects valid data to exist within the factory data partition. |
Scenario(3) | Needed, but there is no factory dataset, to generate a factory dataset and include the application firmware of the generated factory dataset | The factory dataset will be created by the build system and merged into the final firmware binary. Recommended for development purposes. |
Scenario(4) | Needed, and there is already factory dataset and it is needed to include the application firmware of the existing factory dataset | The build system expects to have externally-generated factory dataset (e.g. generated by the script described in the "Scripting" section) at a path (e.g. ${PROJECT_BINARY_DIR}/factory/factory_data.bin) specified by connectedhomeip/config/telink/chip-module/CMakeLists.txt. |
Pair selection settings (depending on the desired scenario) | (1) | (2) | (3) | (4) |
---|---|---|---|---|
CONFIG_CHIP_FACTORY_DATA | n | y | y | y |
CONFIG_CHIP_FACTORY_DATA_BUILD | don't care | don't care | y | n |
CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE | don't care | n | y | y |
You can also build an example application that uses automatically generated new CD, DAC, and PAI certificates. The newly generated certificates will be automatically added to the factory dataset. To generate new certificate, disable the default certificate by building the example application with the additional option -DCHIP_FACTORY_DATA_USE_DEFAULT_CERTS=n
:
$ west build -- \
-DCONFIG_CHIP_FACTORY_DATA=y \
-DCONFIG_CHIP_FACTORY_DATA_BUILD=y \
-DCONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=y \
-DCONFIG_CHIP_FACTORY_DATA_USE_DEFAULT_CERTS=n
Note
To generate a new certificate using the Telink platform build system, you need the chip-cert
executable in the system variable PATH. To learn how to get chip-cert
, refer to the steps in Building Matter Tool and add the new build executable to the system variable PATH. The Cmake build system will automatically find this executable.
Then, in the example application catalog, a generated binary firmware can be used and both the application firmware and the newly generated factory data can be written to.
Implementation with Your Own Factory Data
The Generate Factory Data described above is only an example application valid for the Telink platform. You can create a HEX file containing all the Factory Data Component Table in any format, and then implement a parser to read all the parameters and pass them to the provider.
Each manufacturer can implement the factory dataset itself by implementing a parser and factory data accessor in the Matter stack. UseTelink Factory Data Provider and Factory Data Parseras examples.
Depending on the purpose and format, you can read factory data sets from the device's flash memory in different ways. In the Telink example, the factory data is stored in CBOR
format. The device reads the output raw data using the Factory Data Parser, decodes it and stores it in the FactoryData
structure.
The Factory Data Provider implementation uses this parser to get all the needed factory data parameters and provides them to the Matter core.
In the Telink example, FactoryDataProvider
is a template class that inherits from the DeviceAttestationCredentialsProvider
, CommissionableDataProvider
and DeviceInstanceInfoProvider
classes. Your custom implementation must also inherit from these classes and implement their functions to fetch all factory datasets from the device's flash memory.
These classes are virtual classes and need to be overridden by derived classes. To override an inherited class, complete the following steps:
(1) Override the following methods:
// ===== Members functions that implement the DeviceAttestationCredentialsProvider
CHIP_ERROR GetCertificationDeclaration(MutableByteSpan & outBuffer) override;
CHIP_ERROR GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) override;
CHIP_ERROR GetDeviceAttestationCert(MutableByteSpan & outBuffer) override;
CHIP_ERROR GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) override;
CHIP_ERROR SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override;
// ===== Members functions that implement the CommissionableDataProvider
CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override;
CHIP_ERROR SetSetupDiscriminator(uint16_t setupDiscriminator) override;
CHIP_ERROR GetSpake2pIterationCount(uint32_t & iterationCount) override;
CHIP_ERROR GetSpake2pSalt(MutableByteSpan & saltBuf) override;
CHIP_ERROR GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) override;
CHIP_ERROR GetSetupPasscode(uint32_t & setupPasscode) override;
CHIP_ERROR SetSetupPasscode(uint32_t setupPasscode) override;
// ===== Members functions that implement the DeviceInstanceInfoProvider
CHIP_ERROR GetVendorName(char * buf, size_t bufSize) override;
CHIP_ERROR GetVendorId(uint16_t & vendorId) override;
CHIP_ERROR GetProductName(char * buf, size_t bufSize) override;
CHIP_ERROR GetProductId(uint16_t & productId) override;
CHIP_ERROR GetSerialNumber(char * buf, size_t bufSize) override;
CHIP_ERROR GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) override;
CHIP_ERROR GetHardwareVersion(uint16_t & hardwareVersion) override;
CHIP_ERROR GetHardwareVersionString(char * buf, size_t bufSize) override;
CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override;
(2) Move the newly created parser and provider files into the project directory.
(3) Add the file to CMakeList.txt
.
(4) Disable the default implementation and the Telink implementation of the factory data provider to start using your own factory data parser and provider implementations.
This can be accomplished in one of the following ways:
-
Add the Kconfig setting
CONFIG_CHIP_FACTORY_DATA_CUSTOM_BACKEND=y
to theprj.conf
file. -
Build an example with the following option:
west build -- -DCONFIG_CHIP_FACTORY_DATA_CUSTOM_BACKEND=y
Appendix 5 - ZAP Tool
ZCL Advanced Platform(ZAP)
ZCL Advanced Platform (ZAP) is a node.js template engine based on Matter Clusters that provides the following functions for Matter application and SDK:
-
Configure Matter Endpoint, Cluster, Attribute, and other device functions in the GUI interface
-
Create templates that automatically generate data model definitions, callback functions, and other Matter source code
-
Create and use pre-configured ZAP files to include in your SDKs
Install ZAP
Please refer to scripts/zap.json
and scripts/tools/zap/zap_execution.py
to confirm the earliest supported ZAP_VERSION. Example: ZAP_VERSION=v2023.10.14-nightly
mkdir -p /opt/zap-${ZAP_VERSION}
cd /opt/zap-${ZAP_VERSION}
wget https://github.com/project-chip/zap/releases/download/${ZAP_VERSION}/zap-linux-x64.zip
unzip zap-linux-x64.zip
You may need to add sudo
to get permission to operate under the opt
and usr
paths.
Use ZAP
(1) After installing ZAP, start it by running the executable file from the ZAP installation directory:
./zap
After running you can see the ZAP interface:
(2) Open ZAP file
Click File in the menu bar, select Open File and choose the .zap file you want to open from the following screen. ZAP files are JSON templates that define endpoints, commands, attributes and other device functions, for example, light-switch-app.zap in connectedhomeip/examples/light-switch-app/light-switch-common
After selecting it and clicking Open in the lower right corner, you can see the following interface:
(3) Change the product manufacturer
The product manufacturer can be changed in the ZCL GLOBAL OPTION in the upper right corner. The serial number of Telink is Telink Micro (0x1141).
(4) Configure ZAP file
- Click on EDIT in Endpoint 1 to select different Matter device
-
On the right side is the Cluster in Endpoint 1. You can choose the status of the Cluster, whether the device is a Sever or a Client, or Not Enabled.
-
On the right side of the Cluster, you can click on the cogwheel to access the attribute screen:
The figure shows the Identify Cluster interface, where you can enable or disable attributes and set various attribute options.
- Click COMMANDS above to configure commands for this Cluster
As shown, the Identify, TrrigerEffect command are enabled in the Identify Cluster.
(5) Generate ZAP source file
After you have made any changes to Endpoint, you can save them by clicking on the save option in the File in the upper left corner.
Appendix 6 - Mars_B91
Overview
Mars_B91 is a set of daughter boards created by Telink to promote its chip products. This appendix takes the lighting-app and temperature-measurement-app developed based on Telink Matter V1.2 SDK as examples to add Mars_B91 development board as a Matter device to Apple's smart home ecosystem. Users can control the light on/off/brightness/color temperature or read the ambient temperature through the Home App on iPhone.
Mars_B91 Development Board
The Mars_B91 development board is divided into two parts, the mother board and the daughter board, the daughter board model number is Mars_B91_V1.1
and the mother board model number is Mars_B91_Model_A_V2.2
.
Mars_B91_v1.1
is a module board whose core chip is TLSR9218 and supports ZigBee, BLE, Thread and other communication protocols. Users can easily evaluate the chip, or integrate the module board into their own circuit system to extend the wireless function for their own system.
Mars_B91_Model_A_V2.2
(or Mars_B91_Mother_V2.2
) is a mother board that provides support for the daughter board Mars_B91_v1.1
. The daughter board has a rich set of built-in sensors and interfaces, and through pin-multiplexing, it supports various functions such as IIC, UART, PWM, ADC, etc. It also has a USB debugging interface.
Below are some of the peripherals used by the Matter application on the Mars_B91 development board:
(1) The mother board is equipped with a temperature and humidity sensor SHT30 to capture the ambient temperature.
(2) There are digital RGB LED bead WS2812 which can emit different colors of light.
(3) There are dial-wheel buttons, and three consecutive presses to the left can trigger Factory Reset to restore factory data.
(4) There are two USB-C ports on the mother board, the left side of the front is the USB_UART port from which the Matter device log is output, and the right side is the USB port through which the firmware can be burned.
(5) There is a red LED on the daughter board to indicate device status.
Onboard Matter Device into Your Smart Home Ecosystem
Topology
Using Apple Home as an example for device provisioning.
Equipment Required for Network Commissioning
-
Mars_B91 development board as Matter temperature sensor device or Matter light device
-
Apple HomePod Mini as a Border Router for the Matter network
-
Wireless Router provides Wi-Fi access point to provide data verification for Apple HomePod Mini
-
iPhone as Commissioner, the platform for the user to control the device into the network, get temperature data or control the lights
Software Required for Network Commissioning
-
iPhone mobile system iOS 17.0.3
-
Apple HomePod Mini firmware version 17.1
-
Telink Matter V1.2 lighting-app firmware with bootloader
-
Individual Telink Matter V1.2 temperature-measurement-app firmware
You can download the required prebuilt firmware via the cloud drive link below. The link also contains some sample video clips. https://drive.weixin.qq.com/s?k=AKwA0AfNAA8yj9zSEr
Network Commissioning Operation Steps
The following will describe the steps for network commissioning, using color temperature lights as an example:
(1) Power up your wireless router and HomePod Mini to establish an Apple network.
(2) The firmware ColorLighting_v1.bin
containing the bootloader has been pre-burned into the development board, connect the Mars_B91 board to the PC as shown in the figure, and then power on the board.
Connect a USB-C cable to the development board's USB_UART port. Configure the serial port with these settings: 115200 Bits/second, 8 data bits, no parity, 1 stop bit (115200, 8N1). Then open any serial terminal tool on the computer to monitor the device output logs.
(3) Wait for a number of seconds for the Bootloader to complete the self-test, you can observe that the red light of the development board is short on and blinking, and find the URL of the device's QR code from the device output log (see the red box in the figure).
(4) Copy the URL to your browser to get the QR code.
(5) Use iPhone to add device to the Apple Home ecosystem.
The steps for performing the commissioning on a mobile phone is similar to the Apple Matter Demo in Appendix I. For detailed steps, refer to the video lighting-attaching.mp4
provided on the cloud drive.
(6) A light component will appear in the Home screen after successful addition.
(7) Manipulate color temperature light
In addition to the function of turning on, off, and adjusting the brightness, the color temperature light can also be adjusted to different colors. For more information on how to control it on Apple Home, see the example video light-control.mp4
.
Update Firmware in DFU
We also provide firmware for the color temperature light and thermometer application that do not include a Bootloader. This subsection describes how to update the device firmware via DFU to update the new firmware TemperatureSensor_v2.signed.bin
to the Mars_B91 development board.
Hardware Requirements
-
Mars_B91 as a Matter device
-
Linux host running DFU software with at least one USB port
Software Requirements
dfu-util
tool for updating firmware
Connection Method
DFU Operation Steps
(1) Open the command line on the Linux host and enter the command to install dfu-util
.
$ sudo apt install dfu-util
(2) Before performing DFU, it is best to perform factory reset on the device.
If the device is not yet powered on, power it up first, and when the red LED starts blinking, toggle the jog wheel button on the development board to the left 3 times until the red LED returns to a short light and blinks to indicate that the reset is complete, and then unplug the device.
(3) Press the dial button of the device toward the center, press and hold the button while connecting to the USB port of the device with a data cable. When the red LED of the device is always on, it means the device enters the DFU mode.
(4) Enter the following command at the Linux host command line
$ sudo dfu-util --alt 1 --download TemperatureSensor_v2.signed.bin
This article takes the application firmware TemperatureSensor_v2.signed.bin
as an example. In actual use, you can replace it with your own firmware path name.
(5) DFU Update
You can refer to the example video DFU-process.mp4
for the update process. After the progress bar is finished there is still a need for firmware verification. Do not disconnect power until the red LED initiates a brief illumination followed by blinking, indicating DFU completion.
Verify the Updated Firmware
The steps to add the thermometer to the smart home ecosystem are the same as for the color temperature light, click on the device after completing the addition to see the interface as shown in the picture.
After successfully pairing and adding the temperature sensor to your Apple Home ecosystem following the procedures in the previous section, you can read ambient temperature data directly on your iPhone.