From 259a4586a15734c1677873457af0020702fc55bb Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Thu, 10 Oct 2024 20:01:38 +0800 Subject: [PATCH 1/7] [Bouffalo Lab] Add a script to demonstrate mfd partition generation (#35192) * [Bouffalo Lab] Add a script to demonstrate mfd partition generation * fix restyle * fix restyle * fix lint code and spell * fix lint code and spell * revert changes on Makefile of doc --- .../guides/bouffalolab/matter_factory_data.md | 249 ++++++++ docs/guides/index.md | 2 + examples/lighting-app/bouffalolab/README.md | 37 +- .../bouffalolab/generate_factory_data.py | 556 ++++++++++++++++++ 4 files changed, 827 insertions(+), 17 deletions(-) create mode 100644 docs/guides/bouffalolab/matter_factory_data.md create mode 100755 scripts/tools/bouffalolab/generate_factory_data.py diff --git a/docs/guides/bouffalolab/matter_factory_data.md b/docs/guides/bouffalolab/matter_factory_data.md new file mode 100644 index 00000000000000..9021cd80f61815 --- /dev/null +++ b/docs/guides/bouffalolab/matter_factory_data.md @@ -0,0 +1,249 @@ +# Introduction to Matter factory data + +Each Matter device should have it own unique factory data manufactured. + +This guide demonstrates what `Bouffalo Lab` provides to support factory data: + +- credential factory data protected by hardware security engine +- reference tool to generate factory data +- tool/method to program factory data + +# Matter factory data + +## How to enable + +One dedicate flash region allocates for factory data as below which is read-only +for firmware. + +```toml +name = "MFD" +address0 = 0x3FE000 +size0 = 0x1000 +``` + +To enable matter factory data feature, please append `-mfd` option at end of +target name. Take BL602 Wi-Fi Matter Light as example. + +``` +./scripts/build/build_examples.py --target bouffalolab-bl602dk-light-littlefs-mfd build +``` + +## Factory data + +This flash region is divided to two parts: + +- One is plain text data, such as Vendor ID, Product ID, Serial number and so + on. + + > For development/test purpose, all data can put in plain text data. + +- Other is cipher text data, such as private key for device attestation data. + + `Bouffalo Lab` provides hardware security engine to decrypt this part data + with **only hardware access** efuse key. + +Current supported data + +- DAC certificate and private key +- PAI certificate +- Certificate declaration + +- Discriminator ID +- Pass Code +- Spake2p iteration count, salt and verifier +- Vendor ID and name +- Product ID and name +- Product part number and product label +- Manufacturing date +- Hardware version and version string +- Serial Number +- Unique identifier + +> Note, it is available to add customer/product own information in factory data, +> please reference to `bl_mfd.h`/`bl_mfd.c` in SDK and reference generation +> script +> [generate_factory_data.py](../../../scripts/tools/bouffalolab/generate_factory_data.py) + +# Generate Matter factory data + +Script tool +[generate_factory_data.py](../../../scripts/tools/bouffalolab/generate_factory_data.py) +call `chip-cert` to generate test certificates and verify certificates. + +Please run below command to compile `chip-cert` tool under `connnectedhomeip` +repo. + +```shell +./scripts/build/build_examples.py --target linux-x64-chip-cert build +``` + +## Command options + +- `--cd`, certificate declare + + If not specified, `Chip-Test-CD-Signing-Cert.pem` and + `Chip-Test-CD-Signing-Key.pem` will sign a test certificate declare for + development and test purpose + +- `--pai_cert` and `--pai-key`, PAI certificate and PAI private key + + If not specified, `Chip-Test-PAI-FFF1-8000-Cert.pem` and + `Chip-Test-PAI-FFF1-8000-Key.pem` will be used for development and test + purpose. + +- `--dac_cert` and `--dac_key`, DAC certificate and DAC private key. + + If not specified, script will use PAI certificate and key specified + by`--pai_cert` and `--pai-key` to generate DAC certificate and private key + for development and test purpose. + +- `--discriminator`, discriminator ID + + If not specified, script will generate for user. + +- `--passcode`, passcode + + If not specified, script will generate for user. + +- `--spake2p_it` and `--spake2p_salt` + + If not specified, script will generate and calculate verifier for user. + +Please reference to `--help` for more detail. + +## Generate with default test certificates + +- Run following command to generate all plain text factory data + + Please create output folder first. Here takes `out/test-cert` as example. + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert + ``` + +- Run following command to generate factory data which encrypt private of + device attestation data + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --key + ``` + + > An example of hex string of 16 bytes: 12345678123456781234567812345678 + +After command executes successfully, the output folder will has files as below: + +- Test certificate declare file which file name ends with `cd.der` + + If user wants to reuse CD generated before, please specify CD with option + `--cd` as below. + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --cd + ``` + +- Test DAC certificate and DAC certificate key which file names ends with + `dac_cert.pem` and `dac_key.pem` separately. + +- QR code picture which file name ends with `onboard.png` +- On board information which file name ends with `onboard.txt` +- Matter factory data which file name ends with `mfd.bin`. + +## Generate with self-defined PAA/PAI certificates + +Self-defined PAA/PAI certificates may use in development and test scenario. But, +user should know it has limit to work with real ecosystem. + +- Export environment variables in terminal for easy operations + + ``` + export TEST_CERT_VENDOR_ID=130D # Vendor ID hex string + export TEST_CERT_CN=BFLB # Common Name + ``` + +- Generate PAA certificate and key to `out/cert` folder. + + ```shell + mkdir out/test-cert + ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type a --subject-cn "${TEST_CERT_CN} PAA 01" --valid-from "2020-10-15 14:23:43" --lifetime 7305 --out-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --subject-vid ${TEST_CERT_VENDOR_ID} + ``` + +- Convert PAA PEM format file to PAA DER format file + + ```shell + ./out/linux-x64-chip-cert/chip-cert convert-cert -d out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.der + ``` + + > Please save this PAA DER format file which will be used by `chip-tool` + > during commissioning. + +- Generate PAI certificate and key: + + ```shell + ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type i --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --valid-from "2020-10-15 14:23:43" --lifetime 7305 --ca-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem + ``` + +- Generate `MFD` in plain text data + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --paa_cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --paa_key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --pai_cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --pai_key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem + ``` + + > Appending `--key ` option to enable encrypt + > private key of attestation device data. + +## Generate with self-defined DAC certificate and key + +Self-defined DAC certificates may use in development and test scenario. But, +user should know it has limit to work with real ecosystem. + +- Export environment variables in terminal for easy operations + + ``` + export TEST_CERT_VENDOR_ID=130D # Vendor ID hex string + export TEST_CERT_PRODUCT_ID=1001 # Vendor ID hex string + export TEST_CERT_CN=BFLB # Common Name + ``` + +- Generate DAC certificate and key + + ```shell + out/linux-x64-chip-cert/chip-cert gen-att-cert --type d --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --subject-pid ${TEST_CERT_VENDOR_ID} --valid-from "2020-10-16 14:23:43" --lifetime 5946 --ca-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-DAC-Key-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem --out out/test-cert/Chip-DAC-Cert-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem + ``` + + > **Note**, `--valid-from` and `--lifetime` should be in `--valid-from` and + > `--lifetime` of PAI certificate. + +- Generate `MFD` in plain text data + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --pai_cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --dac_cert out/test-cert/Chip-DAC-Cert-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem --dac_key out/test-cert/Chip-DAC-Key-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem + ``` + + > Appending `--key ` option to enable encrypt + > private key of attestation device data. + +# Program factory data + +After each target built successfully, a flash programming python script will be +generated under out folder. + +Take BL616 Wi-Fi Matter Light as example, `chip-bl616-lighting-example.flash.py` +is using to program firmware, and also for factory data and factory decryption +key. + +```shell +/out/bouffalolab-bl616dk-light-wifi-mfd/chip-bl616-lighting-example.flash.py --port --mfd out/test-cert/ +``` + +> If `MFD` file has cipher text data, please append +> `--key ` option to program to this key to efuse. + +- Limits on BL IOT SDK + + If developer would like to program `MFD` with all plain text data, option + `--key ` needs pass to script, otherwise, flash tool + will raise an error. And SoC BL602, BL702 and BL702L use BL IOT SDK for + Matter Application. + +Please free contact to `Bouffalo Lab` for DAC provider service and higher +security solution, such as SoC inside certificate requesting. diff --git a/docs/guides/index.md b/docs/guides/index.md index 14d9caf7e21839..c1a879277865ed 100644 --- a/docs/guides/index.md +++ b/docs/guides/index.md @@ -9,6 +9,7 @@ and features. :hidden: * +bouffalolab/matter_factory_data esp32/README nxp/README ti/ti_matter_overview @@ -23,6 +24,7 @@ ti/ti_matter_overview - [Android - Building](./android_building.md) - [Apple - Testing with iPhone, iPad, macOS, Apple TV, HomePod, Watch, etc](./darwin.md) - [ASR - Getting Started Guide](./asr_getting_started_guide.md) +- [Bouffalo Lab - Matter factory data generation](./bouffalolab/matter_factory_data.md) - [Espressif (ESP32) - Getting Started Guide](./esp32/README.md) - [Infineon PSoC6 - Software Update](./infineon_psoc6_software_update.md) - [Linux - Simulated Devices](./simulated_device_linux.md) diff --git a/examples/lighting-app/bouffalolab/README.md b/examples/lighting-app/bouffalolab/README.md index d2fd8b72afadf6..b39f65b96d77c7 100644 --- a/examples/lighting-app/bouffalolab/README.md +++ b/examples/lighting-app/bouffalolab/README.md @@ -1,4 +1,4 @@ -# `Bouffalo Lab` +# Matter `Bouffalo Lab` Lighting Example This example functions as a light bulb device type, with on/off and level capabilities and uses a test Vendor ID (VID) and a Product ID (PID) @@ -17,8 +17,6 @@ Legacy supported boards: - `BL602-NIGHT-LIGHT` - `XT-ZB6-DevKit` - `BL706-NIGHT-LIGHT` -- `BL706DK` -- `BL704LDK` > Warning: Changing the VID/PID may cause compilation problems, we recommend > leaving it as the default while using this example. @@ -99,6 +97,7 @@ The following steps take examples for `BL602DK`, `BL704LDK` and `BL706DK`. ``` ./scripts/build/build_examples.py --target bouffalolab-bl602dk-light build + ./scripts/build/build_examples.py --target bouffalolab-bl616dk-light-wifi build ./scripts/build/build_examples.py --target bouffalolab-bl704ldk-light build ./scripts/build/build_examples.py --target bouffalolab-bl706dk-light build ``` @@ -113,25 +112,28 @@ The following steps take examples for `BL602DK`, `BL704LDK` and `BL706DK`. ### Build options with build_examples.py -- `-wifi`, to specify that connectivity Wi-Fi is enabled for Matter - application. +- `-wifi`, specifies to use Wi-Fi for Matter application. - - BL602 uses `-wifi` by default - - BL702 needs specify to use BL706 + BL602 for Wi-Fi connectivity. + - BL602 uses Wi-Fi by default. `-wifi` could be elided. + - BL702 needs it to specify to use BL706 + BL602 for Wi-Fi. -- `-thread`, to specify that connectivity Thread is enabled for Matter - application. +- `-thread`, specifies to use Thread for Matter application. - - BL70X uses `-thread` by default. + - BL70X uses Thread by default. `-thread` could be elided. -- `-ethernet`, to specify that connectivity Ethernet is enabled for Matte - application. +- `-ethernet`, specifies to use Ethernet for Matter application. - - BL706 needs specify to use Ethernet connectivity. + - BL706 needs it to specify to use Ethernet. -- `-easyflash`, to specify that `easyflash` is used for flash storage access. +- `-littlefs`, specifies to use `littlefs` for flash access. +- `-easyflash`, specifies to use `easyflash` for flash access. + - for platform BL602/BL70X, it is necessary to specify one of `-easyflash` + and `-littlefs`. - `-mfd`, enable Matter factory data feature, which load factory data from `MFD` partition + - Please refer to + [Bouffalo Lab Matter factory data guide](../../../docs/guides/bouffalolab/matter_factory_data.md) + or contact to `Bouffalo Lab` for support. - `-shell`, enable command line - `-rpc`, enable Pigweed RPC feature - `-115200`, set UART baudrate to 115200 for log and command line @@ -175,9 +177,10 @@ The following steps take examples for `BL602DK`, `BL704LDK` and `BL706DK`. ```shell - ./out/bouffalolab-bl602dk-light/chip-bl602-lighting-example.flash.py --port /dev/ttyACM0 - ./out/bouffalolab-bl704ldk-light/chip-bl702l-lighting-example.flash.py --port /dev/ttyACM0 - ./out/bouffalolab-bl706dk-light/chip-bl702-lighting-example.flash.py --port /dev/ttyACM0 + ./out/bouffalolab-bl602dk-light-littlefs/chip-bl602-lighting-example.flash.py --port /dev/ttyACM0 + ./out/bouffalolab-bl616dk-light-wifi/chip-bl616dk-lighting-example.flash.py --port /dev/ttyACM0 + ./out/bouffalolab-bl704ldk-light-littlefs/chip-bl702l-lighting-example.flash.py --port /dev/ttyACM0 + ./out/bouffalolab-bl706dk-light-littlefs/chip-bl702-lighting-example.flash.py --port /dev/ttyACM0 ``` - To wipe out flash and download image, please append `--erase` diff --git a/scripts/tools/bouffalolab/generate_factory_data.py b/scripts/tools/bouffalolab/generate_factory_data.py new file mode 100755 index 00000000000000..28f362ba2d3b21 --- /dev/null +++ b/scripts/tools/bouffalolab/generate_factory_data.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +# +# Copyright (c) 2022 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import base64 +import binascii +import logging as log +import os +import random +import secrets +import subprocess +import sys +from datetime import datetime, timedelta +from pathlib import Path + +from Crypto.Cipher import AES +from cryptography import x509 +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.serialization import load_der_private_key +from cryptography.x509.oid import ObjectIdentifier + +MATTER_ROOT = os.path.dirname(os.path.realpath(__file__))[:-len("/scripts/tools/bouffalolab")] + +TEST_CD_CERT = MATTER_ROOT + "/credentials/test/certification-declaration/Chip-Test-CD-Signing-Cert.pem" +TEST_CD_KEY = MATTER_ROOT + "/credentials/test/certification-declaration/Chip-Test-CD-Signing-Key.pem" +TEST_PAA_CERT = MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAA-FFF1-Cert.pem" +TEST_PAA_KEY = MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAA-FFF1-Key.pem" +TEST_PAI_CERT = MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAI-FFF1-8000-Cert.pem" +TEST_PAI_KEY = MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAI-FFF1-8000-Key.pem" +TEST_CHIP_CERT = MATTER_ROOT + "/out/linux-x64-chip-cert/chip-cert" +TEST_CD_TYPE = 1 # 0 - development, 1 - provisional, 2 - official + + +def gen_test_passcode(passcode): + + INVALID_PASSCODES = [0, 11111111, 22222222, 33333333, 44444444, + 55555555, 66666666, 77777777, 88888888, 99999999, + 12345678, 87654321] + + def check_passcode(passcode): + return 0 <= passcode <= 99999999 and passcode not in INVALID_PASSCODES + + if isinstance(passcode, int): + if check_passcode(passcode): + raise Exception("passcode is invalid value.") + return passcode + + passcode = -1 + while not check_passcode(passcode): + passcode = random.randint(0, 99999999) + + return passcode + + +def gen_test_discriminator(discriminator): + + if isinstance(discriminator, int): + if discriminator > 0xfff: + raise Exception("discriminator is invalid value.") + + discriminator = random.randint(0, 0xfff) + + return discriminator + + +def gen_test_unique_id(unique_id): + + if isinstance(unique_id, bytes): + if len(unique_id) != 16: + raise Exception("rotating unique id has invalid length.") + return unique_id + + unique_id = secrets.token_bytes(16) + + return unique_id + + +def gen_test_spake2(passcode, spake2p_it, spake2p_salt, spake2p_verifier=None): + + sys.path.insert(0, os.path.join(MATTER_ROOT, 'scripts', 'tools', 'spake2p')) + from spake2p import generate_verifier + + if isinstance(spake2p_it, int): + if not 1000 <= spake2p_it <= 100000: + raise Exception("SPAKE2+ iteration count out of range.") + else: + spake2p_it = random.randint(1000, 100000) + + if spake2p_salt is None: + spake2p_salt_len = random.randint(16, 32) + spake2p_salt = bytes(random.sample(range(0, 255), spake2p_salt_len)) + else: + spake2p_salt = base64.b64decode(spake2p_salt) + if not 16 <= len(spake2p_salt) <= 32: + raise Exception("SPAKE2+ slat is invalid.") + + if spake2p_verifier is None: + spake2p_verifier = generate_verifier(passcode, spake2p_salt, spake2p_it) + else: + if generate_verifier(passcode, spake2p_salt, spake2p_it) != spake2p_verifier: + raise Exception("SPAKE2+ verifier is invalid.") + + return spake2p_it, spake2p_salt, spake2p_verifier + + +def gen_test_certs(chip_cert: str, + output: str, + vendor_id: int, + product_id: int, + device_name: str, + cd_cert: str = None, + cd_key: str = None, + cd: str = None, + paa_cert: str = None, + paa_key: str = None, + pai_cert: str = None, + pai_key: str = None, + dac_cert: str = None, + dac_key: str = None): + + def parse_cert_file(cert): + + def get_subject_attr(subject, oid): + try: + return subject.get_attributes_for_oid(oid) + except Exception: + return None + + if not os.path.isfile(cert): + return None, None, None, None, None + + with open(cert, 'rb') as cert_file: + cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend()) + + vendor_id = None + product_id = None + for attribute in cert.subject: + if ObjectIdentifier('1.3.6.1.4.1.37244.2.1') == attribute.oid: + vendor_id = int(attribute.value, 16) + if ObjectIdentifier('1.3.6.1.4.1.37244.2.2') == attribute.oid: + product_id = int(attribute.value, 16) + + issue_date = cert.not_valid_before + expire_date = cert.not_valid_after + + return vendor_id, product_id, issue_date, expire_date + + def verify_certificates(chip_cert, paa_cert, pai_cert, dac_cert): + + if not os.path.isfile(pai_cert) or not os.path.isfile(dac_cert): + raise Exception("PAI certificate or DAC certificate is not specified.") + + with open(pai_cert, 'rb') as cert_file: + cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend()) + pai_public_key = cert.public_key() + + with open(dac_cert, 'rb') as cert_file: + cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend()) + + try: + pai_public_key.verify(cert.signature, cert.tbs_certificate_bytes, ec.ECDSA(hashes.SHA256())) + except Exception: + raise Exception("Failed to verify DAC signature with PAI certificate.") + + if (pai_cert != TEST_PAI_CERT and paa_cert != TEST_PAA_CERT) or (pai_cert == TEST_PAI_CERT and paa_cert == TEST_PAA_CERT): + if os.path.isfile(paa_cert): + cmd = [chip_cert, "validate-att-cert", + "--dac", dac_cert, + "--pai", pai_cert, + "--paa", paa_cert, + ] + log.info("Verify Certificate Chain: {}".format(" ".join(cmd))) + subprocess.run(cmd) + + def gen_dac_certificate(chip_cert, device_name, vendor_id, product_id, pai_cert, pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date): + def gen_valid_times(issue_date, expire_date): + now = datetime.now() - timedelta(days=1) + + if not (issue_date <= now <= expire_date): + raise Exception("Invalid time in test PAI to generate DAC.") + + return now.strftime('%Y%m%d%H%M%SZ'), (expire_date - now).days + + if not os.path.isfile(dac_cert) or not os.path.isfile(dac_key): + if not os.path.isfile(pai_cert) or not os.path.isfile(pai_key): + raise Exception("No test PAI certificate/key specified for test DAC generation.") + + valid_from, lifetime = gen_valid_times(pai_issue_date, pai_expire_date) + cmd = [chip_cert, "gen-att-cert", + "--type", "d", # device attestation certificate + "--subject-cn", device_name + " Test DAC 0", + "--subject-vid", hex(vendor_id), + "--subject-pid", hex(product_id), + "--ca-cert", pai_cert, + "--ca-key", pai_key, + "--out", dac_cert, + "--out-key", dac_key, + "--valid-from", valid_from, + "--lifetime", str(lifetime), + ] + log.info("Generate DAC: {}".format(" ".join(cmd))) + subprocess.run(cmd) + + def convert_pem_to_der(chip_cert, action, pem): + + if not os.path.isfile(pem): + raise Exception("File {} is not existed.".format(pem)) + + der = Path(pem).with_suffix(".der") + if not os.path.isfile(der): + cmd = [chip_cert, action, pem, der, "--x509-der", ] + subprocess.run(cmd) + + return der + + def gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd): + + if os.path.isfile(cd): + return + + cmd = [chip_cert, "gen-cd", + "--key", cd_key, + "--cert", cd_cert, + "--out", cd, + "--format-version", "1", + "--vendor-id", hex(vendor_id), + "--product-id", hex(product_id), + "--device-type-id", "0x1234", + "--certificate-id", "ZIG20141ZB330001-24", + "--security-level", "0", + "--security-info", "0", + "--certification-type", str(TEST_CD_TYPE), + "--version-number", "9876", + ] + + if dac_vendor_id != vendor_id or dac_product_id != product_id: + cmd += ["--dac-origin-vendor-id", hex(dac_vendor_id), + "--dac-origin-product-id", hex(dac_product_id), + ] + + log.info("Generate CD: {}".format(" ".join(cmd))) + subprocess.run(cmd) + + pai_vendor_id, pai_product_id, pai_issue_date, pai_expire_date = parse_cert_file(pai_cert) + + dac_vendor_id = pai_vendor_id if pai_vendor_id else vendor_id + dac_product_id = pai_product_id if pai_product_id else product_id + gen_dac_certificate(chip_cert, device_name, dac_vendor_id, dac_product_id, pai_cert, + pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date) + + dac_cert_der = convert_pem_to_der(chip_cert, "convert-cert", dac_cert) + dac_key_der = convert_pem_to_der(chip_cert, "convert-key", dac_key) + pai_cert_der = convert_pem_to_der(chip_cert, "convert-cert", pai_cert) + + dac_vendor_id, dac_product_id, *_ = parse_cert_file(dac_cert) + paa_vendor_id, paa_product_id, *_ = parse_cert_file(paa_cert) + + verify_certificates(chip_cert, paa_cert, pai_cert, dac_cert) + + gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd) + + return cd, pai_cert_der, dac_cert_der, dac_key_der + + +def gen_mfd_partition(args, mfd_output): + + def int_to_2bytearray_l(intvalue): + src = bytearray(2) + src[1] = (intvalue >> 8) & 0xFF + src[0] = (intvalue >> 0) & 0xFF + return src + + def int_to_4bytearray_l(intvalue): + src = bytearray(4) + src[3] = (intvalue >> 24) & 0xFF + src[2] = (intvalue >> 16) & 0xFF + src[1] = (intvalue >> 8) & 0xFF + src[0] = (intvalue >> 0) & 0xFF + return src + + def gen_efuse_aes_iv(): + return bytes(random.sample(range(0, 0xff), 12) + [0] * 4) + + def read_file(rfile): + with open(rfile, 'rb') as _f: + return _f.read() + + def get_private_key(der): + with open(der, 'rb') as file: + keys = load_der_private_key(file.read(), password=None, backend=default_backend()) + private_key = keys.private_numbers().private_value.to_bytes(32, byteorder='big') + + return private_key + + def encrypt_data(data_bytearray, key_bytearray, iv_bytearray): + data_bytearray += bytes([0] * (16 - (len(data_bytearray) % 16))) + cryptor = AES.new(key_bytearray, AES.MODE_CBC, iv_bytearray) + ciphertext = cryptor.encrypt(data_bytearray) + return ciphertext + + def convert_to_bytes(data): + if isinstance(data, bytes) or isinstance(data, str): + if isinstance(data, str): + return data.encode() + else: + return data + elif isinstance(data, int): + byte_len = int((data.bit_length() + 7) / 8) + return data.to_bytes(byte_len, byteorder='little') + elif data is None: + return bytes([]) + else: + raise Exception("Data is invalid type: {}".format(type(data))) + + def gen_tlvs(mfdDict, need_sec): + MFD_ID_RAW_MASK = 0x8000 + + sec_tlvs = bytes([]) + raw_tlvs = bytes([]) + + for name in mfdDict.keys(): + d = mfdDict[name] + if d["sec"] and need_sec: + if d["len"] and d["len"] < len(d["data"]): + raise Exception("Data size of {} is over {}".format(name, d["len"])) + sec_tlvs += int_to_2bytearray_l(d["id"]) + sec_tlvs += int_to_2bytearray_l(len(d["data"])) + sec_tlvs += d["data"] + + for name in mfdDict.keys(): + d = mfdDict[name] + if not d["sec"] or not need_sec: + if d["len"] and d["len"] < len(d["data"]): + raise Exception("Data size of {} is over {}".format(name, d["len"])) + raw_tlvs += int_to_2bytearray_l(d["id"] + MFD_ID_RAW_MASK) + raw_tlvs += int_to_2bytearray_l(len(d["data"])) + raw_tlvs += d["data"] + + return sec_tlvs, raw_tlvs + + mfdDict = { + "aes_iv": {'sec': False, "id": 1, "len": 16, "data": gen_efuse_aes_iv() if args.key else bytes([0] * 16)}, + "dac_cert": {'sec': False, "id": 2, "len": None, "data": read_file(args.dac_cert)}, + "dac_key": {'sec': True, "id": 3, "len": None, "data": get_private_key(args.dac_key)}, + "passcode": {'sec': False, "id": 4, "len": 4, "data": convert_to_bytes(args.passcode)}, + "pai_cert": {'sec': False, "id": 5, "len": None, "data": read_file(args.pai_cert)}, + "cd": {'sec': False, "id": 6, "len": None, "data": read_file(args.cd)}, + "sn": {'sec': False, "id": 7, "len": 32, "data": convert_to_bytes(args.sn)}, + "discriminator": {'sec': False, "id": 8, "len": 2, "data": convert_to_bytes(args.discriminator)}, + "uid": {'sec': False, "id": 9, "len": 32, "data": convert_to_bytes(args.unique_id)}, + "spake2p_it": {'sec': False, "id": 10, "len": 4, "data": convert_to_bytes(args.spake2p_it)}, + "spake2p_salt": {'sec': False, "id": 11, "len": 32, "data": convert_to_bytes(args.spake2p_salt)}, + "spake2p_verifier": {'sec': False, "id": 12, "len": None, "data": convert_to_bytes(args.spake2p_verifier)}, + "vendor_name": {'sec': False, "id": 13, "len": 32, "data": convert_to_bytes(args.vendor_name)}, + "vendor_id": {'sec': False, "id": 14, "len": 2, "data": convert_to_bytes(args.vendor_id)}, + "product_name": {'sec': False, "id": 15, "len": 32, "data": convert_to_bytes(args.product_name)}, + "product_id": {'sec': False, "id": 16, "len": 2, "data": convert_to_bytes(args.product_id)}, + "product_part_no": {'sec': False, "id": 17, "len": 32, "data": convert_to_bytes(args.product_part_no)}, + "product_url": {'sec': False, "id": 18, "len": 256, "data": convert_to_bytes(args.product_url)}, + "product_label": {'sec': False, "id": 19, "len": 64, "data": convert_to_bytes(args.product_label)}, + "manufactoring_date": {'sec': False, "id": 20, "len": 16, "data": convert_to_bytes(args.manufactoring_date)}, + "hardware_ver": {'sec': False, "id": 21, "len": 4, "data": convert_to_bytes(args.hardware_version)}, + "hardware_ver_str": {'sec': False, "id": 22, "len": 64, "data": convert_to_bytes(args.hardware_version_string)}, + } + + sec_tlvs, raw_tlvs = gen_tlvs(mfdDict, args.key) + + output = bytes([]) + + sec_tlvs = sec_tlvs and encrypt_data(sec_tlvs, args.key, mfdDict["aes_iv"]["data"]) + + output = int_to_4bytearray_l(len(sec_tlvs)) + output += sec_tlvs + output += int_to_4bytearray_l(binascii.crc32(sec_tlvs)) + output += int_to_4bytearray_l(len(raw_tlvs)) + output += raw_tlvs + output += int_to_4bytearray_l(binascii.crc32(raw_tlvs)) + + with open(mfd_output, "wb+") as fp: + fp.write(output) + + +def gen_onboarding_data(args, onboard_txt, onboard_png, rendez=6): + + try: + import qrcode + from SetupPayload import CommissioningFlow, SetupPayload + except ImportError: + sys.path.append(os.path.join(MATTER_ROOT, "src/setup_payload/python")) + try: + import qrcode + from SetupPayload import CommissioningFlow, SetupPayload + except Exception: + raise Exception("Please make sure qrcode has been installed.") + else: + raise Exception("Please make sure qrcode has been installed.") + + setup_payload = SetupPayload(discriminator=args.discriminator, + pincode=args.passcode, + rendezvous=rendez, + flow=CommissioningFlow.Standard, + vid=args.vendor_id, + pid=args.product_id) + with open(onboard_txt, "w") as manual_code_file: + manual_code_file.write("Manualcode : " + setup_payload.generate_manualcode() + "\n") + manual_code_file.write("QRCode : " + setup_payload.generate_qrcode()) + qr = qrcode.make(setup_payload.generate_qrcode()) + qr.save(onboard_png) + + return setup_payload.generate_manualcode(), setup_payload.generate_qrcode() + + +def main(): + + def check_arg(args): + + if not isinstance(args.output, str) or not os.path.exists(args.output): + raise Exception("output path is not specified or not existed.") + log.info("output path: {}".format(args.output)) + + if not isinstance(args.chip_cert, str) or not os.path.exists(args.chip_cert): + raise Exception("chip-cert should be built before and is specified.") + log.info("chip-cert path: {}".format(args.chip_cert)) + + def to_bytes(input): + if isinstance(input, str): + return bytearray.fromhex(input) + elif isinstance(input, bytes): + return input + else: + return None + + parser = argparse.ArgumentParser(description="Bouffalo Lab Factory Data generator tool") + + parser.add_argument("--dac_cert", type=str, help="DAC certificate file.") + parser.add_argument("--dac_key", type=str, help="DAC certificate privat key.") + parser.add_argument("--passcode", type=int, help="Setup pincode, optional.") + parser.add_argument("--pai_cert", type=str, default=TEST_PAI_CERT, help="PAI certificate file.") + parser.add_argument("--cd", type=str, help="Certificate Declaration file.") + parser.add_argument("--sn", type=str, default="Test SN", help="Serial Number, optional.") + parser.add_argument("--discriminator", type=int, help="Discriminator ID, optional.") + parser.add_argument("--unique_id", type=base64.b64decode, help="Rotating Unique ID in hex string, optional.") + parser.add_argument("--spake2p_it", type=int, default=None, help="Spake2+ iteration count, optional.") + parser.add_argument("--spake2p_salt", type=base64.b64decode, help="Spake2+ salt in hex string, optional.") + + parser.add_argument("--vendor_id", type=int, default=0x130D, help="Vendor Identification, mandatory.") + parser.add_argument("--vendor_name", type=str, default="Bouffalo Lab", help="Vendor Name string, optional.") + parser.add_argument("--product_id", type=int, default=0x1001, help="Product Identification, mandatory.") + parser.add_argument("--product_name", type=str, default="Test Product", help="Product Name string, optional.") + + parser.add_argument("--product_part_no", type=str, help="Product Part number, optional.") + parser.add_argument("--product_url", type=str, help="Product Web URL, optional.") + parser.add_argument("--product_label", type=str, help="Product Web URL, optional.") + parser.add_argument("--manufactoring_date", type=str, help="Product Web URL, optional.") + parser.add_argument("--hardware_version", type=int, help="Product Web URL, optional.") + parser.add_argument("--hardware_version_string", type=str, help="Product Web URL, optional.") + parser.add_argument("--rendezvous", type=int, default=6, help="Rendezvous Mode for QR code generation") + + parser.add_argument("--output", type=str, help="output path.") + parser.add_argument("--key", type=str, help="Encrypt private part in mfd.") + + parser.add_argument("--cd_cert", type=str, default=TEST_CD_CERT, help="for test, to sign certificate declaration.") + parser.add_argument("--cd_key", type=str, default=TEST_CD_KEY, help="for test, to sign certificate declaration.") + parser.add_argument("--paa_cert", type=str, default=TEST_PAA_CERT, help="for test, to verify certificate chain.") + parser.add_argument("--paa_key", type=str, default=TEST_PAA_KEY, help="for test, to sign pai certificate.") + parser.add_argument("--pai_key", type=str, default=TEST_PAI_KEY, help="for test, to sign dac certificate.") + parser.add_argument("--chip_cert", type=str, default=TEST_CHIP_CERT, help="for test, the tool to issue dac certificate.") + + args = parser.parse_args() + + log.basicConfig(format='[%(levelname)s] %(message)s', level=log.INFO) + + check_arg(args) + + passcode = gen_test_passcode(args.passcode) + discriminator = gen_test_discriminator(args.discriminator) + unique_id = gen_test_unique_id(args.unique_id) + spake2p_it, spake2p_salt, spake2p_verifier = gen_test_spake2(passcode, args.spake2p_it, args.spake2p_salt) + + vp_info = "{}_{}".format(hex(args.vendor_id), hex(args.product_id)) + vp_disc_info = "{}_{}_{}".format(hex(args.vendor_id), hex(args.product_id), discriminator) + if args.dac_cert is None: + args.dac_cert = os.path.join(args.output, "out_{}_dac_cert.pem".format(vp_disc_info)) + args.dac_key = os.path.join(args.output, "out_{}_dac_key.pem".format(vp_disc_info)) + + if args.cd is None: + args.cd = os.path.join(args.output, "out_{}_cd.der".format(vp_info)) + + cd, pai_cert_der, dac_cert_der, dac_key_der = gen_test_certs(args.chip_cert, + args.output, + args.vendor_id, + args.product_id, + args.vendor_name, + args.cd_cert, + args.cd_key, + args.cd, + args.paa_cert, + args.paa_key, + args.pai_cert, + args.pai_key, + args.dac_cert, + args.dac_key) + + mfd_output = os.path.join(args.output, "out_{}_mfd.bin".format(vp_disc_info)) + args.dac_cert = dac_cert_der + args.dac_key = dac_key_der + args.passcode = passcode + args.pai_cert = pai_cert_der + args.cd = cd + args.discriminator = discriminator + args.unique_id = unique_id + args.spake2p_it = spake2p_it + args.spake2p_salt = spake2p_salt + args.spake2p_verifier = spake2p_verifier + args.key = to_bytes(args.key) + gen_mfd_partition(args, mfd_output) + + onboard_txt = os.path.join(args.output, "out_{}_onboard.txt".format(vp_disc_info)) + onboard_png = os.path.join(args.output, "out_{}_onboard.png".format(vp_disc_info)) + manualcode, qrcode = gen_onboarding_data(args, onboard_txt, onboard_png, args.rendezvous) + + log.info("") + log.info("Output as below: ") + log.info("Passcode: {}".format(passcode)) + log.info("Discriminator ID: {}".format(discriminator)) + log.info("Rotating Unique ID: {}".format(unique_id.hex())) + log.info("Rotating Unique ID base64 code: {}".format(base64.b64encode(unique_id).decode())) + log.info("SPAKE2+ iteration: {}".format(spake2p_it)) + log.info("SPAKE2+ slat: {}".format(spake2p_salt.hex())) + log.info("SPAKE2+ slat base code: {}".format(base64.b64encode(spake2p_salt).decode())) + log.info("Manual code: {}".format(manualcode)) + log.info("QR code: {}".format(qrcode)) + + log.info("") + log.info("MFD partition file: {}".format(mfd_output)) + log.info("QR code PNG file: {}".format(onboard_png)) + + +if __name__ == "__main__": + main() From 19299cf90b3cf27f430de125cb9eb29363c279d2 Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Tue, 7 Jan 2025 21:56:02 +0800 Subject: [PATCH 2/7] =?UTF-8?q?[bouffalo=20lab]=20fix=20crash=20issues=20i?= =?UTF-8?q?n=20route=20hook=20and=20rpc=20uart=20driver=20mod=E2=80=A6=20(?= =?UTF-8?q?#36944)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [bouffalo lab] fix crash issues in route hook and rpc uart driver modules * Restyled by clang-format --------- Co-authored-by: Restyled.io --- .../platform/bouffalolab/bl602/lwipopts/lwipopts.h | 2 +- .../bouffalolab/common/route_hook/bl_route_hook.c | 10 ++++++++-- .../bouffalolab/common/rpc/pw_sys_io/sys_io.cc | 4 ++-- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h index ba744a119d77e3..93c14da58cfbbb 100644 --- a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h +++ b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h @@ -61,7 +61,7 @@ a lot of data that needs to be copied, this should be set high. */ /* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One per active UDP "connection". */ -#define MEMP_NUM_UDP_PCB 8 +#define MEMP_NUM_UDP_PCB 12 /* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. */ diff --git a/examples/platform/bouffalolab/common/route_hook/bl_route_hook.c b/examples/platform/bouffalolab/common/route_hook/bl_route_hook.c index 0da6d1bfb34383..f9f35ba8d5da26 100644 --- a/examples/platform/bouffalolab/common/route_hook/bl_route_hook.c +++ b/examples/platform/bouffalolab/common/route_hook/bl_route_hook.c @@ -168,12 +168,12 @@ int8_t bl_route_hook_init(void) goto exit; } - for (bl_route_hook_t * iter = s_hooks; iter != NULL; iter++) + for (bl_route_hook_t * iter = s_hooks; iter != NULL; iter = iter->next) { if (iter->netif == lwip_netif) { ret = 0; - break; + goto exit; } } @@ -194,6 +194,12 @@ int8_t bl_route_hook_init(void) hook->netif = lwip_netif; hook->pcb = raw_new_ip_type(IPADDR_TYPE_V6, IP6_NEXTH_ICMP6); + if (NULL == hook->pcb) + { + ret = -1; + goto exit; + } + hook->pcb->flags |= RAW_FLAGS_MULTICAST_LOOP; hook->pcb->chksum_reqd = 1; // The ICMPv6 header checksum offset diff --git a/examples/platform/bouffalolab/common/rpc/pw_sys_io/sys_io.cc b/examples/platform/bouffalolab/common/rpc/pw_sys_io/sys_io.cc index b7212e48ad8a5f..a2c847f7ce9c96 100644 --- a/examples/platform/bouffalolab/common/rpc/pw_sys_io/sys_io.cc +++ b/examples/platform/bouffalolab/common/rpc/pw_sys_io/sys_io.cc @@ -31,14 +31,14 @@ Status ReadByte(std::byte * dest) return Status::InvalidArgument(); int16_t ret = uartRead(reinterpret_cast(dest), 1); - return ret <= 0 ? Status::FailedPrecondition() : OkStatus(); + return ret < 0 ? Status::FailedPrecondition() : OkStatus(); } Status WriteByte(std::byte b) { int16_t ret = uartWrite(reinterpret_cast(&b), 1); - return ret <= 0 ? Status::FailedPrecondition() : OkStatus(); + return ret < 0 ? Status::FailedPrecondition() : OkStatus(); } // Writes a string using pw::sys_io, and add newline characters at the end. From 456b8f1fa40af7d346ec8f545ccd9202e8ea404f Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Wed, 8 Jan 2025 00:09:51 +0800 Subject: [PATCH 3/7] =?UTF-8?q?[bouffalo=20lab]=20add=20bl616=20lighting?= =?UTF-8?q?=20example=20with=20Wi-Fi=20and=20Thread=20suppo=E2=80=A6=20(#3?= =?UTF-8?q?6954)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [bouffalo lab] add bl616 lighting example with Wi-Fi and Thread supported * Restyled by gn --------- Co-authored-by: Restyled.io Co-authored-by: Andrei Litvin --- .../bouffalolab/toolchain/riscv_toolchain.gni | 7 +- .../lighting-app/bouffalolab/bl602/BUILD.gn | 1 - examples/lighting-app/bouffalolab/bl616/.gn | 28 + .../lighting-app/bouffalolab/bl616/BUILD.gn | 293 ++++ .../bouffalolab/bl616/CHIPProjectConfig.h | 116 ++ .../bouffalolab/bl616/FreeRTOSConfig.h | 142 ++ .../lighting-app/bouffalolab/bl616/args.gni | 34 + .../bouffalolab/bl616/build_overrides | 1 + .../lighting-app/bouffalolab/bl616/mboard.h | 52 + .../bl616/third_party/connectedhomeip | 1 + .../lighting-app/bouffalolab/bl702/BUILD.gn | 1 - .../lighting-app/bouffalolab/bl702l/BUILD.gn | 1 - .../lighting-app/bouffalolab/bl702l/mboard.h | 170 +-- .../bouffalolab/common/AppTask.cpp | 129 +- .../lighting-app/bouffalolab/common/AppTask.h | 12 +- examples/platform/bouffalolab/bl616/BUILD.gn | 22 + examples/platform/bouffalolab/bl616/args.gni | 21 + .../bouffalolab/bl616/bl616_lwip_hooks.h | 15 + .../bl616/flash_config/partition_cfg_4M.toml | 141 ++ .../platform/bouffalolab/bl616/lwipopts.h | 180 +++ .../common/bouffalo_sdk/demo_pwm.c | 157 ++ .../common/bouffalo_sdk/platform_port.cpp | 63 + .../bouffalolab/common/bouffalo_sdk/uart.c | 228 +++ .../bouffalolab/common/bouffalo_sdk/uart.h | 37 + .../bouffalolab/common/plat/platform.cpp | 2 +- scripts/build/build/targets.py | 38 +- scripts/build/builders/bouffalolab.py | 98 +- .../build/testdata/all_targets_linux_x64.txt | 2 +- .../flashing/bouffalolab_firmware_utils.py | 162 ++- src/lib/shell/BUILD.gn | 13 +- src/lib/shell/MainLoopBouffalolab.cpp | 43 + src/lib/shell/streamer_bouffalolab.cpp | 172 ++- src/lwip/BUILD.gn | 20 +- src/platform/BUILD.gn | 12 +- src/platform/bouffalolab/BL602/BUILD.gn | 2 + .../BL602/NetworkCommissioningDriver.cpp | 10 +- .../bouffalolab/BL602/PlatformManagerImpl.cpp | 2 - src/platform/bouffalolab/BL616/BUILD.gn | 107 ++ .../bouffalolab/BL616/CHIPMem-Platform.cpp | 87 ++ .../BL616/ConfigurationManagerImpl.cpp | 46 + .../BL616/ConnectivityManagerImpl.cpp | 103 ++ .../BL616/DiagnosticDataProviderImpl.cpp | 139 ++ .../BL616/NetworkCommissioningDriver.cpp | 463 ++++++ .../BL616/NetworkCommissioningDriver.h | 150 ++ .../bouffalolab/BL616/PlatformManagerImpl.cpp | 108 ++ .../BL616/ThreadStackManagerImpl.cpp | 165 +++ src/platform/bouffalolab/BL616/args.gni | 40 + .../BL616/bl616-chip-mbedtls-config.h | 173 +++ .../bl616-openthread-core-bl-config-check.h | 36 + .../BL616/bl616-openthread-core-bl-config.h | 114 ++ .../bouffalolab/BL616/wifi_mgmr_portable.c | 59 + .../bouffalolab/BL616/wifi_mgmr_portable.h | 18 + src/platform/bouffalolab/BL702/BUILD.gn | 9 +- .../bouffalolab/BL702/PlatformManagerImpl.cpp | 2 - src/platform/bouffalolab/BL702L/BUILD.gn | 9 +- .../BL702L/PlatformManagerImpl.cpp | 11 +- .../BL702L/bl702l-openthread-core-bl-config.h | 1 + .../bouffalolab/common/BLConfig_littlefs.cpp | 17 + .../bouffalolab/common/BLEManagerImpl.cpp | 8 +- .../common/ConfigurationManagerImpl.cpp | 11 +- .../common/ConnectivityManagerImpl.cpp | 3 + .../common/ConnectivityManagerImpl.h | 1 + .../common/DiagnosticDataProviderImpl.cpp | 28 +- .../common/OTAImageProcessorImpl.cpp | 37 +- .../common/OTAImageProcessorImpl.h | 29 + .../common/OTAImageProcessorImpl_bflb.cpp | 374 +++++ .../bouffalolab/common/SystemPlatformConfig.h | 8 + .../bouffalolab/common/SystemTimeSupport.cpp | 78 + .../bouffalolab/common/SystemTimeSupport.h | 24 + src/platform/device.gni | 8 +- src/platform/logging/BUILD.gn | 1 + src/system/BUILD.gn | 6 + third_party/bouffalolab/bl616/BUILD.gn | 27 + .../bouffalolab/bl616/bouffalo_sdk.gni | 1272 +++++++++++++++++ .../common/bouffalolab_executable.gni | 83 +- third_party/bouffalolab/common/rsicv.gni | 7 +- 76 files changed, 5964 insertions(+), 326 deletions(-) create mode 100644 examples/lighting-app/bouffalolab/bl616/.gn create mode 100644 examples/lighting-app/bouffalolab/bl616/BUILD.gn create mode 100644 examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h create mode 100644 examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h create mode 100644 examples/lighting-app/bouffalolab/bl616/args.gni create mode 120000 examples/lighting-app/bouffalolab/bl616/build_overrides create mode 100644 examples/lighting-app/bouffalolab/bl616/mboard.h create mode 120000 examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip create mode 100644 examples/platform/bouffalolab/bl616/BUILD.gn create mode 100644 examples/platform/bouffalolab/bl616/args.gni create mode 100644 examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h create mode 100644 examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml create mode 100644 examples/platform/bouffalolab/bl616/lwipopts.h create mode 100644 examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c create mode 100644 examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp create mode 100644 examples/platform/bouffalolab/common/bouffalo_sdk/uart.c create mode 100644 examples/platform/bouffalolab/common/bouffalo_sdk/uart.h create mode 100644 src/lib/shell/MainLoopBouffalolab.cpp create mode 100644 src/platform/bouffalolab/BL616/BUILD.gn create mode 100644 src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp create mode 100644 src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp create mode 100644 src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp create mode 100644 src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp create mode 100644 src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp create mode 100644 src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h create mode 100644 src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp create mode 100644 src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp create mode 100644 src/platform/bouffalolab/BL616/args.gni create mode 100644 src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h create mode 100644 src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h create mode 100644 src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h create mode 100644 src/platform/bouffalolab/BL616/wifi_mgmr_portable.c create mode 100644 src/platform/bouffalolab/BL616/wifi_mgmr_portable.h create mode 100644 src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp create mode 100644 src/platform/bouffalolab/common/SystemTimeSupport.cpp create mode 100644 src/platform/bouffalolab/common/SystemTimeSupport.h create mode 100644 third_party/bouffalolab/bl616/BUILD.gn create mode 100644 third_party/bouffalolab/bl616/bouffalo_sdk.gni diff --git a/config/bouffalolab/toolchain/riscv_toolchain.gni b/config/bouffalolab/toolchain/riscv_toolchain.gni index db46fc1a98f4fa..9035a6c0b48831 100644 --- a/config/bouffalolab/toolchain/riscv_toolchain.gni +++ b/config/bouffalolab/toolchain/riscv_toolchain.gni @@ -17,13 +17,18 @@ import("//build_overrides/chip.gni") import("//build_overrides/bouffalolab_iot_sdk.gni") import("${build_root}/toolchain/gcc_toolchain.gni") +import("${chip_root}/src/platform/device.gni") template("riscv_toolchain") { gcc_toolchain(target_name) { _tool_name_root = "" if ("linux" == host_os) { - _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-" + if (chip_device_platform == "bl616") { + _tool_name_root = "${bouffalolab_sdk_root}/toolchain/t-head-riscv/gcc_t-head_v2.6.1/bin/riscv64-unknown-elf-" + } else { + _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-" + } } else if ("mac" == host_os || "darwin" == host_os) { _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Darwin/bin/riscv64-unknown-elf-" } diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index 6fc584fa8eeade..e9c45f338a81ef 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -107,7 +107,6 @@ bouffalolab_executable("lighting_app") { defines += [ "BOOT_PIN_RESET=8" ] } - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] diff --git a/examples/lighting-app/bouffalolab/bl616/.gn b/examples/lighting-app/bouffalolab/bl616/.gn new file mode 100644 index 00000000000000..27a24ca4db236b --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "riscv" + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/lighting-app/bouffalolab/bl616/BUILD.gn b/examples/lighting-app/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..6671db3f9f7a6d --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,293 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/common/bouffalolab_executable.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") +import("${chip_root}/src/platform/device.gni") + +import("${chip_root}/src/app/chip_data_model.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") +} + +assert(current_os == "freertos") + +example_dir = "${chip_root}/examples/lighting-app/bouffalolab" +examples_plat_dir = "${chip_root}/examples/platform/bouffalolab" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = true + + # OTA periodic query timeout in seconds + ota_periodic_query_timeout_seconds = 86400 + + # reboot delay in seconds to apply new OTA image + ota_auto_reboot_delay_seconds = 5 + + enable_heap_monitoring = false + enable_reset_counter = false + + setupPinCode = 20202021 + setupDiscriminator = 3840 + + board = "BL616DK" + module_type = "BL616" + baudrate = 2000000 +} + +bouffalo_sdk("sdk") { + include_dirs = [ + "${example_dir}/bl616", + "${examples_plat_dir}/bl616", + "${examples_plat_dir}/common/route_hook", + "${chip_root}/src/platform/bouffalolab/BL616", + "${chip_root}/src/platform/bouffalolab/common", + ] + + defines = [ + "INCLUDE_xSemaphoreGetMutexHolder=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_seconds}", + "OTA_AUTO_REBOOT_DELAY=${ota_auto_reboot_delay_seconds}", + "CHIP_UART_BAUDRATE=${baudrate}", + ] + + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + include_dirs += [ "${examples_plat_dir}/common/rpc" ] + defines += [ "PW_RPC_ENABLED=1" ] + defines += [ "DISABLE_PRINT=1" ] + } else if (chip_build_libshell) { + include_dirs += [ "${examples_plat_dir}/common/plat" ] + } + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/bl616/lwipopts" ] + } +} + +chip_data_model("bouffalolab-lighting") { + if (chip_enable_openthread) { + zap_file = "${example_dir}/data_model/lighting-app-thread.zap" + } else if (chip_enable_wifi) { + zap_file = "${example_dir}/data_model/lighting-app-wifi.zap" + } else { + zap_file = "${example_dir}/data_model/lighting-app-ethernet.zap" + } + is_server = true +} + +bouffalolab_executable("lighting_app") { + output_name = "chip-bl616-lighting-example.out" + bl_plat_name = "bl616" + + defines = [ + "APP_TASK_STACK_SIZE=4096", + "CHIP_UART_BAUDRATE=${baudrate}", + "BL616_ENABLE", + "START_ENTRY=main", + ] + + defines += + [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] + + if (chip_config_network_layer_ble) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=1" ] + } + + if (false == enable_reset_counter) { + defines += [ "BOOT_PIN_RESET=2" ] + } + + defines += [ "BL616DK" ] + + sources = [ + "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", + "${example_dir}/common/AppTask.cpp", + "${example_dir}/common/ZclCallbacks.cpp", + "${examples_plat_dir}/common/bouffalo_sdk/demo_pwm.c", + "${examples_plat_dir}/common/bouffalo_sdk/platform_port.cpp", + "${examples_plat_dir}/common/plat/LEDWidget.cpp", + "${examples_plat_dir}/common/plat/OTAConfig.cpp", + "${examples_plat_dir}/common/plat/main.cpp", + "${examples_plat_dir}/common/plat/platform.cpp", + ] + + deps = [ + ":bouffalolab-lighting", + ":sdk", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs = [ + "${chip_root}/src/platform/bouffalolab/BL616", + "${example_dir}/common", + "${example_dir}/bl616", + "${examples_plat_dir}/common/plat", + "${examples_plat_dir}/common/bouffalo_sdk", + ] + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/bl616/lwipopts" ] + } + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/common/route_hook" ] + + if (chip_enable_wifi) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_WIFI" ] + } + + sources += [ + "${examples_plat_dir}/common/route_hook/bl_route_hook.c", + "${examples_plat_dir}/common/route_hook/bl_route_table.c", + ] + } + + if (chip_enable_openthread) { + import("//build_overrides/openthread.gni") + + deps += [ + "${chip_root}/third_party/openthread/platforms:libopenthread-platform", + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + ] + + if (chip_openthread_ftd) { + defines += [ "CHIP_DEVICE_CONFIG_THREAD_FTD=1" ] + deps += [ + "${openthread_root}:libopenthread-cli-ftd", + "${openthread_root}:libopenthread-ftd", + ] + } else { + defines += [ "CHIP_DEVICE_CONFIG_THREAD_FTD=0" ] + deps += [ + "${openthread_root}:libopenthread-cli-mtd", + "${openthread_root}:libopenthread-mtd", + ] + } + } + + defines += [ "CONFIG_ENABLE_CHIP_SHELL=${chip_build_libshell}" ] + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + defines += [ + "PW_RPC_ENABLED", + "PW_RPC_ATTRIBUTE_SERVICE=1", + "PW_RPC_BUTTON_SERVICE=1", + "PW_RPC_DESCRIPTOR_SERVICE=1", + "PW_RPC_DEVICE_SERVICE=1", + "PW_RPC_LIGHTING_SERVICE=1", + + #"PW_RPC_TRACING_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/common/pigweed/RpcService.cpp", + "${chip_root}/examples/common/pigweed/bouffalolab/PigweedLoggerMutex.cpp", + "${examples_plat_dir}/common/rpc/PigweedLogger.cpp", + "${examples_plat_dir}/common/rpc/Rpc.cpp", + ] + + deps += [ + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_kvs:crc16", + "$dir_pw_log", + "$dir_pw_stream:sys_io_stream", + + #"$dir_pw_trace", + #"$dir_pw_trace_tokenized", + #"$dir_pw_trace_tokenized:trace_rpc_service", + "${chip_root}/config/bouffalolab/common/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:attributes_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:button_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:descriptor_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:device_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:lighting_service.nanopb_rpc", + "${examples_plat_dir}/common/rpc/pw_sys_io:pw_sys_io", + ] + + if (chip_enable_openthread) { + deps += [ + "${chip_root}/examples/common/pigweed:ot_cli_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:thread_service.nanopb_rpc", + ] + } + + deps += pw_build_LINK_DEPS + + include_dirs += [ + "${chip_root}/examples/common", + "${chip_root}/examples/common/pigweed/bouffalolab", + ] + } else if (chip_build_libshell) { + if (chip_build_libshell) { + include_dirs += [ + "${chip_root}/src/lib/shell", + "${chip_root}/examples/shell/shell_common/include", + ] + + deps += [ "${chip_root}/examples/shell/shell_common:shell_common" ] + } + } + + defines += [ "HEAP_MONITORING=${enable_heap_monitoring}" ] + if (enable_heap_monitoring) { + sources += [ "${examples_plat_dir}/common/plat/MemMonitoring.cpp" ] + } + + if (bouffalo_sdk_component_easyflash_enabled) { + defines += [ "BOUFFALO_SDK_COMPONENTS_EASYFLASH_ENABLED=1" ] + } else { + defines += [ "BOUFFALO_SDK_COMPONENTS_EASYFLASH_ENABLED=0" ] + } + + print("bouffalo_sdk_root=${bouffalo_sdk_root}") + cflags_c = [ "-Wno-sign-compare" ] + ldscript = "${bouffalo_sdk_root}/bsp/board/bl616dk/bl616_flash.ld" + + ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + + inputs = [ ldscript ] + + if (chip_print_memory_usage) { + ldflags += [ + "--specs=nano.specs", + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("bl616") { + deps = [ ":lighting_app" ] +} + +group("default") { + deps = [ ":bl616" ] +} diff --git a/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h b/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h new file mode 100644 index 00000000000000..51430ca4e69d92 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h @@ -0,0 +1,116 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * + */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8005 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "0.1ALPHA" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 0x0001 +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION + * + * The product revision number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software revisions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +#define CHIP_BLE_DEVICE_NAME "MatterLight" diff --git a/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h b/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h new file mode 100644 index 00000000000000..609c13605a90a7 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h @@ -0,0 +1,142 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ +#include +#include + +#define configMTIME_BASE_ADDRESS (0xE0000000UL + 0xBFF8UL) +#define configMTIMECMP_BASE_ADDRESS (0xE0000000UL + 0x4000UL) + +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configCPU_CLOCK_HZ ((uint32_t) (1 * 1000 * 1000)) +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +#define configMINIMAL_STACK_SIZE \ + ((unsigned short) 128) /* Only needs to be this high as some demo tasks also use this constant. In production only the idle \ + task would use this. */ +#define configTOTAL_HEAP_SIZE ((size_t) 100 * 1024) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 0 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 1 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 1 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 +#define configUSE_TICKLESS_IDLE 0 +#define configUSE_POSIX_ERRNO 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH (1024) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xSemaphoreGetMutexHolder 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +void vApplicationMallocFailedHook(void); + +#if __cplusplus +extern "C" void vAssertCalled(void); +#else +void vAssertCalled(void); +#endif +#define configASSERT(x) \ + if ((x) == 0) \ + { \ + printf("file [%s]\r\n", __FILE__); \ + printf("func [%s]\r\n", __FUNCTION__); \ + printf("line [%d]\r\n", __LINE__); \ + printf("%s\r\n", (const char *) (#x)); \ + vAssertCalled(); \ + } + +#if (configUSE_TICKLESS_IDLE != 0) +void vApplicationSleep(uint32_t xExpectedIdleTime); +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif + +// #define portUSING_MPU_WRAPPERS + +#if (configGENERATE_RUN_TIME_STATS == 1) +#ifdef __cplusplus +extern "C" uint64_t bflb_mtimer_get_time_us(); +#else +extern uint64_t bflb_mtimer_get_time_us(); +#endif +#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() ((void) 0) +#define portGET_RUN_TIME_COUNTER_VALUE() bflb_mtimer_get_time_us() +#endif + +#endif /* FREERTOS_CONFIG_H */ diff --git a/examples/lighting-app/bouffalolab/bl616/args.gni b/examples/lighting-app/bouffalolab/bl616/args.gni new file mode 100644 index 00000000000000..d031a4b769ec88 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/args.gni @@ -0,0 +1,34 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/src/platform/bouffalolab/BL616/args.gni") + +bouffalo_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" + +chip_detail_logging = true + +# use -Os instead of -Og +is_debug = false + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] diff --git a/examples/lighting-app/bouffalolab/bl616/build_overrides b/examples/lighting-app/bouffalolab/bl616/build_overrides new file mode 120000 index 00000000000000..995884e6163eb5 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/build_overrides @@ -0,0 +1 @@ +../../../build_overrides \ No newline at end of file diff --git a/examples/lighting-app/bouffalolab/bl616/mboard.h b/examples/lighting-app/bouffalolab/bl616/mboard.h new file mode 100644 index 00000000000000..c025609d89472e --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/mboard.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes dev borad compile-time configuration constants for BL602. + * + */ + +#pragma once + +#define CHIP_UART_PORT 0 +#define CHIP_UART_RX_BUFFSIZE 256 + +#define LED_B_PWM_CH 0 +#define LED_B_PIN 0 + +#define LED_R_PWM_CH 1 +#define LED_R_PIN 1 + +#define LED_G_PWM_CH 2 +#define LED_G_PIN 30 + +#define MAX_PWM_CHANNEL 3 + +#define CHIP_UART_PIN_RX 7 +#define CHIP_UART_PIN_TX 16 diff --git a/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip b/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip new file mode 120000 index 00000000000000..59307833b4fee9 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../.. \ No newline at end of file diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index 209e473e693869..d441eb118205bd 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -135,7 +135,6 @@ bouffalolab_executable("lighting_app") { "START_ENTRY=bl702_main", ] - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] if (chip_config_network_layer_ble) { diff --git a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn index 50d2bd417a2ba4..036b31479dab05 100644 --- a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn @@ -112,7 +112,6 @@ bouffalolab_executable("lighting_app") { "START_ENTRY=bl702_main", ] - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] if (chip_config_network_layer_ble) { diff --git a/examples/lighting-app/bouffalolab/bl702l/mboard.h b/examples/lighting-app/bouffalolab/bl702l/mboard.h index 62ee3648eede00..e83529bc168440 100644 --- a/examples/lighting-app/bouffalolab/bl702l/mboard.h +++ b/examples/lighting-app/bouffalolab/bl702l/mboard.h @@ -1,85 +1,85 @@ -/* - * Copyright (c) 2018, The OpenThread Authors. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file - * This file includes dev borad compile-time configuration constants for BL702L. - * - */ - -#pragma once - -#define CHIP_UART_PORT 0 -#define CHIP_UART_RX_BUFFSIZE 256 - -#ifdef BL706_NIGHT_LIGHT - -#define LED_B_PIN_PORT 2 -#define LED_B_PIN 12 - -#define LED_R_PIN_PORT 0 -#define LED_R_PIN 10 - -#define LED_G_PIN_PORT 1 -#define LED_G_PIN 16 - -#define MAX_PWM_CHANNEL 3 - -#elif defined(XT_ZB6_DevKit) - -// #define LED_B_PIN_PORT 3 -// #define LED_B_PIN 18 - -// #define LED_R_PIN_PORT 4 -// #define LED_R_PIN 19 - -// #define LED_G_PIN_PORT 0 -// #define LED_G_PIN 20 - -#define LED_PIN_PORT 3 -#define LED_PIN 18 - -#define MAX_PWM_CHANNEL 1 - -#else - -#define LED_PIN_PORT 2 -#define LED_PIN 22 - -#define MAX_PWM_CHANNEL 1 - -#endif - -#define SPI_WIFI_MISO_PIN 4 -#define SPI_WIFI_MOSI_PIN 5 -#define SPI_WIFI_CLK_PIN 3 -#define SPI_WIFI_CS_PIN 6 -#define SPI_WIFI_IRQ_PIN 10 - -#define CHIP_UART_PIN_RX 15 -#define CHIP_UART_PIN_TX 14 +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes dev borad compile-time configuration constants for BL702L. + * + */ + +#pragma once + +#define CHIP_UART_PORT 0 +#define CHIP_UART_RX_BUFFSIZE 256 + +#ifdef BL706_NIGHT_LIGHT + +#define LED_B_PIN_PORT 2 +#define LED_B_PIN 12 + +#define LED_R_PIN_PORT 0 +#define LED_R_PIN 10 + +#define LED_G_PIN_PORT 1 +#define LED_G_PIN 16 + +#define MAX_PWM_CHANNEL 3 + +#elif defined(XT_ZB6_DevKit) + +// #define LED_B_PIN_PORT 3 +// #define LED_B_PIN 18 + +// #define LED_R_PIN_PORT 4 +// #define LED_R_PIN 19 + +// #define LED_G_PIN_PORT 0 +// #define LED_G_PIN 20 + +#define LED_PIN_PORT 3 +#define LED_PIN 18 + +#define MAX_PWM_CHANNEL 1 + +#else + +#define LED_PIN_PORT 2 +#define LED_PIN 22 + +#define MAX_PWM_CHANNEL 1 + +#endif + +#define SPI_WIFI_MISO_PIN 4 +#define SPI_WIFI_MOSI_PIN 5 +#define SPI_WIFI_CLK_PIN 3 +#define SPI_WIFI_CS_PIN 6 +#define SPI_WIFI_IRQ_PIN 10 + +#define CHIP_UART_PIN_RX 15 +#define CHIP_UART_PIN_TX 14 diff --git a/examples/lighting-app/bouffalolab/common/AppTask.cpp b/examples/lighting-app/bouffalolab/common/AppTask.cpp index 5fc74391f05af0..aa2039bf4e8620 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/common/AppTask.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -46,11 +47,17 @@ #include #include +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#ifdef BOOT_PIN_RESET +#include +#endif +#else extern "C" { #include #include #include } +#endif #include "AppTask.h" #include "mboard.h" @@ -66,7 +73,7 @@ using namespace chip::Shell; namespace { -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) ColorLEDWidget sLightLED; #else DimmableLEDWidget sLightLED; @@ -97,6 +104,18 @@ void StartAppTask(void) } #if CONFIG_ENABLE_CHIP_SHELL +#if CHIP_DEVICE_LAYER_TARGET_BL616 +CHIP_ERROR AppTask::StartAppShellTask() +{ + Engine::Root().Init(); + + cmd_misc_init(); + + Engine::Root().RunMainLoop(); + + return CHIP_NO_ERROR; +} +#else void AppTask::AppShellTask(void * args) { Engine::Root().RunMainLoop(); @@ -115,6 +134,7 @@ CHIP_ERROR AppTask::StartAppShellTask() return CHIP_NO_ERROR; } #endif +#endif void AppTask::PostEvent(app_event_t event) { @@ -142,25 +162,11 @@ void AppTask::AppTaskMain(void * pvParameter) #ifdef BOOT_PIN_RESET ButtonInit(); #else - /** Without RESET PIN defined, factory reset will be executed if power cycle count(resetCnt) >= APP_REBOOT_RESET_COUNT */ - uint32_t resetCnt = 0; - size_t saved_value_len = 0; - ef_get_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt), &saved_value_len); - - if (resetCnt > APP_REBOOT_RESET_COUNT) - { - resetCnt = 0; - /** To share with RESET PIN logic, mButtonPressedTime is used to recorded resetCnt increased. - * +1 makes sure mButtonPressedTime is not zero; - * a power cycle during factory reset confirm time APP_BUTTON_PRESS_LONG will cancel factoryreset */ - GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count() + 1; - } - else - { - resetCnt++; - GetAppTask().mButtonPressedTime = 0; - } - ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); + uint32_t resetCnt = 0; + Internal::BLConfig::ReadConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + Internal::BLConfig::WriteConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count(); + ChipLogProgress(NotSpecified, "AppTaskMain %lld, resetCnt %ld", GetAppTask().mButtonPressedTime, resetCnt); #endif GetAppTask().sTimer = @@ -221,6 +227,18 @@ void AppTask::AppTaskMain(void * pvParameter) /** Turn off light to indicate button long press for factory reset is confirmed */ sLightLED.SetOnoff(false); } + +#else + if (APP_EVENT_RESET_CNT & appEvent) + { + if (resetCnt >= APP_REBOOT_RESET_COUNT) + { + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); + } + ChipLogProgress(NotSpecified, "APP_REBOOT_RESET_COUNT_KEY resetCnt %ld", resetCnt); + resetCnt = 0; + Internal::BLConfig::WriteConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + } #endif if (APP_EVENT_IDENTIFY_MASK & appEvent) { @@ -286,7 +304,7 @@ void AppTask::LightingUpdate(app_event_t status) { v.SetNonNull(254); } -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) sLightLED.SetColor(v.Value(), hue, sat); #else sLightLED.SetLevel(v.Value()); @@ -296,7 +314,7 @@ void AppTask::LightingUpdate(app_event_t status) } else { -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) /** show yellow to indicate not-provision state for extended color light */ sLightLED.SetColor(254, 35, 254); #else @@ -339,12 +357,12 @@ void AppTask::TimerCallback(TimerHandle_t xTimer) void AppTask::TimerEventHandler(app_event_t event) { +#ifdef BOOT_PIN_RESET uint32_t pressedTime = 0; if (GetAppTask().mButtonPressedTime) { pressedTime = System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime; -#ifdef BOOT_PIN_RESET if (ButtonPressed()) { if (pressedTime > APP_BUTTON_PRESS_LONG) @@ -353,7 +371,7 @@ void AppTask::TimerEventHandler(app_event_t event) } else if (pressedTime >= APP_BUTTON_PRESS_SHORT) { -#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) +#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) || defined(BL616DK) /** change color to indicate to wait factory reset confirm */ sLightLED.SetColor(254, 0, 210); #else @@ -380,26 +398,7 @@ void AppTask::TimerEventHandler(app_event_t event) GetAppTask().mTimerIntvl = APP_BUTTON_PRESSED_ITVL; GetAppTask().mButtonPressedTime = 0; } -#else - if (pressedTime > APP_BUTTON_PRESS_LONG) - { - /** factory reset confirm timeout */ - GetAppTask().mButtonPressedTime = 0; - GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); - } - else - { -#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) - /** change color to indicate to wait factory reset confirm */ - sLightLED.SetColor(254, 0, 210); -#else - /** toggle led to indicate to wait factory reset confirm */ - sLightLED.Toggle(); -#endif - } -#endif } -#ifdef BOOT_PIN_RESET else { if (ButtonPressed()) @@ -408,6 +407,21 @@ void AppTask::TimerEventHandler(app_event_t event) GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count(); } } +#else + if (GetAppTask().mButtonPressedTime && + System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime > APP_BUTTON_PRESS_LONG) + { +#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) || defined(BL616DK) + /** change color to indicate to wait factory reset confirm */ + sLightLED.SetColor(254, 0, 210); +#else + /** toggle led to indicate to wait factory reset confirm */ + sLightLED.Toggle(); +#endif + /** factory reset confirm timeout */ + GetAppTask().mButtonPressedTime = 0; + GetAppTask().PostEvent(APP_EVENT_RESET_CNT); + } #endif StartTimer(); @@ -453,23 +467,52 @@ void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) } #ifdef BOOT_PIN_RESET +#if CHIP_DEVICE_LAYER_TARGET_BL616 +static struct bflb_device_s * app_task_gpio_var = NULL; +static void app_task_gpio_isr(int irq, void * arg) +{ + bool intstatus = bflb_gpio_get_intstatus(app_task_gpio_var, BOOT_PIN_RESET); + if (intstatus) + { + bflb_gpio_int_clear(app_task_gpio_var, BOOT_PIN_RESET); + } + + GetAppTask().ButtonEventHandler(arg); +} +#else static hosal_gpio_dev_t gpio_key = { .port = BOOT_PIN_RESET, .config = INPUT_HIGH_IMPEDANCE, .priv = NULL }; +#endif void AppTask::ButtonInit(void) { GetAppTask().mButtonPressedTime = 0; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + app_task_gpio_var = bflb_device_get_by_name("gpio"); + + bflb_gpio_init(app_task_gpio_var, BOOT_PIN_RESET, GPIO_INPUT); + bflb_gpio_int_init(app_task_gpio_var, BOOT_PIN_RESET, GPIO_INT_TRIG_MODE_SYNC_FALLING_RISING_EDGE); + bflb_gpio_int_mask(app_task_gpio_var, BOOT_PIN_RESET, false); + + bflb_irq_attach(app_task_gpio_var->irq_num, app_task_gpio_isr, app_task_gpio_var); + bflb_irq_enable(app_task_gpio_var->irq_num); +#else hosal_gpio_init(&gpio_key); hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_POS_PULSE, GetAppTask().ButtonEventHandler, NULL); +#endif } bool AppTask::ButtonPressed(void) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + return bflb_gpio_read(app_task_gpio_var, BOOT_PIN_RESET); +#else uint8_t val = 1; hosal_gpio_input_get(&gpio_key, &val); return val == 1; +#endif } void AppTask::ButtonEventHandler(void * arg) diff --git a/examples/lighting-app/bouffalolab/common/AppTask.h b/examples/lighting-app/bouffalolab/common/AppTask.h index bcc9dbaec7a4b5..37f8678e0505eb 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.h +++ b/examples/lighting-app/bouffalolab/common/AppTask.h @@ -63,11 +63,13 @@ class AppTask APP_EVENT_FACTORY_RESET = 0x00000040, APP_EVENT_BTN_LONG = 0x00000080, APP_EVENT_BTN_ISR = 0x00000100, + APP_EVENT_RESET_CNT = 0x00000200, - APP_EVENT_LIGHTING_ONOFF = 0x00010000, - APP_EVENT_LIGHTING_LEVEL = 0x00020000, - APP_EVENT_LIGHTING_COLOR = 0x00040000, - APP_EVENT_LIGHTING_MASK = APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR, + APP_EVENT_LIGHTING_ONOFF = 0x00010000, + APP_EVENT_LIGHTING_LEVEL = 0x00020000, + APP_EVENT_LIGHTING_COLOR = 0x00040000, + APP_EVENT_LIGHTING_MASK = APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR, + APP_EVENT_COMMISSION_COMPLETE = APP_EVENT_LIGHTING_MASK, APP_EVENT_IDENTIFY_START = 0x01000000, APP_EVENT_IDENTIFY_IDENTIFY = 0x02000000, @@ -75,7 +77,7 @@ class AppTask APP_EVENT_IDENTIFY_MASK = APP_EVENT_IDENTIFY_START | APP_EVENT_IDENTIFY_IDENTIFY | APP_EVENT_IDENTIFY_STOP, APP_EVENT_ALL_MASK = APP_EVENT_LIGHTING_MASK | APP_EVENT_TIMER | APP_EVENT_BTN_SHORT | APP_EVENT_BTN_LONG | - APP_EVENT_BTN_ISR | APP_EVENT_IDENTIFY_MASK, + APP_EVENT_BTN_ISR | APP_EVENT_RESET_CNT | APP_EVENT_IDENTIFY_MASK, }; void SetEndpointId(EndpointId endpointId) diff --git a/examples/platform/bouffalolab/bl616/BUILD.gn b/examples/platform/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..0a5b997ab0ba7a --- /dev/null +++ b/examples/platform/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") + +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + +config("chip_examples_project_config") { + include_dirs = [ "project_include" ] +} diff --git a/examples/platform/bouffalolab/bl616/args.gni b/examples/platform/bouffalolab/bl616/args.gni new file mode 100644 index 00000000000000..bbab38b1a34ff2 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/args.gni @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +chip_ble_project_config_include = "" +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" diff --git a/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h b/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h new file mode 100644 index 00000000000000..86b297b66fa8fc --- /dev/null +++ b/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h @@ -0,0 +1,15 @@ +#ifndef _LWIP_DEFAULT_HOOKS_H_ +#define _LWIP_DEFAULT_HOOKS_H_ +#include "lwip/arch.h" +#include "lwip/err.h" +#include "lwip/ip_addr.h" + +#include "lwiphooks.h" + +extern struct netif * lwip_hook_ip6_route(const ip6_addr_t * src, const ip6_addr_t * dest); +#define LWIP_HOOK_IP6_ROUTE lwip_hook_ip6_route + +extern const ip6_addr_t * lwip_hook_nd6_get_gw(struct netif * netif, const ip6_addr_t * dest); +#define LWIP_HOOK_ND6_GET_GW lwip_hook_nd6_get_gw + +#endif /* _LWIP_DEFAULT_HOOKS_H_ */ diff --git a/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml b/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml new file mode 100644 index 00000000000000..c6fa8320dda795 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml @@ -0,0 +1,141 @@ +[pt_table] +#partition table is 4K in size +address0 = 0xE000 +address1 = 0xF000 +# If version is 2, It will use dynamic mode. +version = 2 + +[[pt_entry]] +type = 16 +name = "Boot2" +device = 0 +address0 = 0 +size0 = 0xE000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 0 +name = "FW" +device = 0 +address0 = 0x10000 +size0 = 0x200000 +address1 = 0x210000 +size1 = 0x168000 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 10 +name = "mfg" +device = 0 +address0 = 0x210000 +size0 = 0x168000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 2 +name = "media" +device = 0 +address0 = 0x378000 +size0 = 0x71000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 3 +name = "PSM" +device = 0 +address0 = 0x3E9000 +size0 = 0x8000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 4 +name = "KEY" +device = 0 +address0 = 0x3F1000 +size0 = 0x2000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 5 +name = "DATA" +device = 0 +address0 = 0x3F1000 +size0 = 0x5000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 6 +name = "factory" +device = 0 +address0 = 0x3F6000 +size0 = 0x8000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 7 +name = "MFD" +device = 0 +address0 = 0x3FE000 +size0 = 0x1000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 diff --git a/examples/platform/bouffalolab/bl616/lwipopts.h b/examples/platform/bouffalolab/bl616/lwipopts.h new file mode 100644 index 00000000000000..91d779fb9356e5 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/lwipopts.h @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_LWIPOPTS_H__ +#define LWIP_HDR_LWIPOPTS_H__ + +#include "arch/sys_arch.h" +#include "rtos_def.h" +#include + +#if defined(__cplusplus) +extern "C" long random(void); +extern "C" int * __errno(void); +extern "C" uint16_t fhost_ip_chksum(const void * dataptr, int len); +extern "C" sys_mutex_t lock_tcpip_core; +extern "C" int sys_is_inside_interrupt(void); +extern "C" int sys_mutex_is_locked(sys_mutex_t * mutex); +extern "C" int sys_current_is_tcpip(void); +#else +extern long random(void); +extern int * __errno(void); +extern uint16_t fhost_ip_chksum(const void * dataptr, int len); +extern sys_mutex_t lock_tcpip_core; +extern int sys_is_inside_interrupt(void); +extern int sys_mutex_is_locked(sys_mutex_t * mutex); +extern int sys_current_is_tcpip(void); +extern const int fhost_tcpip_priority; +#endif + +#define LWIP_TCPIP_CORE_LOCKING 1 +#define IP_DEFAULT_TTL 64 + +#if defined(CONFIG_HIGH_PERFORMANCE) && (CONFIG_HIGH_PERFORMANCE == 1) +#define LWIP_ASSERT_CORE_LOCKED() +#define LWIP_NOASSERT +#else +#if LWIP_TCPIP_CORE_LOCKING +#define LWIP_ASSERT_CORE_LOCKED() \ + do \ + { \ + if (lock_tcpip_core) \ + { \ + LWIP_ASSERT("api must call with lwip core lock", !sys_is_inside_interrupt() && sys_mutex_is_locked(&lock_tcpip_core)); \ + } \ + } while (0) +#else +#define LWIP_ASSERT_CORE_LOCKED() \ + do \ + { \ + LWIP_ASSERT("api must call inside lwip task", !sys_is_inside_interrupt() && sys_current_is_tcpip()); \ + } while (0) +#endif +#endif + +#define LWIP_NETIF_API 1 +#define LWIP_DEBUG 1 +#define LWIP_STATS_DISPLAY 1 +#define SOCKETS_DEBUG LWIP_DBG_OFF +#ifdef BL616_DHCP_DEBUG +#define DHCP_DEBUG LWIP_DBG_ON +#else +#define DHCP_DEBUG LWIP_DBG_OFF +#endif +#define ICMP_DEBUG LWIP_DBG_OFF +#define ETHARP_DEBUG LWIP_DBG_OFF +#define LWIP_MULTICAST_PING 1 +#define LWIP_BROADCAST_PING 1 + +#define TCPIP_MBOX_SIZE 64 +#define TCPIP_THREAD_STACKSIZE FHOST_TCPIP_STACK_SIZE +#define TCPIP_THREAD_PRIO fhost_tcpip_priority + +#define DEFAULT_THREAD_STACKSIZE 1024 +#define DEFAULT_THREAD_PRIO 1 +#define DEFAULT_RAW_RECVMBOX_SIZE 32 +#define DEFAULT_UDP_RECVMBOX_SIZE 64 +#define DEFAULT_TCP_RECVMBOX_SIZE 64 +#define DEFAULT_ACCEPTMBOX_SIZE 32 + +#define LWIP_NETIF_LOOPBACK 1 +#define LWIP_HAVE_LOOPIF 1 +#define LWIP_LOOPBACK_MAX_PBUFS 0 + +#define LWIP_CHKSUM_ALGORITHM 3 +#define LWIP_CHKSUM fhost_ip_chksum +#define LWIP_TCPIP_CORE_LOCKING_INPUT 1 + +#define PBUF_LINK_ENCAPSULATION_HLEN 388 + +#define MEMP_NUM_NETBUF 32 +#define MEMP_NUM_NETCONN 16 +#define MEMP_NUM_UDP_PCB 16 +#define MEMP_NUM_REASSDATA LWIP_MIN((IP_REASS_MAX_PBUFS), 5) + +#define PBUF_POOL_SIZE 0 +#define MEM_ALIGNMENT 4 +#define MEM_SIZE 30720 +#define PBUF_POOL_BUFSIZE (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + 1280) +#define MEMP_MEM_MALLOC 1 + +// #define LWIP_HOOK_FILENAME "lwiphooks.h" +#define LWIP_HOOK_FILENAME "bl616_lwip_hooks.h" + +#define LWIP_RAW 1 +#define LWIP_MULTICAST_TX_OPTIONS 1 + +#define LWIP_TIMEVAL_PRIVATE \ + 0 // use sys/time.h for struct timeval + // +// #define LWIP_PROVIDE_ERRNO 1 +#ifndef PLATFORM_PRIVDE_ERRNO +#define LWIP_PROVIDE_ERRNO 1 +#else +#define LWIP_ERRNO_STDINCLUDE 1 +#define LWIP_SOCKET_SET_ERRNO 1 +#endif + +#define LWIP_DHCP 1 +#define LWIP_DNS 1 +#define LWIP_IGMP 1 +#define LWIP_SO_RCVTIMEO 1 +#define LWIP_SO_SNDTIMEO 1 +#define SO_REUSE 1 +#define LWIP_TCP_KEEPALIVE 1 +#define LWIP_SO_RCVBUF 1 + +#define LWIP_IPV6 1 +#define LWIP_IPV6_DHCP6 1 +#define LWIP_IPV6_SCOPES 0 +#define LWIP_IPV6_MLD 1 +#define MEMP_NUM_MLD6_GROUP 10 + +#define MEMP_NUM_SYS_TIMEOUT (LWIP_NUM_SYS_TIMEOUT_INTERNAL + 8 + 3) + +#define LWIP_NETIF_STATUS_CALLBACK 1 +#define LWIP_NETIF_API 1 +#define LWIP_NETIF_EXT_STATUS_CALLBACK 1 + +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 + +#define LWIP_SUPPORT_CUSTOM_PBUF 1 +#ifdef HIGH_PERFORMANCE_PBUF +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#else +#define LWIP_NETIF_TX_SINGLE_PBUF 1 +#endif +#define LWIP_RAND() ((u32_t) rand()) +#undef LWIP_DECLARE_MEMORY_ALIGNED +#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) \ + u8_t variable_name[size] __attribute__((aligned(4))) __attribute__((section("SHAREDRAM"))) + +#endif /* LWIP_HDR_LWIPOPTS_H__ */ diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c b/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c new file mode 100644 index 00000000000000..98d1201af8391e --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c @@ -0,0 +1,157 @@ +/** + * Copyright (c) 2016-2021 Bouffalolab Co., Ltd. + * + * Contact information: + * web site: https://www.bouffalolab.com/ + */ +#include +#include +#include +#include + +#include "demo_pwm.h" +#include "mboard.h" + +#if MAX_PWM_CHANNEL == 3 +static const uint32_t rgb_pwm[MAX_PWM_CHANNEL][2] = { + { LED_B_PIN, LED_B_PWM_CH }, + { LED_R_PIN, LED_R_PWM_CH }, + { LED_G_PIN, LED_G_PWM_CH }, +}; +#else +static const uint32_t rgb_pwm[][2] = { + { LED_PIN, LED_PIN_PWM_CH }, +}; +#endif + +struct bflb_device_s * bflb_device_pwm = NULL; + +void demo_pwm_init(void) +{ + struct bflb_pwm_v2_config_s cfg = { + .clk_source = BFLB_SYSTEM_PBCLK, + .clk_div = 40, + .period = 1000, + }; + struct bflb_device_s * gpio = bflb_device_get_by_name("gpio"); + + bflb_device_pwm = bflb_device_get_by_name("pwm_v2_0"); + + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_gpio_init(gpio, rgb_pwm[i][0], GPIO_FUNC_PWM0 | GPIO_ALTERNATE | GPIO_PULLDOWN | GPIO_SMT_EN | GPIO_DRV_1); + } + + bflb_pwm_v2_init(bflb_device_pwm, &cfg); +} + +void demo_pwm_start(void) +{ + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_pwm_v2_channel_positive_start(bflb_device_pwm, rgb_pwm[i][1]); + } + + bflb_pwm_v2_start(bflb_device_pwm); +} + +void demo_pwm_stop(void) +{ + bflb_pwm_v2_stop(bflb_device_pwm); +} + +void set_level(uint8_t currLevel) +{ + int period; + + if (currLevel <= 5 && currLevel >= 1) + { + currLevel = 5; // avoid demo off + } + period = (int) currLevel * 1000 / 254; + + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[i][1], 0, period); + } +} + +void set_color_red(uint8_t currLevel) +{ + set_color(currLevel, 0, 254); +} + +void set_color_green(uint8_t currLevel) +{ + set_color(currLevel, 84, 254); +} + +void set_color_yellow(uint8_t currLevel) +{ + set_color(currLevel, 42, 254); +} + +void set_color(uint8_t currLevel, uint8_t currHue, uint8_t currSat) +{ +#if MAX_PWM_CHANNEL == 3 + uint16_t hue = (uint16_t) currHue * 360 / 254; + uint8_t sat = (uint16_t) currSat * 100 / 254; + + if (currLevel <= 5 && currLevel >= 1) + { + currLevel = 5; // avoid demo off + } + + if (sat > 100) + { + sat = 100; + } + + uint16_t i = hue / 60; + uint16_t rgb_max = currLevel; + uint16_t rgb_min = rgb_max * (100 - sat) / 100; + uint16_t diff = hue % 60; + uint16_t rgb_adj = (rgb_max - rgb_min) * diff / 60; + uint32_t red, green, blue; + + switch (i) + { + case 0: + red = rgb_max; + green = rgb_min + rgb_adj; + blue = rgb_min; + break; + case 1: + red = rgb_max - rgb_adj; + green = rgb_max; + blue = rgb_min; + break; + case 2: + red = rgb_min; + green = rgb_max; + blue = rgb_min + rgb_adj; + break; + case 3: + red = rgb_min; + green = rgb_max - rgb_adj; + blue = rgb_max; + break; + case 4: + red = rgb_min + rgb_adj; + green = rgb_min; + blue = rgb_max; + break; + default: + red = rgb_max; + green = rgb_min; + blue = rgb_max - rgb_adj; + break; + } + + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[0][1], 0, blue * 1000 / 254); + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[1][1], 0, red * 1000 / 254); + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[2][1], 0, green * 1000 / 254); +#else + set_level(currLevel); +#endif +} diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp new file mode 100644 index 00000000000000..f92b527b410d3a --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp @@ -0,0 +1,63 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +extern "C" { +#include +#include +} +#include + +extern "C" void __libc_init_array(void); +extern "C" void shell_init_with_task(struct bflb_device_s * shell); + +void platform_port_init(void) +{ + /*if need use xtal 32k please enable next API */ + board_init(); +#if CONFIG_ENABLE_CHIP_SHELL + struct bflb_device_s * uart0 = bflb_device_get_by_name("uart0"); + shell_init_with_task(uart0); +#endif + + __libc_init_array(); + + bflb_mtd_init(); +} + +extern "C" void vAssertCalled(void) +{ + void * ra = (void *) __builtin_return_address(0); + + taskDISABLE_INTERRUPTS(); + if (xPortIsInsideInterrupt()) + { + printf("vAssertCalled, ra = %p in ISR\r\n", (void *) ra); + } + else + { + printf("vAssertCalled, ra = %p in task %s\r\n", (void *) ra, pcTaskGetName(NULL)); + } + + while (true) + ; +} + +extern "C" void bflb_assert(void) __attribute__((weak, alias("vAssertCalled"))); diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c new file mode 100644 index 00000000000000..ef763dd286982d --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c @@ -0,0 +1,228 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may nCHIP use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include + +#ifdef CFG_USB_CDC_ENABLE +#include +#include +#include +#include +#include +#include +#include +#else +#include +#include +extern hosal_uart_dev_t uart_stdio; +#endif + +#if CONFIG_ENABLE_CHIP_SHELL || PW_RPC_ENABLED + +#define CHIP_UART_RX_TIMER_ID 1 +#define MAX_BUFFER_SIZE 256 + +typedef struct _chipUart +{ + SemaphoreHandle_t sema; + StaticSemaphore_t mutx; + uint32_t head; + uint32_t tail; + uint8_t rxbuf[MAX_BUFFER_SIZE]; +} chipUart_t; + +static chipUart_t chipUart_var; + +#ifndef CFG_USB_CDC_ENABLE +static int uartTxCallback(void * p_arg) +{ + hosal_uart_ioctl(&uart_stdio, HOSAL_UART_TX_TRIGGER_OFF, NULL); + + return 0; +} + +static int uartRxCallback(void * p_arg) +{ + uint32_t len = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + } + } + else + { + chipUart_var.head += + hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } + + return 0; +} +#else +void aosUartRxCallback(int fd, void * param) +{ + uint32_t len = 0, readlen = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + readlen = len = aos_read(fd, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + len = aos_read(fd, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + readlen += len; + } + } + else + { + readlen = aos_read(fd, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + chipUart_var.head += readlen; + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } +} +#endif + +// bl_iot_sdk +#else +static int uartTxCallback(void * p_arg) +{ + + return 0; +} + +static int uartRxCallback(void * p_arg) +{ + uint32_t len = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + // len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + // len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + } + } + else + { + chipUart_var.head += + // hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } + + return 0; +} + +void uartInit(void) +{ + memset(&chipUart_var, 0, offsetof(chipUart_t, rxbuf)); + + chipUart_var.sema = xSemaphoreCreateBinaryStatic(&chipUart_var.mutx); + +#ifndef CFG_USB_CDC_ENABLE + hosal_uart_finalize(&uart_stdio); + hosal_uart_init(&uart_stdio); + hosal_uart_callback_set(&uart_stdio, HOSAL_UART_RX_CALLBACK, uartRxCallback, NULL); + hosal_uart_callback_set(&uart_stdio, HOSAL_UART_TX_CALLBACK, uartTxCallback, NULL); + hosal_uart_ioctl(&uart_stdio, HOSAL_UART_MODE_SET, (void *) HOSAL_UART_MODE_INT); +#endif +} + +int16_t uartRead(char * Buf, uint16_t NbBytesToRead) +{ + int16_t len = 0; + + xSemaphoreTake(chipUart_var.sema, portMAX_DELAY); + + taskENTER_CRITICAL(); + + for (len = 0; len < NbBytesToRead && chipUart_var.head != chipUart_var.tail; len++) + { + Buf[len] = chipUart_var.rxbuf[chipUart_var.tail]; + chipUart_var.tail = (chipUart_var.tail + 1) % MAX_BUFFER_SIZE; + } + + taskEXIT_CRITICAL(); + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGive(chipUart_var.sema); + } + + return len; +} +#endif + +#ifndef CFG_USB_CDC_ENABLE +int16_t uartWrite(const char * Buf, uint16_t BufLength) +{ + return hosal_uart_send(&uart_stdio, Buf, BufLength); +} +#else +int16_t uartWrite(const char * Buf, uint16_t BufLength) +{ + uint16_t sent = 0; + do + { + extern int vfs_fd; + if (vfs_fd >= 0) + { + sent += (uint8_t) aos_write(vfs_fd, Buf + sent, BufLength - sent); + } + } while (sent < BufLength); + return sent; +} +#endif diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h new file mode 100644 index 00000000000000..44d49ac24f60ff --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h @@ -0,0 +1,37 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void uartInit(void); +int16_t uartWrite(const char * Buf, uint16_t BufLength); +int16_t uartRead(char * Buf, uint16_t NbBytesToRead); + +#ifdef CFG_USB_CDC_ENABLE +void aosUartRxCallback(int fd, void * param); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index 6a91567ab9b803..9564e5a07b0edd 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -158,7 +158,7 @@ void ChipEventHandler(const ChipDeviceEvent * event, intptr_t arg) break; case DeviceEventType::kCommissioningComplete: ChipLogProgress(NotSpecified, "Commissioning complete"); - GetAppTask().PostEvent(AppTask::APP_EVENT_LIGHTING_MASK); + GetAppTask().PostEvent(AppTask::APP_EVENT_COMMISSION_COMPLETE); break; default: break; diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 8d1b30234cec87..0349cb7cc805ac 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -15,7 +15,7 @@ from builders.ameba import AmebaApp, AmebaBoard, AmebaBuilder from builders.android import AndroidApp, AndroidBoard, AndroidBuilder, AndroidProfile from builders.asr import ASRApp, ASRBoard, ASRBuilder -from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder +from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder, BouffalolabThreadType from builders.cc32xx import cc32xxApp, cc32xxBuilder from builders.cyw30739 import Cyw30739App, Cyw30739Board, Cyw30739Builder from builders.efr32 import Efr32App, Efr32Board, Efr32Builder @@ -690,40 +690,46 @@ def BuildBouffalolabTarget(): # Boards target.AppendFixedTargets([ TargetPart('BL602DK', - board=BouffalolabBoard.BL602_IoT_Matter_V1, module_type="BL602"), + board=BouffalolabBoard.BL602DK, module_type="BL602"), + TargetPart('BL616DK', board=BouffalolabBoard.BL616DK, module_type="BL616"), TargetPart('BL704LDK', board=BouffalolabBoard.BL704LDK, module_type="BL704L"), TargetPart('BL706DK', board=BouffalolabBoard.BL706DK, module_type="BL706C-22"), TargetPart('BL602-NIGHT-LIGHT', - board=BouffalolabBoard.BL602_NIGHT_LIGHT, module_type="BL602"), + board=BouffalolabBoard.BL602_NIGHT_LIGHT, module_type="BL602", enable_resetCnt=True), TargetPart('BL706-NIGHT-LIGHT', - board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL706C-22"), + board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL706C-22", enable_resetCnt=True), TargetPart('BL602-IoT-Matter-V1', board=BouffalolabBoard.BL602_IoT_Matter_V1, module_type="BL602"), TargetPart('XT-ZB6-DevKit', board=BouffalolabBoard.XT_ZB6_DevKit, module_type="BL706C-22"), ]) - # Apps target.AppendFixedTargets([ TargetPart('light', app=BouffalolabApp.LIGHT), ]) - target.AppendModifier('ethernet', enable_ethernet=True) - target.AppendModifier('wifi', enable_wifi=True) - target.AppendModifier('thread', enable_thread=True) - target.AppendModifier('easyflash', enable_easyflash=True) - target.AppendModifier('littlefs', enable_littlefs=True) + target.AppendFixedTargets([ + TargetPart('ethernet', enable_ethernet=True), + TargetPart('wifi', enable_wifi=True), + TargetPart('thread', enable_thread_type=BouffalolabThreadType.THREAD_FTD), + TargetPart('thread-ftd', enable_thread_type=BouffalolabThreadType.THREAD_FTD), + TargetPart('thread-mtd', enable_thread_type=BouffalolabThreadType.THREAD_MTD), + ]) + + target.AppendFixedTargets([ + TargetPart('easyflash', enable_easyflash=True), + TargetPart('littlefs', enable_littlefs=True), + ]) + target.AppendModifier('shell', enable_shell=True) target.AppendModifier('mfd', enable_mfd=True) target.AppendModifier('rotating_device_id', enable_rotating_device_id=True) - target.AppendModifier('rpc', enable_rpcs=True) - target.AppendModifier('cdc', enable_cdc=True) - target.AppendModifier('mot', use_matter_openthread=True) - target.AppendModifier('resetCnt', enable_resetCnt=True) + target.AppendModifier('rpc', enable_rpcs=True, baudrate=115200).OnlyIfRe('-(bl602dk|bl704ldk|bl706dk)') + target.AppendModifier('cdc', enable_cdc=True).OnlyIfRe('-(bl706dk)') + target.AppendModifier('mot', use_matter_openthread=True).OnlyIfRe('-(thread)') target.AppendModifier('memmonitor', enable_heap_monitoring=True) - target.AppendModifier('115200', baudrate=115200) - target.AppendModifier('fp', enable_frame_ptr=True) + target.AppendModifier('coredump', enable_debug_coredump=True) return target diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index 09d5f250f5b221..049cacbb97eb7b 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -14,6 +14,7 @@ import logging import os +import time from enum import Enum, auto from .builder import BuilderOutput @@ -22,6 +23,7 @@ class BouffalolabApp(Enum): LIGHT = auto() + CONTACT = auto() def ExampleName(self): if self == BouffalolabApp.LIGHT: @@ -32,26 +34,33 @@ def ExampleName(self): def AppNamePrefix(self, chip_name): if self == BouffalolabApp.LIGHT: return ('chip-%s-lighting-example' % chip_name) - else: - raise Exception('Unknown app type: %r' % self) - - def FlashBundleName(self): - if self == BouffalolabApp.LIGHT: - return 'lighting_app.flashbundle.txt' + elif self == BouffalolabApp.CONTACT: + return ('chip-%s-contact-example' % chip_name) else: raise Exception('Unknown app type: %r' % self) class BouffalolabBoard(Enum): + BL602DK = auto() + BL616DK = auto() + BL704LDK = auto() + BL706DK = auto() BL602_IoT_Matter_V1 = auto() BL602_NIGHT_LIGHT = auto() XT_ZB6_DevKit = auto() BL706_NIGHT_LIGHT = auto() - BL706DK = auto() - BL704LDK = auto() def GnArgName(self): - if self == BouffalolabBoard.BL602_IoT_Matter_V1: + + if self == BouffalolabBoard.BL602DK: + return 'BL602DK' + elif self == BouffalolabBoard.BL616DK: + return 'BL616DK' + elif self == BouffalolabBoard.BL704LDK: + return 'BL704LDK' + elif self == BouffalolabBoard.BL706DK: + return 'BL706DK' + elif self == BouffalolabBoard.BL602_IoT_Matter_V1: return 'BL602-IoT-Matter-V1' elif self == BouffalolabBoard.BL602_NIGHT_LIGHT: return 'BL602-NIGHT-LIGHT' @@ -59,14 +68,16 @@ def GnArgName(self): return 'XT-ZB6-DevKit' elif self == BouffalolabBoard.BL706_NIGHT_LIGHT: return 'BL706-NIGHT-LIGHT' - elif self == BouffalolabBoard.BL706DK: - return 'BL706DK' - elif self == BouffalolabBoard.BL704LDK: - return 'BL704LDK' else: raise Exception('Unknown board #: %r' % self) +class BouffalolabThreadType(Enum): + NONE = auto() + THREAD_FTD = auto() + THREAD_MTD = auto() + + class BouffalolabBuilder(GnBuilder): def __init__(self, @@ -84,12 +95,12 @@ def __init__(self, enable_mfd: bool = False, enable_ethernet: bool = False, enable_wifi: bool = False, - enable_thread: bool = False, - enable_frame_ptr: bool = False, + enable_thread_type: BouffalolabThreadType = BouffalolabThreadType.NONE, enable_heap_monitoring: bool = False, use_matter_openthread: bool = False, enable_easyflash: bool = False, - enable_littlefs: bool = False + enable_littlefs: bool = False, + enable_debug_coredump: bool = False, ): if 'BL602' == module_type: @@ -98,6 +109,8 @@ def __init__(self, bouffalo_chip = 'bl702l' elif "BL70" in module_type: bouffalo_chip = 'bl702' + elif "BL616" == module_type: + bouffalo_chip = "bl616" else: raise Exception(f"module_type {module_type} is not supported") @@ -120,6 +133,8 @@ def __init__(self, self.argsOpt.append(f'board="{self.board.GnArgName()}"') self.argsOpt.append(f'baudrate="{baudrate}"') + enable_thread = False if enable_thread_type == BouffalolabThreadType.NONE else True + if not (enable_wifi or enable_thread or enable_ethernet): # decide default connectivity for each chip if bouffalo_chip == "bl602": @@ -128,6 +143,8 @@ def __init__(self, enable_wifi, enable_thread, enable_ethernet = False, True, False elif bouffalo_chip == "bl702l": enable_wifi, enable_thread, enable_ethernet = False, True, False + elif bouffalo_chip == "bl616": + raise Exception("Must select one of wifi and thread to build.") if [enable_wifi, enable_thread, enable_ethernet].count(True) > 1: raise Exception('Currently, only one of wifi, thread and ethernet supports.') @@ -144,15 +161,15 @@ def __init__(self, elif bouffalo_chip == "bl702l": if enable_ethernet or enable_wifi: raise Exception(f"SoC {bouffalo_chip} does NOT support connectivity Ethernet/Wi-Fi currently.") + elif bouffalo_chip == "bl616": + if enable_ethernet: + raise Exception(f"SoC {bouffalo_chip} does NOT support connectivity Ethernet currently.") if enable_thread: chip_mdns = "platform" elif enable_ethernet or enable_wifi: chip_mdns = "minimal" - if enable_frame_ptr and bouffalo_chip == "bl616": - raise Exception("BL616 does NOT support frame pointer for debug purpose.") - self.argsOpt.append(f'chip_enable_ethernet={str(enable_ethernet).lower()}') self.argsOpt.append(f'chip_enable_wifi={str(enable_wifi).lower()}') self.argsOpt.append(f'chip_enable_openthread={str(enable_thread).lower()}') @@ -165,25 +182,37 @@ def __init__(self, if enable_easyflash and enable_littlefs: raise Exception("Only one of easyflash and littlefs can be enabled.") - - if not enable_easyflash and not enable_littlefs: - logging.fatal('*' * 80) - logging.fatal('littlefs is added to support for flash storage access.') - logging.fatal('Please consider and select one of easyflash and littlefs to use.') - logging.fatal('*' * 80) - raise Exception("None of easyflash and littlefs select to build.") + if bouffalo_chip == "bl616": + if not enable_easyflash: + enable_littlefs = True + else: + if not enable_easyflash and not enable_littlefs: + logging.fatal('*' * 80) + logging.fatal('littlefs is added to support for flash storage access.') + logging.fatal('Please consider and select one of easyflash and littlefs to use.') + logging.fatal('*' * 80) + raise Exception("None of easyflash and littlefs select to build.") self.argsOpt.append(f'bouffalo_sdk_component_easyflash_enabled={"false" if enable_littlefs else "true"}') if enable_thread: + self.argsOpt.append('chip_system_config_use_open_thread_inet_endpoints=true') self.argsOpt.append('chip_with_lwip=false') self.argsOpt.append(f'openthread_project_core_config_file="{bouffalo_chip}-openthread-core-bl-config.h"') self.argsOpt.append(f'openthread_package_version="7e32165be"') + if enable_thread_type == BouffalolabThreadType.THREAD_FTD: + self.argsOpt.append(f'chip_openthread_ftd=true') + else: + self.argsOpt.append(f'chip_openthread_ftd=false') + if not use_matter_openthread: if bouffalo_chip in {"bl702", "bl702l"}: self.argsOpt.append( 'openthread_root="//third_party/connectedhomeip/third_party/bouffalolab/repo/components/network/thread/openthread"') + else: + self.argsOpt.append( + 'openthread_root="//third_party/connectedhomeip/third_party/bouffalolab/bouffalo_sdk/components/wireless/thread/openthread"') if enable_cdc: if bouffalo_chip != "bl702": @@ -208,9 +237,12 @@ def __init__(self, if enable_mfd: self.argsOpt.append("chip_enable_factory_data=true") - self.enable_frame_ptr = enable_frame_ptr - self.argsOpt.append(f"enable_debug_frame_ptr={str(enable_frame_ptr).lower()}") self.argsOpt.append(f"enable_heap_monitoring={str(enable_heap_monitoring).lower()}") + if enable_debug_coredump: + self.argsOpt.append(f"enable_debug_coredump=true") + self.argsOpt.append(f"coredump_binary_id={int(time.time())}") + + self.argsOpt.append(f"chip_generate_link_map_file=true") try: self.argsOpt.append('bouffalolab_sdk_root="%s"' % os.environ['BOUFFALOLAB_SDK_ROOT']) @@ -229,11 +261,7 @@ def print_enviroment_error(self): logging.fatal('*' * 80) def GnBuildArgs(self): - if self.enable_frame_ptr: - debug_output_file = os.path.join(self.output_dir, '%s.out' % self.app.AppNamePrefix(self.chip_name)) - return self.argsOpt + [f'debug_output_file="{debug_output_file}"'] - else: - return self.argsOpt + return self.argsOpt def build_outputs(self): extensions = ["out"] @@ -251,8 +279,12 @@ def PreBuildCommand(self): def PostBuildCommand(self): + bouffalo_sdk_chips = ["bl616"] abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") + if self.chip_name not in bouffalo_sdk_chips: + abs_path_fw_raw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw") + if os.path.isfile(abs_path_fw): target_dir = self.output_dir.replace(self.chip_dir, "").strip("/") diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 93e375c857a83f..c396fe0525e655 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,7 +1,7 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,light-switch,pigweed} asr-{asr582x,asr595x,asr550x}-{all-clusters,all-clusters-minimal,lighting,light-switch,lock,bridge,temperature-measurement,thermostat,ota-requestor,dishwasher,refrigerator}[-ota][-shell][-no_logging][-factory][-rotating_id][-rio] android-{arm,arm64,x86,x64,androidstudio-arm,androidstudio-arm64,androidstudio-x86,androidstudio-x64}-{chip-tool,chip-test,tv-server,tv-casting-app,java-matter-controller,kotlin-matter-controller,virtual-device-app}[-no-debug] -bouffalolab-{bl602dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-light[-ethernet][-wifi][-thread][-easyflash][-littlefs][-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-resetcnt][-memmonitor][-115200][-fp] +bouffalolab-{bl602dk,bl616dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-light-{ethernet,wifi,thread,thread-ftd,thread-mtd}-{easyflash,littlefs}[-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-memmonitor][-coredump] cc32xx-{lock,air-purifier} ti-cc13x4_26x4-{lighting,lock,pump,pump-controller}[-mtd][-ftd] cyw30739-{cyw30739b2_p5_evk_01,cyw30739b2_p5_evk_02,cyw30739b2_p5_evk_03,cyw930739m2evb_01,cyw930739m2evb_02}-{light,light-switch,lock,thermostat} diff --git a/scripts/flashing/bouffalolab_firmware_utils.py b/scripts/flashing/bouffalolab_firmware_utils.py index 2c4e1cca4c5789..e6ca898609102f 100755 --- a/scripts/flashing/bouffalolab_firmware_utils.py +++ b/scripts/flashing/bouffalolab_firmware_utils.py @@ -14,6 +14,7 @@ # limitations under the License. import binascii +import configparser import logging import os import pathlib @@ -224,6 +225,7 @@ class Flasher(firmware_utils.Flasher): args = {} work_dir = None + bouffalo_sdk_chips = ["bl616"] def __init__(self, **options): super().__init__(platform=None, module=__name__, **options) @@ -500,6 +502,150 @@ def exe_prog_cmd(flashtool_exe, mfd_addr): exe_gen_ota_image_cmd(flashtool_exe) exe_prog_cmd(flashtool_exe, mfd_addr) + def bouffalo_sdk_prog(self): + + def int_to_lhex(intvalue): + lhex = ((intvalue & 0xff000000) >> 24) | ((intvalue & 0xff0000) >> 8) + lhex |= ((intvalue & 0xff00) << 8) | ((intvalue & 0xff) << 24) + + return "%08x" % lhex + + def get_tools(): + bflb_tools = os.path.join(MATTER_ROOT, "third_party/bouffalolab/bouffalo_sdk/tools/bflb_tools") + bflb_tools_dict = { + "linux": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc-ubuntu", "flash_tool": "bouffalo_flash_cube/BLFlashCommand-ubuntu"}, + "win32": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc.exe", "flash_tool": "bouffalo_flash_cube/BLFlashCommand.exe"}, + "darwin": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc-macos", "flash_tool": "bouffalo_flash_cube/BLFlashCommand-macos"}, + } + + try: + fw_proc_exe = os.path.join(bflb_tools, bflb_tools_dict[sys.platform]["fw_proc"]) + flashtool_exe = os.path.join(bflb_tools, bflb_tools_dict[sys.platform]["flash_tool"]) + except Exception: + raise Exception("Do NOT support {} operating system to program firmware.".format(sys.platform)) + + if not os.path.exists(flashtool_exe) or not os.path.exists(fw_proc_exe): + logging.fatal('*' * 80) + logging.error("Expecting tools as below:") + logging.error(fw_proc_exe) + logging.error(flashtool_exe) + raise Exception("Flashtool or fw tool doesn't contain in SDK") + + return fw_proc_exe, flashtool_exe + + def prog_config(configDir, output, isErase=False): + + partition_file = self.find_file(configDir, r'^partition.+\.toml$') + if len(partition_file) != 1: + raise Exception("No partition file or one more partition file found.") + + partition_file = partition_file[0] + with open(partition_file, 'r') as file: + partition_config = toml.load(file) + + part_addr0 = partition_config["pt_table"]["address0"] + part_addr1 = partition_config["pt_table"]["address1"] + + config = configparser.ConfigParser() + + config.add_section('cfg') + config.set('cfg', 'erase', '2' if isErase else '1') + config.set('cfg', 'skip_mode', '0x0, 0x0') + config.set('cfg', 'boot2_isp_mode', '0') + + config.add_section('boot2') + config.set('boot2', 'filedir', os.path.join(self.work_dir, "boot2*.bin")) + config.set('boot2', 'address', '0x000000') + + config.add_section('partition') + config.set('partition', 'filedir', os.path.join(self.work_dir, "partition*.bin")) + config.set('partition', 'address', hex(part_addr0)) + + config.add_section('partition1') + config.set('partition1', 'filedir', os.path.join(self.work_dir, "partition*.bin")) + config.set('partition1', 'address', hex(part_addr1)) + + config.add_section('FW') + config.set('FW', 'filedir', self.args["firmware"]) + config.set('FW', 'address', '@partition') + + if self.args["mfd"]: + config.add_section("MFD") + config.set('MFD', 'filedir', self.args["mfd"]) + config.set('MFD', 'address', '@partition') + + with open(output, 'w') as configfile: + config.write(configfile) + + def exe_proc_cmd(fw_proc_exe): + + os.system("rm -rf {}/ota_images".format(self.work_dir)) + + fw_proc_cmd = [ + fw_proc_exe, + "--chipname", self.args["chipname"], + "--brdcfgdir", os.path.join(self.work_dir, "config"), + "--imgfile", self.args["firmware"], + ] + + if self.args["sk"]: + fw_proc_cmd += [ + "--privatekey", self.args["sk"], + ] + + if self.args["key"]: + lock0 = int_to_lhex((1 << 30) | (1 << 20)) + lock1 = int_to_lhex((1 << 25) | (1 << 15)) + fw_proc_cmd += [ + "--edata", "0x80,{};0x7c,{};0xfc,{}".format(self.args["key"], lock0, lock1) + ] + + logging.info("firmware process command: {}".format(" ".join(fw_proc_cmd))) + process = subprocess.Popen(fw_proc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + while process.poll() is None: + line = process.stdout.readline().decode('utf-8').rstrip() + if line: + logging.info(line) + + os.system("mkdir -p {}/ota_images".format(self.work_dir)) + os.system("mv {}/*.ota {}/ota_images/".format(self.work_dir, self.work_dir)) + + def exe_prog_cmd(flashtool_exe): + prog_cmd = [ + flashtool_exe, + "--chipname", self.args["chipname"], + "--baudrate", str(self.args["baudrate"]), + "--config", self.args["config"] + ] + + if self.args["sk"] or (self.args["key"] and self.args["iv"]): + prog_cmd += [ + "--efuse", os.path.join(self.work_dir, "efusedata.bin") + ] + + if self.args["port"]: + prog_config(os.path.join(self.work_dir, "config"), os.path.join( + self.work_dir, "flash_prog_cfg.ini"), self.option.erase) + + prog_cmd += [ + "--port", self.args["port"], + ] + + logging.info("firwmare programming: {}".format(" ".join(prog_cmd))) + process = subprocess.Popen(prog_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + while process.poll() is None: + line = process.stdout.readline().decode('utf-8').rstrip() + if line: + logging.info(line) + + fw_proc_exe, flashtool_exe = get_tools() + os.chdir(self.work_dir) + + self.parse_mfd() + + exe_proc_cmd(fw_proc_exe) + exe_prog_cmd(flashtool_exe) + def gen_ota_image(self): sys.path.insert(0, os.path.join(MATTER_ROOT, 'src', 'app')) import ota_image_tool @@ -547,6 +693,13 @@ def actions(self): """Perform actions on the device according to self.option.""" self.log(3, 'Options:', self.option) + # is_for_ota_image_building = None + # is_for_programming = False + # has_private_key = False + # has_public_key = False + # ota_output_folder = None + # options_keys = BOUFFALO_OPTIONS["configuration"].keys() + if platform.machine() not in ["x86_64"]: raise Exception("Only support x86_64 CPU machine to program firmware.") @@ -573,9 +726,12 @@ def actions(self): if self.args["port"]: raise Exception("Do not generate OTA image with firmware programming.") - if self.args["mfd"] and self.args["mfd_str"]: - raise Exception("Cannot use option mfd and mfd-str together.") - self.iot_sdk_prog() + if self.args["chipname"] in self.bouffalo_sdk_chips: + self.bouffalo_sdk_prog() + else: + if self.args["mfd"] and self.args["mfd_str"]: + raise Exception("Cannot use option mfd and mfd-str together.") + self.iot_sdk_prog() if self.args["build_ota"]: self.gen_ota_image() diff --git a/src/lib/shell/BUILD.gn b/src/lib/shell/BUILD.gn index 8a9f6233a476f6..fed0dfa5b8bbcb 100644 --- a/src/lib/shell/BUILD.gn +++ b/src/lib/shell/BUILD.gn @@ -88,11 +88,14 @@ static_library("shell") { ] } else if (chip_device_platform == "bl602" || chip_device_platform == "bl702" || - chip_device_platform == "bl702l") { - sources += [ - "MainLoopDefault.cpp", - "streamer_bouffalolab.cpp", - ] + chip_device_platform == "bl702l" || + chip_device_platform == "bl616") { + sources += [ "streamer_bouffalolab.cpp" ] + if (chip_device_platform == "bl616") { + sources += [ "MainLoopBouffalolab.cpp" ] + } else { + sources += [ "MainLoopDefault.cpp" ] + } } else if (chip_device_platform == "cc13x4_26x4") { sources += [ "MainLoopDefault.cpp", diff --git a/src/lib/shell/MainLoopBouffalolab.cpp b/src/lib/shell/MainLoopBouffalolab.cpp new file mode 100644 index 00000000000000..098f3809cc8c0c --- /dev/null +++ b/src/lib/shell/MainLoopBouffalolab.cpp @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +extern "C" { +#include +} + +using chip::Shell::Engine; + +void cmd_matter(size_t argc, char ** argv) +{ + Engine::Root().ExecCommand(argc - 1, argv + 1); +} + +SHELL_CMD_EXPORT_ALIAS(cmd_matter, matter, matter command); + +namespace chip { +namespace Shell { + +void Engine::RunMainLoop() +{ + // Intentionally empty as Zephyr has own thread handling shell +} + +} // namespace Shell +} // namespace chip diff --git a/src/lib/shell/streamer_bouffalolab.cpp b/src/lib/shell/streamer_bouffalolab.cpp index 9a7b669ae47088..d7e168ead571eb 100644 --- a/src/lib/shell/streamer_bouffalolab.cpp +++ b/src/lib/shell/streamer_bouffalolab.cpp @@ -1,66 +1,106 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Source implementation of an input / output stream for Bouffalo Lab targets. - */ - -#include -#include -#include - -#include -#include -#include - -namespace chip { -namespace Shell { -namespace { - -int streamer_iot_sdk_init(streamer_t * streamer) -{ - (void) streamer; - return 0; -} - -ssize_t streamer_iot_sdk_read(streamer_t * streamer, char * buffer, size_t length) -{ - (void) streamer; - return (ssize_t) uartRead(buffer, (uint16_t) length); -} - -ssize_t streamer_iot_sdk_write(streamer_t * streamer, const char * buffer, size_t length) -{ - (void) streamer; - return uartWrite(buffer, (uint16_t) length); -} - -static streamer_t streamer_iot_sdk = { - .init_cb = streamer_iot_sdk_init, - .read_cb = streamer_iot_sdk_read, - .write_cb = streamer_iot_sdk_write, -}; - -} // namespace -streamer_t * streamer_get(void) -{ - return &streamer_iot_sdk; -} - -} // namespace Shell -} // namespace chip +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Source implementation of an input / output stream for Bouffalo Lab targets. + */ + +#include +#include +#include + +#if !CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#include +#include +#endif + +namespace chip { +namespace Shell { + +#if CHIP_DEVICE_LAYER_TARGET_BL616 +namespace { +int streamer_bouffalo_sdk_init(streamer_t * streamer) +{ + (void) streamer; + return 0; +} + +ssize_t streamer_bouffalo_sdk_read(streamer_t * streamer, char * buffer, size_t length) +{ + (void) (streamer); + return 0; +} + +ssize_t streamer_bouffalo_sdk_write(streamer_t * streamer, const char * buffer, size_t length) +{ + (void) (streamer); + + printf("%s", buffer); + return 0; +} + +static streamer_t streamer_bouffalo_sdk = { + .init_cb = streamer_bouffalo_sdk_init, + .read_cb = streamer_bouffalo_sdk_read, + .write_cb = streamer_bouffalo_sdk_write, +}; +} // namespace + +streamer_t * streamer_get(void) +{ + return &streamer_bouffalo_sdk; +} + +#else + +namespace { + +int streamer_iot_sdk_init(streamer_t * streamer) +{ + (void) streamer; + return 0; +} + +ssize_t streamer_iot_sdk_read(streamer_t * streamer, char * buffer, size_t length) +{ + (void) streamer; + return (ssize_t) uartRead(buffer, (uint16_t) length); +} + +ssize_t streamer_iot_sdk_write(streamer_t * streamer, const char * buffer, size_t length) +{ + (void) streamer; + return uartWrite(buffer, (uint16_t) length); +} + +static streamer_t streamer_iot_sdk = { + .init_cb = streamer_iot_sdk_init, + .read_cb = streamer_iot_sdk_read, + .write_cb = streamer_iot_sdk_write, +}; + +} // namespace +streamer_t * streamer_get(void) +{ + return &streamer_iot_sdk; +} +#endif + +} // namespace Shell +} // namespace chip diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index 145bc2dd1d0183..a9d08df3641299 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -32,9 +32,10 @@ assert(lwip_platform == "external" || lwip_platform == "standalone" || lwip_platform == "nxp" || lwip_platform == "silabs" || lwip_platform == "qpg" || lwip_platform == "mbed" || lwip_platform == "psoc6" || lwip_platform == "cyw30739" || - lwip_platform == "bl602" || lwip_platform == "mw320" || - lwip_platform == "bl702" || lwip_platform == "bl702l" || - lwip_platform == "mt793x" || lwip_platform == "asr", + lwip_platform == "mw320" || lwip_platform == "bl602" || + lwip_platform == "bl616" || lwip_platform == "bl702" || + lwip_platform == "bl702l" || lwip_platform == "mt793x" || + lwip_platform == "asr", "Unsupported lwIP platform: ${lwip_platform}") if (lwip_platform != "external") { @@ -59,6 +60,9 @@ if (lwip_platform == "cc13xx_26xx") { import("//build_overrides/cyw30739_sdk.gni") } else if (lwip_platform == "bl602") { import("//build_overrides/bouffalolab_iot_sdk.gni") +} else if (lwip_platform == "bl616") { + import("//build_overrides/bouffalolab_iot_sdk.gni") + import("${chip_root}/src/platform/device.gni") } else if (lwip_platform == "bl702") { import("//build_overrides/bouffalolab_iot_sdk.gni") import("${chip_root}/src/platform/device.gni") @@ -149,6 +153,16 @@ if (current_os == "zephyr" || current_os == "mbed") { public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl602:bl_iot_sdk" ] } + group("all") { + deps = [ ":lwip" ] + } +} else if (lwip_platform == "bl616" && defined(chip_enable_openthread) && + chip_enable_openthread == false) { + group("lwip") { + public_deps = [ ":lwip_buildconfig" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + } + group("all") { deps = [ ":lwip" ] } diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index d379bd0e1f4e0d..c348996f9f6df2 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -148,7 +148,8 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { if (chip_device_platform == "linux" || chip_device_platform == "darwin" || chip_device_platform == "tizen" || chip_device_platform == "android" || chip_device_platform == "webos" || chip_device_platform == "bl602" || - chip_device_platform == "bl702" || chip_device_platform == "bl702l") { + chip_device_platform == "bl702" || chip_device_platform == "bl702l" || + chip_device_platform == "bl616") { defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=${chip_enable_ble}" ] } @@ -249,6 +250,12 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] + } else if (chip_device_platform == "bl616") { + device_layer_target_define = "BL616" + defines += [ + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", + "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", + ] } else if (chip_device_platform == "bl702") { device_layer_target_define = "BL702" defines += [ @@ -346,6 +353,7 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "TELINK", "MBED", "BL602", + "BL616", "BL702", "BL702L", "FAKE", @@ -574,6 +582,8 @@ if (chip_device_platform != "none") { _platform_target = "webos" } else if (chip_device_platform == "bl602") { _platform_target = "bouffalolab/BL602" + } else if (chip_device_platform == "bl616") { + _platform_target = "bouffalolab/BL616" } else if (chip_device_platform == "bl702") { _platform_target = "bouffalolab/BL702" } else if (chip_device_platform == "bl702l") { diff --git a/src/platform/bouffalolab/BL602/BUILD.gn b/src/platform/bouffalolab/BL602/BUILD.gn index d4cd04c739c6cd..7e4877490de172 100644 --- a/src/platform/bouffalolab/BL602/BUILD.gn +++ b/src/platform/bouffalolab/BL602/BUILD.gn @@ -39,6 +39,7 @@ static_library("BL602") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -73,5 +74,6 @@ static_library("BL602") { "${chip_root}/src/lib/dnssd:platform_header", "${chip_root}/src/platform/logging:headers", ] + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index 4d8bd35af57380..87136268afd0d2 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -15,7 +15,7 @@ * limitations under the License. */ #include -#include +#include #include #include @@ -405,6 +405,10 @@ void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg) case kWiFiOnScanDone: BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(); break; + case kWiFiOnConnecting: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; case kWiFiOnConnected: BLWiFiDriver::GetInstance().OnNetworkStatusChange(); break; @@ -447,6 +451,10 @@ extern "C" void wifi_event_handler(uint32_t code) event.Type = kWiFiOnScanDone; PlatformMgr().PostEventOrDie(&event); break; + case CODE_WIFI_ON_CONNECTING: + event.Type = kWiFiOnConnecting; + PlatformMgr().PostEventOrDie(&event); + break; case CODE_WIFI_ON_CONNECTED: event.Type = kWiFiOnConnected; PlatformMgr().PostEventOrDie(&event); diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp index 3c7b35941128c7..ade4d468dff8a3 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp @@ -46,8 +46,6 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) // Initialize LwIP. tcpip_init(NULL, NULL); - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); SuccessOrExit(err); diff --git a/src/platform/bouffalolab/BL616/BUILD.gn b/src/platform/bouffalolab/BL616/BUILD.gn new file mode 100644 index 00000000000000..f77216b48b68f8 --- /dev/null +++ b/src/platform/bouffalolab/BL616/BUILD.gn @@ -0,0 +1,107 @@ +# Copyright (c) 2022 Project CHIP Authors +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +import("${chip_root}/src/platform/device.gni") + +import("${chip_root}/src/platform/bouffalolab/common/args.gni") + +assert(chip_device_platform == "bl616") + +if (chip_enable_openthread) { + import("//build_overrides/openthread.gni") +} + +static_library("BL616") { + sources = [ + "DiagnosticDataProviderImpl.cpp", + "PlatformManagerImpl.cpp", + ] + + sources += [ + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/PlatformManagerImpl.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "../common/OTAImageProcessorImpl_bflb.cpp" ] + } + + if (chip_enable_ble) { + sources += [ + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", + ] + } + + if (chip_enable_factory_data) { + sources += [ + "../common/FactoryDataProvider.cpp", + "../common/FactoryDataProvider.h", + ] + } + + if (bouffalo_sdk_component_easyflash_enabled) { + sources += [ "../common/BLConfig.cpp" ] + } else { + sources += [ "../common/BLConfig_littlefs.cpp" ] + } + + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + + if (chip_enable_wifi) { + sources += [ + "ConfigurationManagerImpl.cpp", + "ConnectivityManagerImpl.cpp", + "NetworkCommissioningDriver.cpp", + "wifi_mgmr_portable.c", + ] + + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + + if (chip_enable_openthread) { + # needed for MTD/FTD + + import("//build_overrides/bouffalolab_iot_sdk.gni") + import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + deps += [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + + sources += [ + "../../OpenThread/OpenThreadUtils.cpp", + "ThreadStackManagerImpl.cpp", + ] + + if (chip_mdns == "platform") { + sources += [ + "../../OpenThread/DnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.h", + ] + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + } + + public_deps = [ "${chip_root}/src/platform:platform_base" ] +} diff --git a/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp b/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp new file mode 100644 index 00000000000000..0e04b79a1cbfe6 --- /dev/null +++ b/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * + * Copyright (c) 2020-2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file implements heap memory allocation APIs for CHIP. These functions are platform + * specific and might be C Standard Library heap functions re-direction in most of cases. + * + */ + +#include + +#include + +#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM +namespace chip { +namespace Platform { + +CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) +{ + return CHIP_NO_ERROR; +} + +void MemoryAllocatorShutdown() {} + +void * MemoryAlloc(size_t size) +{ + return kmalloc(size); +} + +void * MemoryCalloc(size_t num, size_t size) +{ + return kcalloc(size, num); +} + +void * MemoryRealloc(void * p, size_t size) +{ + return realloc(p, size); +} + +void MemoryFree(void * p) +{ + kfree(p); +} + +bool MemoryInternalCheckPointer(const void * p, size_t min_size) +{ + return (p != nullptr); +} + +} // namespace Platform +} // namespace chip + +#endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp new file mode 100644 index 00000000000000..f0b65b34bd896b --- /dev/null +++ b/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp @@ -0,0 +1,46 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include + +#include +#include + +#include +#include + +extern "C" { +#include +} + +namespace chip { +namespace DeviceLayer { + +CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) +{ + bflb_efuse_read_mac_address_opt(0, buf, 1); + + return CHIP_NO_ERROR; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp new file mode 100644 index 00000000000000..77dfca05ca66e4 --- /dev/null +++ b/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include + +using namespace ::chip; + +namespace chip { +namespace DeviceLayer { + +void ConnectivityManagerImpl::OnWiFiStationDisconnected() +{ + NetworkCommissioning::BLWiFiDriver::GetInstance().SetLastDisconnectReason(NULL); + uint16_t reason = NetworkCommissioning::BLWiFiDriver::GetInstance().GetLastDisconnectReason(); + uint8_t associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kUnknown); + WiFiDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetWiFiDiagnosticsDelegate(); + + ChipLogError(DeviceLayer, "WiFi station disconnect, reason %d.", reason); + + switch (reason) + { + case WLAN_FW_TX_ASSOC_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_ASSOCIATE_FAIILURE: + case WLAN_FW_4WAY_HANDSHAKE_ERROR_PSK_TIMEOUT_FAILURE: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kAssociationFailed); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_TX_AUTH_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_AUTHENTICATION_FAIILURE: + case WLAN_FW_AUTH_ALGO_FAIILURE: + case WLAN_FW_DEAUTH_BY_AP_WHEN_NOT_CONNECTION: + case WLAN_FW_DEAUTH_BY_AP_WHEN_CONNECTION: + case WLAN_FW_4WAY_HANDSHAKE_TX_DEAUTH_FRAME_TRANSMIT_FAILURE: + case WLAN_FW_4WAY_HANDSHAKE_TX_DEAUTH_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_AUTH_OR_ASSOC_RESPONSE_TIMEOUT_FAILURE: + case WLAN_FW_DISCONNECT_BY_USER_WITH_DEAUTH: + case WLAN_FW_DISCONNECT_BY_USER_NO_DEAUTH: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kAuthenticationFailed); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_SCAN_NO_BSSID_AND_CHANNEL: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kSsidNotFound); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_BEACON_LOSS: + case WLAN_FW_DISCONNECT_BY_FW_PS_TX_NULLFRAME_FAILURE: + case WLAN_FW_CREATE_CHANNEL_CTX_FAILURE_WHEN_JOIN_NETWORK: + case WLAN_FW_ADD_STA_FAILURE: + case WLAN_FW_JOIN_NETWORK_FAILURE: + break; + + default: + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + } + + if (delegate) + { + delegate->OnDisconnectionDetected(reason); + delegate->OnConnectionStatusChanged( + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::ConnectionStatusEnum::kNotConnected)); + } +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp new file mode 100644 index 00000000000000..f62ae3762183ab --- /dev/null +++ b/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp @@ -0,0 +1,139 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include + +extern "C" { +#include +} +#include +#endif + +namespace chip { +namespace DeviceLayer { + +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) +{ + bootReason = BootReasonType::kUnspecified; + return CHIP_NO_ERROR; +} + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(MutableByteSpan & BssId) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (ConnectivityMgrImpl()._IsWiFiStationConnected() && 0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + return CopySpanToMutableSpan(ByteSpan(statInfo.bssid), BssId); + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (ConnectivityMgrImpl()._IsWiFiStationConnected() && 0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + channelNumber = statInfo.channel; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) +{ + int tmp_rssi; + if (ConnectivityMgrImpl()._IsWiFiStationConnected()) + { + wifi_mgmr_sta_rssi_get(&tmp_rssi); + rssi = (int8_t) tmp_rssi; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} +#endif + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp new file mode 100644 index 00000000000000..dc5c22dcd0f1b0 --- /dev/null +++ b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp @@ -0,0 +1,463 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include +#include +#include +#include +extern "C" { +#include +} +#include + +using namespace ::chip; +using namespace ::chip::DeviceLayer::Internal; +using namespace ::chip::Platform; + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +CHIP_ERROR BLWiFiDriver::Init(NetworkStatusChangeCallback * networkStatusChangeCallback) +{ + CHIP_ERROR err; + size_t ssidLen = 0; + size_t credentialsLen = 0; + + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, mSavedNetwork.credentials, + sizeof(mSavedNetwork.credentials), &credentialsLen); + SuccessOrExit(err); + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, mSavedNetwork.ssid, sizeof(mSavedNetwork.ssid), + &ssidLen); + SuccessOrExit(err); + mSavedNetwork.credentialsLen = credentialsLen; + mSavedNetwork.ssidLen = ssidLen; + + mStagingNetwork = mSavedNetwork; + mpScanCallback = nullptr; + mpConnectCallback = nullptr; + mpStatusChangeCallback = networkStatusChangeCallback; + +exit: + if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) + { + /** Not commissioned, SSID and Network Password not found. */ + return CHIP_NO_ERROR; + } + + return err; +} + +void BLWiFiDriver::Shutdown() +{ + mpStatusChangeCallback = nullptr; +} + +CHIP_ERROR BLWiFiDriver::CommitConfiguration() +{ + ChipLogProgress(NetworkProvisioning, "BLWiFiDriver::CommitConfiguration"); + ReturnErrorOnFailure( + PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiSSID, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiPassword, mStagingNetwork.credentials, + mStagingNetwork.credentialsLen)); + mSavedNetwork = mStagingNetwork; + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLWiFiDriver::RevertConfiguration() +{ + mStagingNetwork = mSavedNetwork; + return CHIP_NO_ERROR; +} + +bool BLWiFiDriver::NetworkMatch(const WiFiNetwork & network, ByteSpan networkId) +{ + return networkId.size() == network.ssidLen && memcmp(networkId.data(), network.ssid, network.ssidLen) == 0; +} + +Status BLWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(mStagingNetwork.ssidLen == 0 || NetworkMatch(mStagingNetwork, ssid), Status::kBoundsExceeded); + VerifyOrReturnError(credentials.size() <= sizeof(mStagingNetwork.credentials), Status::kOutOfRange); + VerifyOrReturnError(ssid.size() <= sizeof(mStagingNetwork.ssid), Status::kOutOfRange); + + memcpy(mStagingNetwork.credentials, credentials.data(), credentials.size()); + mStagingNetwork.credentialsLen = static_cast(credentials.size()); + + memcpy(mStagingNetwork.ssid, ssid.data(), ssid.size()); + mStagingNetwork.ssidLen = static_cast(ssid.size()); + + return Status::kSuccess; +} + +Status BLWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + + // Use empty ssid for representing invalid network + mStagingNetwork.ssidLen = 0; + return Status::kSuccess; +} + +Status BLWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) +{ + outDebugText.reduce_size(0); + + // Only one network is supported now + VerifyOrReturnError(index == 0, Status::kOutOfRange); + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + return Status::kSuccess; +} + +CHIP_ERROR BLWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen) +{ + wifi_mgmr_sta_connect_params_t conn_param = { 0 }; + + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + + strncpy((char *) conn_param.ssid, ssid, ssidLen); + conn_param.ssid_len = ssidLen; + + if (keyLen) + { + strncpy((char *) conn_param.key, key, keyLen); + conn_param.key_len = keyLen; + } + conn_param.freq1 = 0; + conn_param.freq2 = 0; + conn_param.use_dhcp = 1; + conn_param.pmf_cfg = 1; + conn_param.quick_connect = 1; + conn_param.timeout_ms = -1; + + wifi_mgmr_sta_connect(&conn_param); + + return CHIP_NO_ERROR; +} + +void BLWiFiDriver::OnConnectWiFiNetwork(bool isConnected) +{ + if (mpConnectCallback) + { + if (isConnected) + { + mpConnectCallback->OnResult(Status::kSuccess, CharSpan(), 0); + } + else + { + mpConnectCallback->OnResult(Status::kUnknownError, CharSpan(), 0); + } + mpConnectCallback = nullptr; + } +} + +void BLWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + Status networkingStatus = Status::kSuccess; + + VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); + VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); + ChipLogProgress(NetworkProvisioning, "BL NetworkCommissioningDelegate: SSID: %.*s", static_cast(networkId.size()), + networkId.data()); + + err = ConnectWiFiNetwork(reinterpret_cast(mStagingNetwork.ssid), mStagingNetwork.ssidLen, + reinterpret_cast(mStagingNetwork.credentials), mStagingNetwork.credentialsLen); + mpConnectCallback = callback; + +exit: + if (err != CHIP_NO_ERROR) + { + networkingStatus = Status::kUnknownError; + } + if (networkingStatus != Status::kSuccess) + { + ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network:%s", chip::ErrorStr(err)); + mpConnectCallback = nullptr; + callback->OnResult(networkingStatus, CharSpan(), 0); + } +} + +void BLWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * callback) +{ + if (callback != nullptr) + { + mpScanCallback = nullptr; + if (0 == wifi_start_scan(ssid.data(), ssid.size())) + { + mpScanCallback = callback; + } + else + { + callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); + } + } +} + +void BLWiFiDriver::OnScanWiFiNetworkDone() +{ + uint32_t nums = wifi_mgmr_sta_scanlist_nums_get(); + if (nums) + { + wifi_mgmr_scan_item_t * pScanList = (wifi_mgmr_scan_item_t *) MemoryAlloc(nums * sizeof(wifi_mgmr_scan_item_t)); + + if (NULL == pScanList || 0 == wifi_mgmr_sta_scanlist_dump(pScanList, nums)) + { + mpScanCallback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); + mpScanCallback = nullptr; + } + else + { + + if (CHIP_NO_ERROR == DeviceLayer::SystemLayer().ScheduleLambda([nums, pScanList]() { + BLScanResponseIterator iter(nums, pScanList); + if (GetInstance().mpScanCallback) + { + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); + GetInstance().mpScanCallback = nullptr; + } + else + { + ChipLogError(DeviceLayer, "can't find the ScanCallback function"); + } + })) + { + MemoryFree(pScanList); + } + } + } + else + { + ChipLogProgress(DeviceLayer, "No AP found"); + if (mpScanCallback != nullptr) + { + mpScanCallback->OnFinished(Status::kNetworkNotFound, CharSpan(), nullptr); + mpScanCallback = nullptr; + } + } +} + +CHIP_ERROR GetConfiguredNetwork(Network & network) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + memcpy(network.networkID, statInfo.ssid, strlen(statInfo.ssid)); + network.networkIDLen = strlen(statInfo.ssid); + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_INTERNAL; +} + +void BLWiFiDriver::OnNetworkStatusChange() +{ + Network configuredNetwork; + + VerifyOrReturn(mpStatusChangeCallback != nullptr); + if (GetConfiguredNetwork(configuredNetwork) != CHIP_NO_ERROR) + { + return; + } + + if (ConnectivityManagerImpl().GetWiFiStationState() == ConnectivityManager::kWiFiStationState_Connected) + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kSuccess, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), NullOptional); + } + else + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kUnknownError, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), + MakeOptional(GetLastDisconnectReason())); + } +} + +CHIP_ERROR BLWiFiDriver::SetLastDisconnectReason(const ChipDeviceEvent * event) +{ + mLastDisconnectedReason = wifi_mgmr_sta_info_status_code_get(); + + return CHIP_NO_ERROR; +} + +int32_t BLWiFiDriver::GetLastDisconnectReason() +{ + return mLastDisconnectedReason; +} + +size_t BLWiFiDriver::WiFiNetworkIterator::Count() +{ + return mDriver->mStagingNetwork.ssidLen == 0 ? 0 : 1; +} + +bool BLWiFiDriver::WiFiNetworkIterator::Next(Network & item) +{ + if (mExhausted || mDriver->mStagingNetwork.ssidLen == 0) + { + return false; + } + memcpy(item.networkID, mDriver->mStagingNetwork.ssid, mDriver->mStagingNetwork.ssidLen); + item.networkIDLen = mDriver->mStagingNetwork.ssidLen; + item.connected = false; + mExhausted = true; + + Network connectedNetwork; + CHIP_ERROR err = GetConfiguredNetwork(connectedNetwork); + if (err == CHIP_NO_ERROR) + { + if (connectedNetwork.networkIDLen == item.networkIDLen && + memcmp(connectedNetwork.networkID, item.networkID, item.networkIDLen) == 0) + { + item.connected = true; + } + } + return true; +} + +void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg) +{ + if (!(DeviceEventType::IsPlatformSpecific(event->Type) && DeviceEventType::IsPublic(event->Type))) + { + return; + } + + switch (event->Type) + { + case kWiFiOnInitDone: + break; + case kWiFiOnScanDone: + BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(); + break; + case kWiFiOnConnecting: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kWiFiOnConnected: + BLWiFiDriver::GetInstance().OnNetworkStatusChange(); + break; + case kGotIpAddress: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManagerImpl::kWiFiStationState_Connected); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kGotIpv6Address: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManagerImpl::kWiFiStationState_Connected); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kWiFiOnDisconnected: + if (ConnectivityManager::kWiFiStationState_Connecting == ConnectivityMgrImpl().GetWiFiStationState()) + { + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting_Failed); + } + break; + default: + ChipLogProgress(DeviceLayer, "Undefined network commission event type %x.\r\n", event->Type); + break; + } +} + +static wifi_conf_t conf = { + .country_code = "CN", +}; + +extern "C" void wifi_event_handler(uint32_t code) +{ + ChipDeviceEvent event; + + memset(&event, 0, sizeof(ChipDeviceEvent)); + + switch (code) + { + case CODE_WIFI_ON_INIT_DONE: + wifi_mgmr_init(&conf); + break; + case CODE_WIFI_ON_MGMR_DONE: + wifi_mgmr_sta_autoconnect_enable(); + break; + case CODE_WIFI_ON_SCAN_DONE: + event.Type = kWiFiOnScanDone; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_CONNECTING: + event.Type = kWiFiOnConnecting; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_CONNECTED: + event.Type = kWiFiOnConnected; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_GOT_IP: + event.Type = kGotIpAddress; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_DISCONNECT: + event.Type = kWiFiOnDisconnected; + PlatformMgr().PostEventOrDie(&event); + break; + default: { + ChipLogProgress(DeviceLayer, "[APP] [EVT] Unknown code %lu \r\n", code); + } + } +} + +extern "C" void network_netif_ext_callback(struct netif * nif, netif_nsc_reason_t reason, const netif_ext_callback_args_t * args) +{ + ChipDeviceEvent event; + + memset(&event, 0, sizeof(ChipDeviceEvent)); + + if (((LWIP_NSC_IPV6_ADDR_STATE_CHANGED | LWIP_NSC_IPV6_SET) & reason) && args) + { + + if (args->ipv6_addr_state_changed.addr_index >= LWIP_IPV6_NUM_ADDRESSES || + ip6_addr_islinklocal(netif_ip6_addr(nif, args->ipv6_addr_state_changed.addr_index))) + { + return; + } + + if (netif_ip6_addr_state(nif, args->ipv6_addr_state_changed.addr_index) != args->ipv6_addr_state_changed.old_state && + ip6_addr_ispreferred(netif_ip6_addr_state(nif, args->ipv6_addr_state_changed.addr_index))) + { + event.Type = kGotIpv6Address; + PlatformMgr().PostEventOrDie(&event); + } + } + + if ((LWIP_NSC_IPV4_SETTINGS_CHANGED & reason) && args) + { + if (!ip4_addr_isany(netif_ip4_addr(nif)) && !ip4_addr_isany(netif_ip4_gw(nif))) + { + event.Type = kGotIpAddress; + PlatformMgr().PostEventOrDie(&event); + } + } +} + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip +// #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h new file mode 100644 index 00000000000000..5a8cc7a1096d03 --- /dev/null +++ b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h @@ -0,0 +1,150 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + +#pragma once +extern "C" { +#include +} +#include + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg); + +namespace { +constexpr uint8_t kMaxWiFiNetworks = 1; +constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; +constexpr uint8_t kWiFiConnectNetworkTimeoutSeconds = 20; +} // namespace + +class BLScanResponseIterator : public Iterator +{ +public: + BLScanResponseIterator(const size_t size, const wifi_mgmr_scan_item_t * scanResults) : mSize(size), mpScanResults(scanResults) + {} + size_t Count() override { return mSize; } + bool Next(WiFiScanResponse & item) override + { + if (mIternum >= mSize) + { + return false; + } + + item.security.SetRaw(mpScanResults[mIternum].auth); + item.ssidLen = (uint32_t) (mpScanResults[mIternum].ssid_len) < chip::DeviceLayer::Internal::kMaxWiFiSSIDLength + ? mpScanResults[mIternum].ssid_len + : chip::DeviceLayer::Internal::kMaxWiFiSSIDLength; + item.channel = mpScanResults[mIternum].channel; + item.wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4; + item.rssi = mpScanResults[mIternum].rssi; + memcpy(item.ssid, mpScanResults[mIternum].ssid, item.ssidLen); + memcpy(item.bssid, mpScanResults[mIternum].bssid, 6); + + mIternum++; + return true; + } + void Release() override {} + +private: + const size_t mSize; + const wifi_mgmr_scan_item_t * mpScanResults; + size_t mIternum = 0; +}; + +class BLWiFiDriver final : public WiFiDriver +{ +public: + class WiFiNetworkIterator final : public NetworkIterator + { + public: + WiFiNetworkIterator(BLWiFiDriver * aDriver) : mDriver(aDriver) {} + size_t Count() override; + bool Next(Network & item) override; + void Release() override { delete this; } + ~WiFiNetworkIterator() = default; + + private: + BLWiFiDriver * mDriver; + bool mExhausted = false; + }; + + struct WiFiNetwork + { + char ssid[DeviceLayer::Internal::kMaxWiFiSSIDLength]; + uint8_t ssidLen = 0; + char credentials[DeviceLayer::Internal::kMaxWiFiKeyLength]; + uint8_t credentialsLen = 0; + }; + + // BaseDriver + NetworkIterator * GetNetworks() override { return new WiFiNetworkIterator(this); } + CHIP_ERROR Init(NetworkStatusChangeCallback * networkStatusChangeCallback) override; + void Shutdown(); + + // WirelessDriver + uint8_t GetMaxNetworks() override { return kMaxWiFiNetworks; } + uint8_t GetScanNetworkTimeoutSeconds() override { return kWiFiScanNetworksTimeOutSeconds; } + uint8_t GetConnectNetworkTimeoutSeconds() override { return kWiFiConnectNetworkTimeoutSeconds; } + + CHIP_ERROR CommitConfiguration() override; + CHIP_ERROR SaveConfiguration(); + CHIP_ERROR RevertConfiguration() override; + + Status RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) override; + Status ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) override; + void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; + + // WiFiDriver + Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) override; + void ScanNetworks(ByteSpan ssid, ScanCallback * callback) override; + + CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen); + CHIP_ERROR ReConnectWiFiNetwork(void); + void OnConnectWiFiNetwork(bool isConnected); + void OnScanWiFiNetworkDone(); + void OnNetworkStatusChange(); + + CHIP_ERROR SetLastDisconnectReason(const ChipDeviceEvent * event); + int32_t GetLastDisconnectReason(); + + static BLWiFiDriver & GetInstance() + { + static BLWiFiDriver instance; + return instance; + } + +private: + bool NetworkMatch(const WiFiNetwork & network, ByteSpan networkId); + + WiFiNetwork mSavedNetwork; + WiFiNetwork mStagingNetwork; + ScanCallback * mpScanCallback; + ConnectCallback * mpConnectCallback; + NetworkStatusChangeCallback * mpStatusChangeCallback = nullptr; + int32_t mLastDisconnectedReason; +}; + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp new file mode 100644 index 00000000000000..4ed9920cfd843d --- /dev/null +++ b/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp @@ -0,0 +1,108 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#if CHIP_SYSTEM_CONFIG_USE_LWIP +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#include +#endif + +#include +#include +extern "C" { +#include +#include +} + +namespace chip { +namespace DeviceLayer { + +static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen) +{ + bflb_trng_readlen(reinterpret_cast(output), static_cast(len)); + *olen = len; + return 0; +} + +CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + TaskHandle_t backup_eventLoopTask; + int iret_rfInit = -1; + + pt_table_set_flash_operation(bflb_flash_erase, bflb_flash_write, bflb_flash_read); + + VerifyOrDieWithMsg(0 == (iret_rfInit = rfparam_init(0, NULL, 0)), DeviceLayer, "rfparam_init failed with %d", iret_rfInit); + +#if CHIP_SYSTEM_CONFIG_USE_LWIP + tcpip_init(NULL, NULL); +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + wifi_start_firmware_task(); +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + otRadio_opt_t opt; +#if CHIP_DEVICE_CONFIG_THREAD_FTD + opt.bf.isFtd = true; +#else + opt.bf.isFtd = false; +#endif + opt.bf.isCoexEnable = true; + + ot_alarmInit(); + ot_radioInit(opt); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + + ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); + + err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); + SuccessOrExit(err); + + // Call _InitChipStack() on the generic implementation base class + // to finish the initialization process. + /** weiyin, backup mEventLoopTask which is reset in _InitChipStack */ + backup_eventLoopTask = Internal::GenericPlatformManagerImpl_FreeRTOS::mEventLoopTask; + err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); + SuccessOrExit(err); + Internal::GenericPlatformManagerImpl_FreeRTOS::mEventLoopTask = backup_eventLoopTask; + +exit: + return err; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp b/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp new file mode 100644 index 00000000000000..251ccf5113a294 --- /dev/null +++ b/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include + +#include + +#include + +#include + +#include +#include + +namespace chip { +namespace DeviceLayer { + +using namespace ::chip::DeviceLayer::Internal; + +ThreadStackManagerImpl ThreadStackManagerImpl::sInstance; + +CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack(void) +{ + return InitThreadStack(NULL); +} + +CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Initialize the generic implementation base classes. + err = GenericThreadStackManagerImpl_FreeRTOS::DoInit(); + SuccessOrExit(err); + err = GenericThreadStackManagerImpl_OpenThread::DoInit(otInst); + SuccessOrExit(err); + +exit: + return err; +} + +bool ThreadStackManagerImpl::IsInitialized() +{ + return sInstance.mThreadStackLock != NULL; +} + +} // namespace DeviceLayer +} // namespace chip + +using namespace ::chip::DeviceLayer; + +ot_system_event_t ot_system_event_var = OT_SYSTEM_EVENT_NONE; + +void otSysProcessDrivers(otInstance * aInstance) +{ + ot_system_event_t sevent = otrGetNotifyEvent(); + + ot_alarmTask(sevent); + ot_radioTask(sevent); +} + +extern "C" void otTaskletsSignalPending(otInstance * p_instance) +{ + otSysEventSignalPending(); +} + +extern "C" void otSysEventSignalPending(void) +{ + if (xPortIsInsideInterrupt()) + { + BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); + portYIELD_FROM_ISR(yieldRequired); + } + else + { + ThreadStackMgrImpl().SignalThreadActivityPending(); + } +} + +extern "C" otInstance * otrGetInstance() +{ + return ThreadStackMgrImpl().OTInstance(); +} + +extern "C" void otrLock(void) +{ + ThreadStackMgrImpl().LockThreadStack(); +} + +extern "C" void otrUnlock(void) +{ + ThreadStackMgrImpl().UnlockThreadStack(); +} + +extern "C" uint32_t otrEnterCrit(void) +{ + if (xPortIsInsideInterrupt()) + { + return taskENTER_CRITICAL_FROM_ISR(); + } + else + { + taskENTER_CRITICAL(); + return 0; + } +} + +extern "C" void otrExitCrit(uint32_t tag) +{ + if (xPortIsInsideInterrupt()) + { + taskEXIT_CRITICAL_FROM_ISR(tag); + } + else + { + taskEXIT_CRITICAL(); + } +} + +extern "C" ot_system_event_t otrGetNotifyEvent(void) +{ + ot_system_event_t sevent = OT_SYSTEM_EVENT_NONE; + + taskENTER_CRITICAL(); + sevent = ot_system_event_var; + ot_system_event_var = OT_SYSTEM_EVENT_NONE; + taskEXIT_CRITICAL(); + + return sevent; +} + +extern "C" void otrNotifyEvent(ot_system_event_t sevent) +{ + if (xPortIsInsideInterrupt()) + { + ot_system_event_var = (ot_system_event_t) (ot_system_event_var | sevent); + } + else + { + uint32_t tag = otrEnterCrit(); + ot_system_event_var = (ot_system_event_t) (ot_system_event_var | sevent); + otrExitCrit(tag); + } + + otSysEventSignalPending(); +} diff --git a/src/platform/bouffalolab/BL616/args.gni b/src/platform/bouffalolab/BL616/args.gni new file mode 100644 index 00000000000000..728448a63908c7 --- /dev/null +++ b/src/platform/bouffalolab/BL616/args.gni @@ -0,0 +1,40 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") +import("${chip_root}/examples/platform/bouffalolab/bl616/args.gni") + +riscv_platform_config = "${bouffalolab_iot_sdk_build_root}/common/rsicv.gni" + +mbedtls_target = "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" + +chip_device_platform = "bl616" + +chip_enable_ota_requestor = true + +lwip_platform = "bl616" + +chip_inet_config_enable_tcp_endpoint = false + +chip_build_tests = false + +openthread_external_mbedtls = mbedtls_target + +openthread_core_config_platform_check_file = + "bl616-openthread-core-bl-config-check.h" +openthread_project_include_dirs = + [ "${chip_root}/src/platform/bouffalolab/BL616" ] +openthread_external_platform = + "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" diff --git a/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h b/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h new file mode 100644 index 00000000000000..32eeb078fbe236 --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#ifndef MBEDTLS_CONFIG_H +#define MBEDTLS_CONFIG_H +#include +#include +#include + +/** + * Enable FreeRTOS threading support + */ +#define MBEDTLS_FREERTOS +// #define MBEDTLS_THREADING_C + +/** + * Enable H Crypto and Entropy modules + */ +#define MBEDTLS_AES_C +#define MBEDTLS_ECP_C +#define MBEDTLS_ECDH_C +#define MBEDTLS_ENTROPY_C +#define MBEDTLS_SHA256_C +#define MBEDTLS_CIPHER_MODE_CTR +#define MBEDTLS_TRNG_C + +#if defined(MBEDTLS_ECP_ALT) && !defined(MBEDTLS_ECP_RESTARTABLE) +typedef void mbedtls_ecp_restart_ctx; +#endif + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +#define MBEDTLS_PLATFORM_MEMORY + +#define MBEDTLS_CIPHER_PADDING_PKCS7 +#define MBEDTLS_CIPHER_PADDING_ZEROS +#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES +#define MBEDTLS_REMOVE_3DES_CIPHERSUITES + +#define MBEDTLS_AES_ROM_TABLES +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C +#define MBEDTLS_BASE64_C +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_CCM_C +#define MBEDTLS_CIPHER_C +#define MBEDTLS_CIPHER_MODE_CBC +#define MBEDTLS_CIPHER_MODE_CFB +#define MBEDTLS_CMAC_C +#define MBEDTLS_CTR_DRBG_C +#define MBEDTLS_DEBUG_C +#define MBEDTLS_ECDH_LEGACY_CONTEXT +#define MBEDTLS_ECDSA_C +#define MBEDTLS_ECDSA_DETERMINISTIC +#define MBEDTLS_ECJPAKE_C +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_NIST_OPTIM +#define MBEDTLS_ENTROPY_FORCE_SHA256 + +#define MBEDTLS_ERROR_C +#define MBEDTLS_GCM_C +#define MBEDTLS_ERROR_STRERROR_DUMMY +#define MBEDTLS_HAVE_ASM +#define MBEDTLS_HKDF_C +#define MBEDTLS_HMAC_DRBG_C +#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED +#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + +#define MBEDTLS_MD_C +#define MBEDTLS_MD5_C +#define MBEDTLS_OID_C +#define MBEDTLS_PEM_PARSE_C +#define MBEDTLS_PEM_WRITE_C +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#define MBEDTLS_PK_WRITE_C +#define MBEDTLS_PKCS5_C +#define MBEDTLS_PKCS1_V15 +#define MBEDTLS_PKCS1_V21 + +#define MBEDTLS_PLATFORM_C +#define MBEDTLS_GENPRIME +#define MBEDTLS_RSA_C +#define MBEDTLS_DHM_C + +#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define MBEDTLS_PSA_CRYPTO_C +#define MBEDTLS_PSA_CRYPTO_CONFIG +#define MBEDTLS_PSA_CRYPTO_DRIVERS +#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS +#define MBEDTLS_PSA_CRYPTO_STORAGE_C + +#define MBEDTLS_SHA1_C +#define MBEDTLS_SHA256_SMALLER +#define MBEDTLS_SHA512_C + +#define MBEDTLS_SSL_CLI_C +#define MBEDTLS_SSL_COOKIE_C +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY +#define MBEDTLS_SSL_EXPORT_KEYS +#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#define MBEDTLS_SSL_PROTO_TLS1_2 +#define MBEDTLS_SSL_ALPN +#define MBEDTLS_SSL_SESSION_TICKETS +#define MBEDTLS_SSL_PROTO_DTLS +#define MBEDTLS_SSL_SRV_C +#define MBEDTLS_SSL_TLS_C +#define MBEDTLS_SSL_SERVER_NAME_INDICATION +#define MBEDTLS_X509_CREATE_C +#define MBEDTLS_X509_CSR_WRITE_C +#define MBEDTLS_X509_CRL_PARSE_C +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_X509_CSR_PARSE_C +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CHECK_KEY_USAGE +#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + +#define MBEDTLS_NO_PLATFORM_ENTROPY +#define MBEDTLS_ENTROPY_HARDWARE_ALT + +#define MBEDTLS_PLATFORM_STD_MEM_HDR "mbedtls_port_bouffalo_sdk.h" +#define MBEDTLS_SSL_MAX_CONTENT_LEN 900 /**< Maxium fragment length in bytes */ + +#define MBEDTLS_SHA1_ALT +#define MBEDTLS_SHA256_ALT +#define MBEDTLS_SHA512_ALT +#define MBEDTLS_AES_ALT +#define MBEDTLS_ECP_ALT + +#if defined(CONFIG_MBEDTLS_ECC_USE_HW) && defined(MBEDTLS_ECP_RESTARTABLE) +#error "ECP Restartable is not implemented with ECP HW acceleration!" +#endif + +#include "mbedtls/check_config.h" + +#endif /* MBEDTLS_CONFIG_H */ diff --git a/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h new file mode 100644 index 00000000000000..8c15b61eb608bc --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OPENTHREAD_CORE_CONFIG_CHECK_H_ +#define OPENTHREAD_CORE_CONFIG_CHECK_H_ + +#if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT +#error "Platform doesn't support configuration option: OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT" +#endif + +#endif /* OPENTHREAD_CORE_CONFIG_CHECK_H_ */ diff --git a/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h new file mode 100644 index 00000000000000..8c4c5f3807a7d0 --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2016, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OPENTHREAD_CORE_PROJ_CONFIG_H +#define OPENTHREAD_CORE_PROJ_CONFIG_H + +#define OPENTHREAD_CONFIG_PLATFORM_INFO "BL616" + +// #define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_DEBG + +#if !defined(OPENTHREAD_FTD) && !defined(OPENTHREAD_MTD) +#if CHIP_DEVICE_CONFIG_THREAD_FTD +#define OPENTHREAD_FTD 1 +#define OPENTHREAD_MTD 0 +#else +#define OPENTHREAD_FTD 0 +#define OPENTHREAD_MTD 1 +#endif +#endif + +#define OPENTHREAD_CONFIG_PING_SENDER_ENABLE 1 + +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE 1 + +#define OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE 1 +#define OPENTHREAD_CONFIG_DUA_ENABLE 1 +#define OPENTHREAD_CONFIG_MLR_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE 1 + +#define OPENTHREAD_CONFIG_TMF_NETDIAG_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE 1 +#define OPENTHREAD_CONFIG_TMF_ANYCAST_LOCATOR_ENABLE 1 +#define OPENTHREAD_CONFIG_DATASET_UPDATER_ENABLE 1 + +// #define OPENTHREAD_CONFIG_COAP_API_ENABLE 1 +// #define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 1 +// #define OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 +#define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_SNTP_CLIENT_ENABLE 1 + +#define OPENTHREAD_CONFIG_NEIGHBOR_DISCOVERY_AGENT_ENABLE 1 + +#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE 1 + +// #define OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE 1 + +// #define OPENTHREAD_CONFIG_MAC_BEACON_PAYLOAD_PARSING_ENABLE 1 +// #define OPENTHREAD_CONFIG_MAC_OUTGOING_BEACON_PAYLOAD_ENABLE 1 + +#if OPENTHREAD_FTD +#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 1 +#define OPENTHREAD_CONFIG_JOINER_ENABLE 1 +#endif + +#if OPENTHREAD_MTD +#define OPENTHREAD_CONFIG_JOINER_ENABLE 1 +#endif + +#define OPENTHREAD_CONFIG_TCP_ENABLE 0 +#define OPENTHREAD_CONFIG_TLS_ENABLE 0 +#define OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 +#define OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE 0 + +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ACK_TIMEOUT_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_RETRANSMIT_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_CSMA_BACKOFF_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_TX_SECURITY_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_TX_TIMING_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ENERGY_SCAN_ENABLE 1 + +#define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 1 +#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 + +#define OPENTHREAD_EXAMPLES_SIMULATION 0 +#define OPENTHREAD_PLATFORM_POSIX 0 +#define OPENTHREAD_ENABLE_VENDOR_EXTENSION 0 + +#define IEEE802_15_4_RADIO_RECEIVE_SENSITIVITY -105 +#define OPENTHREAD_CONFIG_PLATFORM_XTAL_ACCURACY 40 + +#endif // OPENTHREAD_CORE_PROJ_CONFIG_H diff --git a/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c new file mode 100644 index 00000000000000..bf22cb51abccc3 --- /dev/null +++ b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c @@ -0,0 +1,59 @@ +#include +#include + +#include +#include + +#include +#undef __INLINE +#undef __PACKED +#include + +#include + +#define WIFI_STACK_SIZE (1536) +#define TASK_PRIORITY_FW (16) + +static TaskHandle_t wifi_fw_task; +static netif_ext_callback_t netifExtCallback; + +struct netif * deviceInterface_getNetif(void) +{ + LOCK_TCPIP_CORE(); + struct netif * net_if = netif_find("wl1"); + UNLOCK_TCPIP_CORE(); + + return net_if; +} + +int wifi_start_scan(const uint8_t * ssid, uint32_t length) +{ + wifi_mgmr_scan_params_t config; + + memset(&config, 0, sizeof(wifi_mgmr_scan_params_t)); + if (length && length <= MGMR_SSID_LEN) + { + memcpy(config.ssid_array, ssid, length); + config.ssid_length = length; + } + + return wifi_mgmr_sta_scan(&config); +} + +void wifi_start_firmware_task(void) +{ + memset(&netifExtCallback, 0, sizeof(netifExtCallback)); + + GLB_PER_Clock_UnGate(GLB_AHB_CLOCK_IP_WIFI_PHY | GLB_AHB_CLOCK_IP_WIFI_MAC_PHY | GLB_AHB_CLOCK_IP_WIFI_PLATFORM); + GLB_AHB_MCU_Software_Reset(GLB_AHB_MCU_SW_WIFI); + + extern void interrupt0_handler(void); + bflb_irq_attach(WIFI_IRQn, (irq_callback) interrupt0_handler, NULL); + bflb_irq_enable(WIFI_IRQn); + + LOCK_TCPIP_CORE(); + netif_add_ext_callback(&netifExtCallback, network_netif_ext_callback); + UNLOCK_TCPIP_CORE(); + + xTaskCreate(wifi_main, (char *) "fw", WIFI_STACK_SIZE, NULL, TASK_PRIORITY_FW, &wifi_fw_task); +} diff --git a/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h new file mode 100644 index 00000000000000..9ebffffa20e422 --- /dev/null +++ b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h @@ -0,0 +1,18 @@ +#ifndef __WIFI_MGMR_POARABLE_H__ +#define __WIFI_MGMR_POARABLE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +int wifi_start_scan(const uint8_t * ssid, uint32_t length); +void network_netif_ext_callback(struct netif * netif, netif_nsc_reason_t reason, const netif_ext_callback_args_t * args); +void wifi_start_firmware_task(void); + +struct netif * deviceInterface_getNetif(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index e0daee04056a51..c9112449a652fc 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -41,6 +41,7 @@ static_library("BL702") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -57,8 +58,6 @@ static_library("BL702") { ] } - deps = [ "${chip_root}/src/platform/logging:headers" ] - if (chip_enable_factory_data) { sources += [ "../common/FactoryDataProvider.cpp", @@ -72,6 +71,11 @@ static_library("BL702") { sources += [ "../common/BLConfig_littlefs.cpp" ] } + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + if (chip_enable_wifi) { sources += [ "ConfigurationManagerImpl.cpp", @@ -115,6 +119,5 @@ static_library("BL702") { deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } - deps += [ "${chip_root}/src/credentials:credentials_header" ] public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp index ae68f9c680795c..94835f921c753f 100644 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp @@ -79,8 +79,6 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) ot_radioInit(opt); #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); SuccessOrExit(err); diff --git a/src/platform/bouffalolab/BL702L/BUILD.gn b/src/platform/bouffalolab/BL702L/BUILD.gn index 2529c8d3a7e736..c32dc33255e541 100644 --- a/src/platform/bouffalolab/BL702L/BUILD.gn +++ b/src/platform/bouffalolab/BL702L/BUILD.gn @@ -39,6 +39,7 @@ static_library("BL702L") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -55,8 +56,6 @@ static_library("BL702L") { ] } - deps = [ "${chip_root}/src/platform/logging:headers" ] - if (chip_enable_factory_data) { sources += [ "../common/FactoryDataProvider.cpp", @@ -70,6 +69,11 @@ static_library("BL702L") { sources += [ "../common/BLConfig_littlefs.cpp" ] } + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + if (chip_enable_openthread) { # needed for MTD/FTD @@ -92,6 +96,5 @@ static_library("BL702L") { } } - deps += [ "${chip_root}/src/credentials:credentials_header" ] public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp index 68c75305f64ed8..2cd84609ef0505 100644 --- a/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp @@ -57,17 +57,22 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) TaskHandle_t backup_eventLoopTask; otRadio_opt_t opt; + opt.byte = 0; - opt.byte = 0; +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#if CHIP_DEVICE_CONFIG_THREAD_FTD + opt.bf.isFtd = true; +#else + opt.bf.isFtd = false; +#endif opt.bf.isCoexEnable = true; +#endif ot_utils_init(); ot_alarmInit(); ot_radioInit(opt); - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - #if CHIP_SYSTEM_CONFIG_USE_LWIP // Initialize LwIP. tcpip_init(NULL, NULL); diff --git a/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h b/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h index 6937bba875750b..659f782448357c 100644 --- a/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h +++ b/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h @@ -32,6 +32,7 @@ #define OPENTHREAD_CONFIG_PLATFORM_INFO "BL702L" // #define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_DEBG +// #define OPENTHREAD_CONFIG_LOG_PKT_DUMP 0 #if !defined(OPENTHREAD_FTD) && !defined(OPENTHREAD_MTD) #if CHIP_DEVICE_CONFIG_THREAD_FTD diff --git a/src/platform/bouffalolab/common/BLConfig_littlefs.cpp b/src/platform/bouffalolab/common/BLConfig_littlefs.cpp index ae0788ab1c8f62..7f5e221195e8d3 100644 --- a/src/platform/bouffalolab/common/BLConfig_littlefs.cpp +++ b/src/platform/bouffalolab/common/BLConfig_littlefs.cpp @@ -36,7 +36,20 @@ namespace chip { namespace DeviceLayer { namespace Internal { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +static struct lfs_context lfs_ctx = { .partition_name = (char *) "PSM" }; +static struct lfs_config lfs_cfg = { + .read_size = 256, + .prog_size = 256, + .block_size = 4096, + .block_cycles = 500, + .cache_size = 512, + .lookahead_size = 256, +}; +static lfs_t * blconfig_lfs = NULL; +#else static lfs_t * blconfig_lfs = nullptr; +#endif static inline char * blcfg_convert_key(const char * pKey, const char * pNameSpace = NULL) { @@ -153,7 +166,11 @@ void BLConfig::Init(void) int ret; struct lfs_info stat; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + blconfig_lfs = lfs_xip_init(&lfs_ctx, &lfs_cfg); +#else blconfig_lfs = lfs_xip_init(); +#endif VerifyOrExit(blconfig_lfs != NULL, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* init namespace */ diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp index 7731828c314ca3..c5a3932e83cc1f 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -31,7 +31,7 @@ #endif extern "C" { -#if CHIP_DEVICE_LAYER_TARGET_BL702L +#if CHIP_DEVICE_LAYER_TARGET_BL702L || CHIP_DEVICE_LAYER_TARGET_BL616 #include #else #include @@ -121,7 +121,7 @@ CHIP_ERROR BLEManagerImpl::_Init() memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); ReturnErrorOnFailure(InitRandomStaticAddress()); -#if CHIP_DEVICE_LAYER_TARGET_BL702L +#if CHIP_DEVICE_LAYER_TARGET_BL702L || CHIP_DEVICE_LAYER_TARGET_BL616 btble_controller_init(configMAX_PRIORITIES - 1); #else ble_controller_init(configMAX_PRIORITIES - 1); @@ -841,6 +841,10 @@ ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gat } #endif +extern "C" int ble_connection_number(void) +{ + return BLEMgr().NumConnections(); +} } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp index 4318dcc4a58dac..176803d00a1ebe 100644 --- a/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp @@ -21,7 +21,13 @@ #include +#if CHIP_DEVICE_LAYER_TARGET_BL616 +extern "C" { +#include +} +#else extern "C" void hal_reboot(void); +#endif namespace chip { namespace DeviceLayer { @@ -202,8 +208,11 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) // Restart the system. ChipLogProgress(DeviceLayer, "System restarting"); - +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bl_sys_reset_por(); +#else hal_reboot(); +#endif } ConfigurationManager & ConfigurationMgrImpl() diff --git a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp index c6babf25e5f74c..dcff80f79beab9 100644 --- a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp @@ -39,6 +39,9 @@ #if CHIP_DEVICE_LAYER_TARGET_BL702 #include #endif +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#endif #endif #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/common/ConnectivityManagerImpl.h b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h index 80b1d980d4f9d1..7a36c59cceca29 100644 --- a/src/platform/bouffalolab/common/ConnectivityManagerImpl.h +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h @@ -46,6 +46,7 @@ enum { kWiFiOnInitDone = DeviceEventType::kRange_PublicPlatformSpecific, kWiFiOnScanDone, + kWiFiOnConnecting, kWiFiOnConnected, kGotIpAddress, kGotIpv6Address, diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp index 45deceb2e03255..a5d70240ba5a04 100644 --- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp @@ -23,7 +23,9 @@ #include #include - +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#endif namespace chip { namespace DeviceLayer { @@ -41,22 +43,33 @@ DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + struct meminfo info; + bflb_mem_usage(KMEM_HEAP, &info); + currentHeapFree = info.free_size; +#else #ifdef CFG_USE_PSRAM - size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); + currentHeapFree = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); #else - size_t freeHeapSize = xPortGetFreeHeapSize(); + currentHeapFree = xPortGetFreeHeapSize(); +#endif #endif - currentHeapFree = static_cast(freeHeapSize); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + struct meminfo info; + bflb_mem_usage(KMEM_HEAP, &info); + currentHeapUsed = info.total_size - info.free_size; +#else #ifdef CFG_USE_PSRAM currentHeapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); #else currentHeapUsed = (get_heap_size() - xPortGetFreeHeapSize()); +#endif #endif return CHIP_NO_ERROR; @@ -64,14 +77,17 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeap CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + return CHIP_ERROR_NOT_IMPLEMENTED; +#else #ifdef CFG_USE_PSRAM currentHeapHighWatermark = get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram(); #else currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize(); #endif - return CHIP_NO_ERROR; +#endif } CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) @@ -233,7 +249,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** #if CHIP_DEVICE_CONFIG_ENABLE_WIFI ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kWiFi; #else - ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kEthernet; + ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kEthernet; #endif ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp index 0d3357b38f0106..d55b2a26d10af4 100644 --- a/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp @@ -19,14 +19,20 @@ #include extern "C" { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#include +#else #include #include - -extern void hal_reboot(void); +#endif } - #include "OTAImageProcessorImpl.h" +#if CHIP_DEVICE_LAYER_TARGET_BL602 || CHIP_DEVICE_LAYER_TARGET_BL702 || CHIP_DEVICE_LAYER_TARGET_BL702L +extern "C" void hal_reboot(void); +#endif + using namespace chip::System; namespace chip { @@ -136,7 +142,11 @@ void OTAImageProcessorImpl::HandleFinalize(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_check() < 0) +#else if (hosal_ota_check() < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); ChipLogProgress(SoftwareUpdate, "OTA image verification error"); @@ -158,12 +168,20 @@ void OTAImageProcessorImpl::HandleApply(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bflb_ota_apply(); +#else hosal_ota_apply(0); +#endif DeviceLayer::SystemLayer().StartTimer( System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), [](Layer *, void *) { ChipLogProgress(SoftwareUpdate, "Rebooting..."); +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bl_sys_reset_por(); +#else hal_reboot(); +#endif }, nullptr); } @@ -176,7 +194,11 @@ void OTAImageProcessorImpl::HandleAbort(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bflb_ota_abort(); +#else hosal_ota_abort(); +#endif imageProcessor->ReleaseBlock(); } @@ -219,7 +241,11 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) imageProcessor->mParams.totalFileBytes = header.mPayloadSize; imageProcessor->mHeaderParser.Clear(); +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_start(header.mPayloadSize) < 0) +#else if (hosal_ota_start(header.mPayloadSize) < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); return; @@ -228,8 +254,13 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) if (imageProcessor->mParams.totalFileBytes) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, + (uint8_t *) block.data(), block.size()) < 0) +#else if (hosal_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, (uint8_t *) block.data(), block.size()) < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl.h b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h index 3e68f3c59d329a..2e0656affacf03 100644 --- a/src/platform/bouffalolab/common/OTAImageProcessorImpl.h +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h @@ -24,6 +24,31 @@ namespace chip { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +typedef struct _ota_header_s +{ + uint8_t header[16]; + + uint8_t type[4]; // RAW XZ + uint32_t image_len; // body len + uint8_t pad0[8]; + + uint8_t ver_hardware[16]; + uint8_t ver_software[16]; + + uint8_t sha256[32]; +} ota_header_s_t; + +typedef struct _ota_header +{ + union + { + ota_header_s_t s; + uint8_t _pad[512]; + } u; +} ota_header_t; +#endif + class OTAImageProcessorImpl : public OTAImageProcessorInterface { public: @@ -59,6 +84,10 @@ class OTAImageProcessorImpl : public OTAImageProcessorInterface MutableByteSpan mBlock; OTADownloader * mDownloader; OTAImageHeaderParser mHeaderParser; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + ota_header_s_t mOtaHdr; + uint32_t mImageTotalSize; +#endif }; } // namespace chip diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp new file mode 100644 index 00000000000000..0e0a6ff0ccd14d --- /dev/null +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "OTAImageProcessorImpl.h" +#include +#include + +extern "C" { +#include +#include +} + +using namespace chip::System; + +namespace chip { + +#define OTA_IMAGE_TYPE_XZ "XZ" +#define OTA_IMAGE_TYPE_RAW "RAW" + +static bool check_ota_header(ota_header_s_t * ota_header_s) +{ + char str[sizeof(ota_header_s->header) + 1]; + + memcpy(str, ota_header_s->header, sizeof(ota_header_s->header)); + str[sizeof(ota_header_s->header)] = '\0'; + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA header: %s", str); + + if (0 == memcmp(OTA_IMAGE_TYPE_XZ, ota_header_s->type, strlen(OTA_IMAGE_TYPE_XZ))) + { + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image type: %s", OTA_IMAGE_TYPE_XZ); + } + else if (0 == memcmp(OTA_IMAGE_TYPE_RAW, ota_header_s->type, strlen(OTA_IMAGE_TYPE_RAW))) + { + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image type: %s", OTA_IMAGE_TYPE_RAW); + } + else + { + return false; + } + + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image file size: %ld", ota_header_s->image_len); + + memcpy(str, ota_header_s->ver_hardware, sizeof(ota_header_s->ver_hardware)); + str[sizeof(ota_header_s->ver_hardware)] = '\0'; + ChipLogProgress(SoftwareUpdate, "OTA image hardware version: %s", str); + + memcpy(str, ota_header_s->ver_software, sizeof(ota_header_s->ver_software)); + str[sizeof(ota_header_s->ver_software)] = '\0'; + ChipLogProgress(SoftwareUpdate, "OTA image software version: %s", str); + + return true; +} + +bool OTAImageProcessorImpl::IsFirstImageRun() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return false; + } + + return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying; +} + +CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return CHIP_ERROR_INTERNAL; + } + + uint32_t currentVersion; + uint32_t targetVersion = requestor->GetTargetVersion(); + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); + if (currentVersion != targetVersion) + { + ChipLogError(SoftwareUpdate, "Current software version = %" PRIu32 ", expected software version = %" PRIu32, currentVersion, + targetVersion); + return CHIP_ERROR_INCORRECT_STATE; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Finalize() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Apply() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Abort() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) +{ + if ((nullptr == block.data()) || block.empty()) + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Store block data for HandleProcessBlock to access + CHIP_ERROR err = SetBlock(block); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); + } + + DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + + imageProcessor->mParams.downloadedBytes = 0; + imageProcessor->mParams.totalFileBytes = 0; + imageProcessor->mHeaderParser.Init(); + + memset(&(imageProcessor->mOtaHdr), 0, sizeof(ota_header_s_t)); + imageProcessor->mImageTotalSize = 0; + + imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); +} + +void OTAImageProcessorImpl::HandleFinalize(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + return; + } + + ByteSpan block = imageProcessor->mBlock; + + if (bflb_ota_update(imageProcessor->mImageTotalSize, imageProcessor->mParams.downloadedBytes - sizeof(ota_header_t), + imageProcessor->mOtaHdr.sha256, sizeof(imageProcessor->mOtaHdr.sha256)) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + + if (bflb_ota_check() < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + ChipLogProgress(SoftwareUpdate, "OTA image verification error"); + } + else + { + ChipLogProgress(SoftwareUpdate, "OTA image downloaded"); + } + + imageProcessor->ReleaseBlock(); +} + +void OTAImageProcessorImpl::HandleApply(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + return; + } + + bflb_ota_apply(); + + DeviceLayer::SystemLayer().StartTimer( + System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), + [](Layer *, void *) { + ChipLogProgress(SoftwareUpdate, "Rebooting..."); + bl_sys_reset_por(); + }, + nullptr); +} + +void OTAImageProcessorImpl::HandleAbort(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + if (imageProcessor == nullptr) + { + return; + } + + bflb_ota_abort(); + + imageProcessor->ReleaseBlock(); +} + +void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) +{ + OTAImageHeader header; + CHIP_ERROR error; + uint32_t iOffset, iSize; + + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + + ByteSpan block = imageProcessor->mBlock; + if (imageProcessor->mHeaderParser.IsInitialized()) + { + error = imageProcessor->mHeaderParser.AccumulateAndDecode(block, header); + if (CHIP_ERROR_BUFFER_TOO_SMALL == error) + { + return; + } + else if (CHIP_NO_ERROR != error) + { + ChipLogError(SoftwareUpdate, "Matter image header parser error %s", chip::ErrorStr(error)); + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER); + imageProcessor->mHeaderParser.Clear(); + return; + } + + ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, + (long unsigned int) header.mPayloadSize); + imageProcessor->mParams.totalFileBytes = header.mPayloadSize; + imageProcessor->mHeaderParser.Clear(); + } + + if (imageProcessor->mParams.totalFileBytes) + { + if (0 == imageProcessor->mImageTotalSize) + { + + iSize = sizeof(ota_header_s_t) - imageProcessor->mParams.downloadedBytes; + if (block.size() < iSize) + { + iSize = block.size(); + } + + memcpy(reinterpret_cast(&imageProcessor->mOtaHdr) + imageProcessor->mParams.downloadedBytes, block.data(), + iSize); + + if (imageProcessor->mParams.downloadedBytes + iSize >= sizeof(ota_header_s_t)) + { + if (!check_ota_header(&imageProcessor->mOtaHdr)) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_DECODE_FAILED); + return; + } + + if (bflb_ota_start(imageProcessor->mOtaHdr.image_len + sizeof(imageProcessor->mOtaHdr.sha256)) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); + return; + } + + imageProcessor->mImageTotalSize = imageProcessor->mOtaHdr.image_len + sizeof(imageProcessor->mOtaHdr.sha256); + } + } + + if (imageProcessor->mImageTotalSize && imageProcessor->mParams.downloadedBytes + block.size() > sizeof(ota_header_t)) + { + + if (imageProcessor->mParams.downloadedBytes >= sizeof(ota_header_t)) + { + iOffset = imageProcessor->mParams.downloadedBytes - sizeof(ota_header_t); + iSize = 0; + } + else + { + iOffset = 0; + iSize = sizeof(ota_header_t) - imageProcessor->mParams.downloadedBytes; + } + + if (bflb_ota_update(imageProcessor->mImageTotalSize, iOffset, const_cast(block.data() + iSize), + block.size() - iSize) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + } + + imageProcessor->mParams.downloadedBytes += block.size(); + } + + imageProcessor->mDownloader->FetchNextData(); +} + +// Store block data for HandleProcessBlock to access +CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) +{ + if ((block.data() == nullptr) || block.empty()) + { + return CHIP_NO_ERROR; + } + + // Allocate memory for block data if we don't have enough already + if (mBlock.size() < block.size()) + { + ReleaseBlock(); + + mBlock = MutableByteSpan(static_cast(chip::Platform::MemoryAlloc(block.size())), block.size()); + if (mBlock.data() == nullptr) + { + return CHIP_ERROR_NO_MEMORY; + } + } + + // Store the actual block data + CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() +{ + if (mBlock.data() != nullptr) + { + chip::Platform::MemoryFree(mBlock.data()); + } + + mBlock = MutableByteSpan(); + return CHIP_NO_ERROR; +} + +} // namespace chip diff --git a/src/platform/bouffalolab/common/SystemPlatformConfig.h b/src/platform/bouffalolab/common/SystemPlatformConfig.h index c42b2671f84b48..89a0a5a8f9a966 100644 --- a/src/platform/bouffalolab/common/SystemPlatformConfig.h +++ b/src/platform/bouffalolab/common/SystemPlatformConfig.h @@ -34,5 +34,13 @@ struct ChipDeviceEvent; #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 #endif +#if CHIP_DEVICE_LAYER_TARGET_BL616 +// #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(mbedtls_sha256_context) in hw_acc/sha256_alt.h +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE (32 + 64 + 64 + 19 * 32) +#define CHIP_CONFIG_SHA256_CONTEXT_ALIGN 32 +#define CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE (388) +#else + // #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) #define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((7 + 1 + 5 + 18 + 16 + 16 + 7) * sizeof(unsigned int)) +#endif diff --git a/src/platform/bouffalolab/common/SystemTimeSupport.cpp b/src/platform/bouffalolab/common/SystemTimeSupport.cpp new file mode 100644 index 00000000000000..89a9756ca23fde --- /dev/null +++ b/src/platform/bouffalolab/common/SystemTimeSupport.cpp @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* this file behaves like a config.h, comes first */ +#include + +#include +#include + +#include + +#if CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME + +namespace chip { +namespace System { +namespace Clock { + +namespace Internal { +ClockImpl gClockImpl; +} // namespace Internal + +static Microseconds64 gBootRealTime = Seconds64::zero(); + +Microseconds64 ClockImpl::GetMonotonicMicroseconds64(void) +{ + return Clock::Microseconds64(bl_timer_now_us64()); +} + +Milliseconds64 ClockImpl::GetMonotonicMilliseconds64(void) +{ + return Clock::Milliseconds64(bl_timer_now_us64() / 1000); +} + +CHIP_ERROR ClockImpl::GetClock_RealTime(Microseconds64 & aCurTime) +{ + aCurTime = gBootRealTime + GetMonotonicMicroseconds64(); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::GetClock_RealTimeMS(Milliseconds64 & aCurTime) +{ + Microseconds64 curTimeUs; + + GetClock_RealTime(curTimeUs); + aCurTime = std::chrono::duration_cast(curTimeUs); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::SetClock_RealTime(Microseconds64 aNewCurTime) +{ + gBootRealTime = aNewCurTime - GetMonotonicMicroseconds64(); + + return CHIP_NO_ERROR; +} + +} // namespace Clock +} // namespace System +} // namespace chip + +#endif diff --git a/src/platform/bouffalolab/common/SystemTimeSupport.h b/src/platform/bouffalolab/common/SystemTimeSupport.h new file mode 100644 index 00000000000000..7ef95ab66c67cd --- /dev/null +++ b/src/platform/bouffalolab/common/SystemTimeSupport.h @@ -0,0 +1,24 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +namespace chip { +namespace System { +namespace Clock {} // namespace Clock +} // namespace System +} // namespace chip diff --git a/src/platform/device.gni b/src/platform/device.gni index 87e2eb12e8d0d2..a28d9823a91438 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -175,6 +175,8 @@ if (chip_device_platform == "cc13x4_26x4") { _chip_device_layer = "Ameba" } else if (chip_device_platform == "bl602") { _chip_device_layer = "bouffalolab/common" +} else if (chip_device_platform == "bl616") { + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702") { _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702l") { @@ -265,9 +267,9 @@ assert( chip_device_platform == "ameba" || chip_device_platform == "cyw30739" || chip_device_platform == "webos" || chip_device_platform == "mw320" || chip_device_platform == "zephyr" || chip_device_platform == "beken" || - chip_device_platform == "bl602" || chip_device_platform == "bl702" || - chip_device_platform == "bl702l" || chip_device_platform == "mt793x" || - chip_device_platform == "SiWx917" || + chip_device_platform == "bl602" || chip_device_platform == "bl616" || + chip_device_platform == "bl702" || chip_device_platform == "bl702l" || + chip_device_platform == "mt793x" || chip_device_platform == "SiWx917" || chip_device_platform == "openiotsdk" || chip_device_platform == "asr" || chip_device_platform == "stm32" || chip_device_platform == "nuttx", "Please select a valid value for chip_device_platform") diff --git a/src/platform/logging/BUILD.gn b/src/platform/logging/BUILD.gn index eb3c62154ce436..9ed7bd2f4d6ca5 100644 --- a/src/platform/logging/BUILD.gn +++ b/src/platform/logging/BUILD.gn @@ -29,6 +29,7 @@ group("default") { } else if (chip_device_platform == "mbed") { deps += [ "${chip_root}/src/platform/mbed:logging" ] } else if (chip_device_platform == "bl602" || + chip_device_platform == "bl616" || chip_device_platform == "bl702" || chip_device_platform == "bl702l") { deps += [ "${chip_root}/src/platform/bouffalolab/common:logging" ] diff --git a/src/system/BUILD.gn b/src/system/BUILD.gn index 40ae99ae99c77e..c222f44673268c 100644 --- a/src/system/BUILD.gn +++ b/src/system/BUILD.gn @@ -72,6 +72,8 @@ if (chip_device_platform == "cc13x4_26x4") { import("//build_overrides/bouffalolab_iot_sdk.gni") } else if (chip_device_platform == "bl702l") { import("//build_overrides/bouffalolab_iot_sdk.gni") +} else if (chip_device_platform == "bl616") { + import("//build_overrides/bouffalolab_iot_sdk.gni") } buildconfig_header("system_buildconfig") { @@ -197,6 +199,10 @@ source_set("system_config_header") { if (chip_device_platform == "bl702l") { public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702l:bl_iot_sdk" ] } + if (chip_device_platform == "bl616") { + public_deps += + [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + } # Add platform here as needed. } diff --git a/third_party/bouffalolab/bl616/BUILD.gn b/third_party/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..15335a44f9354a --- /dev/null +++ b/third_party/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + +declare_args() { + # Build target to use for Bouffalo Lab SDK. Use this to set global SDK defines. + bouffalo_sdk_target = "" +} + +assert(bouffalo_sdk_target != "", "bl_iot_sdk_target must be specified") + +group("bouffalo_sdk") { + public_deps = [ bouffalo_sdk_target ] +} diff --git a/third_party/bouffalolab/bl616/bouffalo_sdk.gni b/third_party/bouffalolab/bl616/bouffalo_sdk.gni new file mode 100644 index 00000000000000..174b04b8160ae2 --- /dev/null +++ b/third_party/bouffalolab/bl616/bouffalo_sdk.gni @@ -0,0 +1,1272 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//args.gni") +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/mbedtls.gni") +import("${chip_root}/src/lib/lib.gni") + +declare_args() { + # Location of the bl616 SDK. + bouffalo_sdk_root = "${chip_root}/third_party/bouffalolab/bouffalo_sdk" + + enable_debug_coredump = false + coredump_binary_id = 0 + bouffalo_sdk_coredump_version = 1 +} + +assert(bouffalo_sdk_root != "", "bouffalo_sdk_root must be specified") + +# Defines an bl616 SDK build target. +# +# Parameters: +# bouffalo_sdk_root - The location of the bl616 SDK. +# sources - The sources files to build. +template("bouffalo_sdk") { + if (defined(invoker.bouffalo_sdk_root)) { + bouffalo_sdk_root = invoker.bouffalo_sdk_root + } + + assert(bouffalo_sdk_root != "", "bouffalo_sdk_root must be specified") + + sdk_target_name = target_name + + config("${sdk_target_name}_config") { + defines = [ + "BL616=BL616", + "ARCH_RISCV", + ] + + include_dirs = [] + if (defined(invoker.include_dirs)) { + include_dirs += invoker.include_dirs + } + + if (defined(invoker.defines)) { + defines += invoker.defines + } + + cflags_c = [ + "-fno-jump-tables", + "-fstrict-volatile-bitfields", + "-fshort-enums", + "-Wno-unused-but-set-variable", + ] + + cflags = [ + "-Wno-conversion", + "-fstack-usage", + ] + + if (defined(invoker.defines)) { + defines += invoker.defines + } + } + + config("${sdk_target_name}_config_startup") { + include_dirs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup" ] + } + + source_set("${sdk_target_name}_startup") { + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + "CONFIG_IRQ_NUM=80", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "CONFIG_COREDUMP" ] + } + + include_dirs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup" ] + + sources = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/interrupt.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/riscv_fpu.S", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/start.S", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/start_load.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/system_bl616.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/vector.S", + ] + + configs += [ + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_startup", + ] + } + + config("${sdk_target_name}_config_std_drv") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include/hardware", + ] + + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + ] + + cflags = [ "-Wsign-compare" ] + } + + source_set("${sdk_target_name}_std_drv") { + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + "BFLB_USE_ROM_DRIVER", + ] + + include_dirs = [ + #bl616 startup + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include/hardware", + ] + + sources = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/port/bl616_clock.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/port/bl616_gpio.c", + ] + + sources += [ + #use rom api default + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_clock.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_common.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_ef_cfg.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_efuse.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_flash.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_media.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_pm.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_psram.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_romapi_e907.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_romapi_patch.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_sdh.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_tzc_sec.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-enum-conversion", + "-Wno-type-limits", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config", + ] + } + + config("${sdk_target_name}_config_lhal") { + include_dirs = [ + #bl616 lhal + "${bouffalo_sdk_root}/drivers/lhal/include", + "${bouffalo_sdk_root}/drivers/lhal/include/arch", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/Core/Include", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/csi_dsp/include", + "${bouffalo_sdk_root}/drivers/lhal/src/flash", + "${bouffalo_sdk_root}/drivers/lhal/config/bl616", + ] + } + + source_set("${sdk_target_name}_lhal") { + defines = [ + "CPU_M0", + "CONFIG_IRQ_NUM=80", + ] + + include_dirs = [ + #bl616 lhal + "${bouffalo_sdk_root}/drivers/lhal/include", + ] + + sources = [ + "${bouffalo_sdk_root}/drivers/lhal/config/bl616/device_table.c", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/rv_hart.c", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/rv_pmp.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_acomp.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_adc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_auadc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_audac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_cam.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_cks.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_common.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dbi.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dma.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_ef_ctrl.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_emac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_flash.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_gpio.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_i2c.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_i2s.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_ir.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_irq.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_l1c.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_mjpeg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_mtimer.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_pwm_v2.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_rtc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sdio2.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_aes.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_sha.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_trng.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_spi.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_timer.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_uart.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_wdg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sf_cfg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sf_ctrl.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sflash.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_xip_sflash.c", + ] + + libs = [ "${bouffalo_sdk_root}/drivers/lhal/src/pka/libpka.a" ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + "-Wno-implicit-fallthrough", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-function", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lhal", + ] + } + + config("${sdk_target_name}_config_sys") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/sys", + "${bouffalo_sdk_root}/drivers/sys/bl616", + ] + } + + source_set("${sdk_target_name}_sys") { + defines = [ "BL_WIFI_LP_FW" ] + sources = [ + "${bouffalo_sdk_root}/drivers/sys/bl616/bl616_lp.c", + "${bouffalo_sdk_root}/drivers/sys/bl616/bl616_sys.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-shadow", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_sys", + ] + } + + config("${sdk_target_name}_config_board") { + include_dirs = [ "${bouffalo_sdk_root}/bsp/board" ] + } + + source_set("${sdk_target_name}_board") { + defines = [ + "CONFIG_MBEDTLS", + "CONFIG_BFLOG", + "BL616", + ] + + include_dirs = [ "${bouffalo_sdk_root}/bsp/board/bl616dk" ] + + sources = [ + "${bouffalo_sdk_root}/bsp/board/bl616dk/board.c", + "${bouffalo_sdk_root}/bsp/board/bl616dk/board_rf.c", + "${bouffalo_sdk_root}/bsp/board/bl616dk/fw_header.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-enum-conversion", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_rf", + ] + + public_configs = [ ":${sdk_target_name}_config_board" ] + } + + config("${sdk_target_name}_config_shell") { + include_dirs = [ "${bouffalo_sdk_root}/components/shell" ] + } + + source_set("${sdk_target_name}_shell") { + include_dirs = [ "${bouffalo_sdk_root}/bsp/board/bl616dk" ] + + sources = [ + "${bouffalo_sdk_root}/components/shell/shell.c", + "${bouffalo_sdk_root}/components/shell/shell_freertos.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-enum-conversion", + "-Wno-format-security", + "-Wno-format-truncation", + "-Wno-format-nonliteral", + "-Wno-sign-compare", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_board", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ] + public_configs = [ ":${sdk_target_name}_config_shell" ] + } + + config("${sdk_target_name}_config_rf") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/phyrf/include", + "${bouffalo_sdk_root}/drivers/rfparam/Inc", + ] + + defines = [ "WL_BL616=1" ] + } + + source_set("${sdk_target_name}_rf") { + defines = [ "RFPARAM_BL616" ] + + include_dirs = [ "${bouffalo_sdk_root}/drivers/rfparam/Inc" ] + + sources = [ + "${bouffalo_sdk_root}/drivers/rfparam/Src/rfparam_adapter.c", + "${bouffalo_sdk_root}/drivers/rfparam/Src/rfparam_rftlv.c", + ] + + libs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/phyrf/lib-gcc_10.2.0-toolchain_V2.6.1/libbl616_phyrf.a" ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_rf", + ] + } + + source_set("${sdk_target_name}_libc") { + include_dirs = [ "${bouffalo_sdk_root}/components/libc" ] + + sources = [ + "${bouffalo_sdk_root}/components/libc/newlib/port_init_fini.c", + "${bouffalo_sdk_root}/components/libc/newlib/port_memory.c", + "${bouffalo_sdk_root}/components/libc/newlib/syscalls_nosys.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_abs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atof.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atoi.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atol.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atoll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_bsearch.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_checkbase.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_itoa.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_llabs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_lldiv.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_qsort.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_strtod.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffsl.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffsll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_fls.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_flsl.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_flsll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_index.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memccpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memcmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memmove.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memrchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memset.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_stpcpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_stpncpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcasecmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcasestr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcat.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcspn.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strdup.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strnlen.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strpbrk.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strsep.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strspn.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strstr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtok.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtokr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_vikmemcpy.c", + "${bouffalo_sdk_root}/components/libc/printf.c", + "${bouffalo_sdk_root}/components/libc/snprintf.c", + "${bouffalo_sdk_root}/components/libc/sprintf.c", + "${bouffalo_sdk_root}/components/libc/stdatomic.c", + "${bouffalo_sdk_root}/components/libc/vsnprintf.c", + "${bouffalo_sdk_root}/components/libc/vsprintf.c", + ] + + cflags = [ + "-fno-builtin", + "-Wno-sign-compare", + "-Wno-implicit-fallthrough", + "-Wno-builtin-declaration-mismatch", + ] + configs += [ + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_lhal", + ] + public_configs = [ ":${sdk_target_name}_config" ] + } + + config("${sdk_target_name}_config_freertos") { + defines = [ + "CONFIG_FREERTOS", + "configSTACK_ALLOCATION_FROM_SEPARATE_HEAP=1", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/os/freertos/include", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/chip_specific_extensions/RV32I_CLINT_no_extensions", + + #"${bouffalo_sdk_root}/components/os/freertos/posix/include", + "${chip_root}/examples/platform/bouffalolab/bl616", + ] + } + + source_set("${sdk_target_name}_freertos") { + defines = [ + "portasmHANDLE_INTERRUPT=interrupt_entry", + "default_interrupt_handler=freertos_risc_v_trap_handler", + + #"CONFIG_POSIX", + ] + + include_dirs = [ + #memory heap + "${bouffalo_sdk_root}/components/os/freertos/include", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/chip_specific_extensions/RV32I_CLINT_no_extensions", + ] + + sources = [ + "${bouffalo_sdk_root}/components/os/freertos/croutine.c", + "${bouffalo_sdk_root}/components/os/freertos/event_groups.c", + "${bouffalo_sdk_root}/components/os/freertos/freertos_port.c", + "${bouffalo_sdk_root}/components/os/freertos/list.c", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/port.c", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/portASM.S", + "${bouffalo_sdk_root}/components/os/freertos/portable/MemMang/heap_3.c", + "${bouffalo_sdk_root}/components/os/freertos/queue.c", + "${bouffalo_sdk_root}/components/os/freertos/tasks.c", + "${bouffalo_sdk_root}/components/os/freertos/timers.c", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_freertos", + ] + } + + config("${sdk_target_name}_config_mm") { + include_dirs = [ + "${bouffalo_sdk_root}/components/mm", + "${bouffalo_sdk_root}/components/mm/tlsf", + ] + } + + source_set("${sdk_target_name}_mm") { + defines = [ + "configSTACK_ALLOCATION_FROM_SEPARATE_HEAP=1", + "CONFIG_TLSF", + ] + + include_dirs = [ + #memory heap + "${bouffalo_sdk_root}/components/mm", + "${bouffalo_sdk_root}/components/mm/tlsf", + ] + + sources = [ + "${bouffalo_sdk_root}/components/mm/mem.c", + "${bouffalo_sdk_root}/components/mm/tlsf/bflb_tlsf.c", + "${bouffalo_sdk_root}/components/mm/tlsf/tlsf.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_mm", + ] + } + + config("${sdk_target_name}_config_easyflash4") { + include_dirs = [ "${bouffalo_sdk_root}/components/easyflash4/inc" ] + } + + source_set("${sdk_target_name}_easyflash4") { + defines = [ + "CONFIG_EASYFLASH4", + "BL616", + "EF_ENV_CACHE_TABLE_SIZE=100", + ] + + include_dirs = [ "${bouffalo_sdk_root}/components/easyflash4/inc" ] + + sources = [ + "${bouffalo_sdk_root}/components/easyflash4/src/easyflash.c", + "${bouffalo_sdk_root}/components/easyflash4/src/easyflash_cli.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env_legacy.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env_legacy_wl.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_port.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_utils.c", + ] + + cflags_c = [ "-Wno-sign-compare" ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ ":${sdk_target_name}_config_easyflash4" ] + } + + config("${sdk_target_name}_config_littlefs") { + include_dirs = [ + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs", + "${bouffalo_sdk_root}/components/fs/littlefs/port", + ] + + defines = [ "LFS_THREADSAFE" ] + } + + source_set("${sdk_target_name}_littlefs") { + defines = [ + "CONFIG_LITTLEFS", + "CONFIG_FREERTOS", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs", + "${bouffalo_sdk_root}/components/fs/littlefs/port", + ] + + sources = [ + "${bouffalo_sdk_root}/components/fs/littlefs/easyflash_port/lfs_easyflash.c", + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs/lfs.c", + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs/lfs_util.c", + "${bouffalo_sdk_root}/components/fs/littlefs/port/lfs_xip_flash.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-shadow", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_littlefs", + ] + } + + config("${sdk_target_name}_config_utils") { + include_dirs = [ + "${bouffalo_sdk_root}/components/utils/log", + "${bouffalo_sdk_root}/components/utils/log/bflog", + "${bouffalo_sdk_root}/components/utils/bflb_mtd/include", + "${bouffalo_sdk_root}/components/utils/bflb_ota", + "${bouffalo_sdk_root}/components/utils/coredump", + "${bouffalo_sdk_root}/components/utils/partition", + "${bouffalo_sdk_root}/components/utils/getopt", + "${bouffalo_sdk_root}/components/utils/ring_buffer", + "${bouffalo_sdk_root}/components/utils/math/include", + "${bouffalo_sdk_root}/components/utils/list", + ] + + defines = [ + "CONFIG_LOG_LEVEL=0", + "CONFIG_BFLOG", + "CONFIG_BFLOG_DEBUG", + ] + } + + source_set("${sdk_target_name}_utils") { + defines = [ + "CONFIG_LOG_LEVEL=0", + "CONFIG_BFLOG", + "CONFIG_BFLOG_DEBUG", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "CONFIG_COREDUMP" ] + } + + sources = [ + "${bouffalo_sdk_root}/components/utils/bflb_mtd/bflb_boot2.c", + "${bouffalo_sdk_root}/components/utils/bflb_mtd/bflb_mtd.c", + "${bouffalo_sdk_root}/components/utils/bflb_ota/bflb_ota.c", + "${bouffalo_sdk_root}/components/utils/bflb_ota/utils_sha256.c", + "${bouffalo_sdk_root}/components/utils/getopt/utils_getopt.c", + "${bouffalo_sdk_root}/components/utils/log/bflog/bflog.c", + "${bouffalo_sdk_root}/components/utils/log/log.c", + "${bouffalo_sdk_root}/components/utils/log/log_freertos.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_base64.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_crc.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_hex.c", + "${bouffalo_sdk_root}/components/utils/partition/partition.c", + "${bouffalo_sdk_root}/components/utils/ring_buffer/ring_buffer.c", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + if (bouffalo_sdk_coredump_version == 1) { + sources += [ + "${bouffalo_sdk_root}/components/utils/coredump/bin_fmt_v1.c", + "${bouffalo_sdk_root}/components/utils/coredump/coredump.c", + "${bouffalo_sdk_root}/components/utils/coredump/encoder_v1.c", + ] + } else if (bouffalo_sdk_coredump_version == 2) { + sources += [ + "${bouffalo_sdk_root}/components/utils/coredump/bin_fmt_v2.c", + "${bouffalo_sdk_root}/components/utils/coredump/coredump.c", + "${bouffalo_sdk_root}/components/utils/coredump/encoder_v2.c", + ] + } + } + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-type-limits", + "-Wno-stringop-truncation", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-implicit-function-declaration", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ] + } + + config("${sdk_target_name}_config_mbedtls") { + include_dirs = [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/include", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port", + ] + + defines = [ "MBEDTLS_CONFIG_FILE=\"bl616-chip-mbedtls-config.h\"" ] + } + + source_set("${sdk_target_name}_mbedtls") { + defines = [ "CONFIG_FREERTOS" ] + + include_dirs = + [ "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library" ] + + sources = [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/aes_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/bignum_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/bignum_ext.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/ecp_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/ecp_curves_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha1_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha256_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha512_alt.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/bignum.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/entropy_poll_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/net_sockets.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/sec_mutex.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/poly1305.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/ripemd160.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/rsa.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/rsa_internal.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aes.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aesni.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/arc4.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aria.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/asn1parse.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/asn1write.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/base64.c", + + # "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/bignum.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/blowfish.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/camellia.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ccm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/certs.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/chacha20.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/chachapoly.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cipher.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cipher_wrap.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cmac.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/constant_time.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ctr_drbg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/debug.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/des.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/dhm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecdh.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecdsa.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecjpake.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecp.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecp_curves.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/entropy.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/entropy_poll.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/error.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/gcm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/havege.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/hkdf.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/hmac_drbg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md2.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md4.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md5.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/memory_buffer_alloc.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/mps_reader.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/mps_trace.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/nist_kw.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/oid.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/padlock.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pem.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pk.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pk_wrap.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs11.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs12.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs5.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkparse.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkwrite.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/platform.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/platform_util.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha1.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha256.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha512.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cache.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_ciphersuites.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cli.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cookie.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_msg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_srv.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_ticket.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_tls.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_tls13_keys.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/threading.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/timing.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/version.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/version_features.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_create.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_crl.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_crt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_csr.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509write_crt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509write_csr.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/xtea.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-security", + "-Wno-format-nonliteral", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_lwip", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_mbedtls", + ] + } + + config("${sdk_target_name}_config_lwip") { + include_dirs = [ + "${bouffalolab_iot_sdk_build_root}/bl616", + "${bouffalo_sdk_root}/components/net/lwip/lwip/system", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/include", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/compat/posix", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/include/compat/posix", + "${bouffalo_sdk_root}/components/net/lwip/lwip/lwip-port", + ] + + include_dirs += + [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd" ] + + defines = [ + "CONFIG_LWIP", + "CONFIG_MAC_TXQ_DEPTH=8", + "CONFIG_MAC_RXQ_DEPTH=8", + ] + } + + source_set("${sdk_target_name}_lwip") { + sources = [ + "${bouffalo_sdk_root}/components/net/lwip/lwip/lwip-port/FreeRTOS/sys_arch.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/api_lib.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/api_msg.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/err.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netbuf.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netdb.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netifapi.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/sockets.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/tcpip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/http/fs.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/mdns/mdns.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/def.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/dns.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/inet_chksum.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/init.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/autoip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/dhcp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/etharp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/icmp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/igmp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4_addr.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4_frag.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/dhcp6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ethip6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/icmp6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/inet6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_addr.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_frag.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/mld6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/nd6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/memp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/netif.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/pbuf.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/raw.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/stats.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/sys.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp_in.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp_out.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/timeouts.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/udp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/netif/ethernet.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd/dhcp_server_raw.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/lwiperf/lwiperf.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-variable", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_wifi", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lwip", + ] + } + + config("${sdk_target_name}_config_wifi") { + defines = [ + "CFG_VIF_MAX=2", + "CFG_STA_MAX=4", + "CFG_UMAC", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/wifi6/include", + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/include", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/include", + ] + } + + source_set("${sdk_target_name}_wifi") { + defines = [ "CFG_IPV6" ] + libs = [ "${bouffalo_sdk_root}/components/wireless/wifi6/lib/libwifi6.a" ] + + include_dirs = + [ "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter" ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/src/platform_bouffalo_sdk.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/src/rtos_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/cli_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/mat.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/net_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/net_al_ext.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/pbuf_custom_ref.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/tx_buffer_copy.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/wifi_pkt_hooks.c", + ] + + cflags_c = [ + "-Wno-error", + "-Wno-sign-compare", + "-Wno-int-conversion", + "-Wno-shadow", + "-Wno-incompatible-pointer-types", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-discarded-qualifiers", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_shell", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_lwip", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_wifi", + ] + } + + config("${sdk_target_name}_config_ble") { + defines = [ + "BFLB_BLE", + "CONFIG_BT_CONN=1", + + "CONFIG_SET_TX_PWR", + "CFG_CON=1", + "CFG_BLE", + "CFG_SLEEP", + "CFG_BT_RESET", + "CONFIG_BT_PERIPHERAL=1", + "CFG_BLE_TX_BUFF_DATA=2", + "CONFIG_BT_GATT_DYNAMIC_DB", + "CONFIG_BT_GATT_SERVICE_CHANGED", + "CONFIG_BT_SETTINGS_CCC_LAZY_LOADING", + "CONFIG_BT_KEYS_OVERWRITE_OLDEST", + "CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS", + "CONFIG_BT_BONDABLE", + "CONFIG_BT_ASSERT", + "CFG_BLE_STACK_DBG_PRINT", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/btblecontroller/btble_inc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include/bluetooth", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/port/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/zephyr", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/misc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include/drivers/bluetooth", + ] + } + + source_set("${sdk_target_name}_ble") { + defines = [ + "CONFIG_BT_L2CAP_DYNAMIC_CHANNEL", + "CONFIG_BT_GATT_CLIENT", + "CONFIG_BT_CONN=1", + "CONFIG_BT_GATT_DIS_PNP", + "CONFIG_BT_GATT_DIS_SERIAL_NUMBER", + "CONFIG_BT_GATT_DIS_FW_REV", + "CONFIG_BT_GATT_DIS_HW_REV", + "CONFIG_BT_GATT_DIS_SW_REV", + "CONFIG_BT_ECC", + "CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING", + "CONFIG_BT_HCI_VS_EVT_USER", + "CONFIG_BT_SETTINGS_USE_PRINTK", + "CONFIG_BLE_MULTI_ADV", + ] + + libs = [ "${bouffalo_sdk_root}/components/wireless/bluetooth/btblecontroller/lib/libbtblecontroller_bl616_ble1m0s1bredr0.a" ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/bl_hci_wrapper", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/misc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/tinycrypt/include/tinycrypt", + ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/atomic_c.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/buf.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/dec.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/log.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/poll.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/work_q.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/hci_onchip/hci_driver.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/att.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/bl_host_assist.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/conn.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/crypto.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/gatt.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/hci_core.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/l2cap.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/multi_adv.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/settings.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/uuid.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/port/bl_port.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-discarded-qualifiers", + "-Wno-misleading-indentation", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_ble", + ] + } + + config("${sdk_target_name}_config_openthread_port") { + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/include", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_utils/include", + ] + } + + source_set("${sdk_target_name}_openthread_port") { + import("//build_overrides/openthread.gni") + + defines = [ + "CONFIG_BL_SDK", + "CHIP_HDR=", + "CHIP_GLB_HDR=", + "MAC_ADDRESS_MAX_NUM=3", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/lmac154/lmac154/include", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port", + ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_alarm_bl616.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_radio.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_radio_bflb.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_sys_bflb.c", + ] + + if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && + invoker.bouffalo_sdk_component_easyflash_enabled) { + sources += [ "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_settings_easyflash.c" ] + } else { + sources += [ "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_settings_littlefs.c" ] + } + + libs = [ + "${bouffalo_sdk_root}/components/wireless/lmac154/lmac154/lib/liblmac154.a", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_utils/lib/libopenthread_utils.a", + ] + + cflags_c = [ "-Wno-sign-compare" ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_shell", + ":${sdk_target_name}_config_littlefs", + ":${sdk_target_name}_config_openthread_port", + ] + + public_deps = [ + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + "${openthread_root}/src/core:libopenthread_core_headers", + ] + } + + config("${sdk_target_name}_config_factory_data") { + include_dirs = + [ "${bouffalo_sdk_root}/components/wireless/matter/mfd/include" ] + } + + source_set("${sdk_target_name}_factory_data") { + defines = [ "BL_MFD_PLAT_H=\"bl_mfd_bl616.h\"" ] + sources = [ + "${bouffalo_sdk_root}/components/wireless/matter/mfd/bl_mfd.c", + "${bouffalo_sdk_root}/components/wireless/matter/mfd/bl_mfd_decrypt_bl616.c", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ ":${sdk_target_name}_config_factory_data" ] + } + + group(sdk_target_name) { + public_deps = [ + ":${sdk_target_name}_board", + ":${sdk_target_name}_freertos", + ":${sdk_target_name}_lhal", + ":${sdk_target_name}_libc", + ":${sdk_target_name}_mbedtls", + ":${sdk_target_name}_mm", + ":${sdk_target_name}_rf", + ":${sdk_target_name}_shell", + ":${sdk_target_name}_startup", + ":${sdk_target_name}_std_drv", + ":${sdk_target_name}_sys", + ":${sdk_target_name}_utils", + ] + + if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && + invoker.bouffalo_sdk_component_easyflash_enabled) { + public_deps += [ ":${sdk_target_name}_easyflash4" ] + } else { + public_deps += [ ":${sdk_target_name}_littlefs" ] + } + + if (defined(invoker.chip_enable_wifi) && invoker.chip_enable_wifi) { + public_deps += [ ":${sdk_target_name}_wifi" ] + public_deps += [ ":${sdk_target_name}_lwip" ] + } else if (defined(invoker.chip_enable_openthread) && + invoker.chip_enable_openthread) { + public_deps += [ ":${sdk_target_name}_openthread_port" ] + } + + if (defined(invoker.chip_config_network_layer_ble) && + invoker.chip_config_network_layer_ble) { + public_deps += [ ":${sdk_target_name}_ble" ] + } + + if (defined(invoker.chip_enable_factory_data) && + invoker.chip_enable_factory_data) { + public_deps += [ ":${sdk_target_name}_factory_data" ] + } + } +} diff --git a/third_party/bouffalolab/common/bouffalolab_executable.gni b/third_party/bouffalolab/common/bouffalolab_executable.gni index 105a8dc2fe48e4..491cb49cdf50ed 100644 --- a/third_party/bouffalolab/common/bouffalolab_executable.gni +++ b/third_party/bouffalolab/common/bouffalolab_executable.gni @@ -21,12 +21,15 @@ import("${build_root}/toolchain/flashable_executable.gni") template("bouffalolab_executable") { output_base_name = get_path_info(invoker.output_name, "name") - objcopy_image_name = output_base_name + ".bin" objcopy_image_format = "binary" objcopy = "riscv64-unknown-elf-objcopy" if ("linux" == host_os) { - objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-objcopy" + if (invoker.bl_plat_name == "bl616") { + objcopy = "${bouffalolab_sdk_root}/toolchain/t-head-riscv/gcc_t-head_v2.6.1/bin/riscv64-unknown-elf-objcopy" + } else { + objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-objcopy" + } } else if ("mac" == host_os || "darwin" == host_os) { objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Darwin/bin/riscv64-unknown-elf-objcopy" } @@ -46,17 +49,30 @@ template("bouffalolab_executable") { } flashing_config_target = target_name + ".config" + if (invoker.bl_plat_name == "bl616") { + objcopy_image_name = output_base_name + ".raw" + flashing_config_inputs = [ + "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml", + "${chip_root}/third_party/bouffalolab/bouffalo_sdk/bsp/board/bl616dk/config/bl_factory_params_IoTKitA_auto.dts", + "${chip_root}/third_party/bouffalolab/bouffalo_sdk/bsp/board/bl616dk/config/boot2_bl616_isp_release_v8.1.6.bin", + ] - objcopy_image_name = output_base_name + ".bin" - if (invoker.bl_plat_name == "bl602") { - flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml" ] + copy(flashing_config_target) { + sources = flashing_config_inputs + outputs = [ "${root_out_dir}/config/{{source_file_part}}" ] + } } else { - flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_2M.toml" ] - } + objcopy_image_name = output_base_name + ".bin" + if (invoker.bl_plat_name == "bl602") { + flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml" ] + } else { + flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_2M.toml" ] + } - copy(flashing_config_target) { - sources = flashing_config_inputs - outputs = [ "${root_out_dir}/{{source_file_part}}" ] + copy(flashing_config_target) { + sources = flashing_config_inputs + outputs = [ "${root_out_dir}/{{source_file_part}}" ] + } } flashing_script_generator = @@ -66,27 +82,34 @@ template("bouffalolab_executable") { flashing_options += [ "--chipname" ] flashing_options += [ "${invoker.bl_plat_name}" ] - flashing_options += [ "--xtal" ] - if (invoker.bl_plat_name == "bl602") { - flashing_options += [ "40M" ] - } else if (invoker.bl_plat_name == "bl702") { - flashing_options += [ "32M" ] - } else if (invoker.bl_plat_name == "bl702l") { - flashing_options += [ "32M" ] - } - - flashing_options += [ "--pt" ] - if (invoker.bl_plat_name == "bl602") { - flashing_options += - [ rebase_path("partition_cfg_4M.toml", root_out_dir, root_out_dir) ] - } else if (defined(invoker.enable_openthread_border_router) && - invoker.enable_openthread_border_router) { - flashing_options += [ rebase_path("partition_cfg_2M_noOTA.toml", - root_out_dir, - root_out_dir) ] + if (invoker.bl_plat_name == "bl616") { + flashing_options += [ + "--config", + "${root_out_dir}/flash_prog_cfg.ini", + ] } else { - flashing_options += - [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] + flashing_options += [ "--xtal" ] + if (invoker.bl_plat_name == "bl602") { + flashing_options += [ "40M" ] + } else if (invoker.bl_plat_name == "bl702") { + flashing_options += [ "32M" ] + } else if (invoker.bl_plat_name == "bl702l") { + flashing_options += [ "32M" ] + } + + flashing_options += [ "--pt" ] + if (invoker.bl_plat_name == "bl602") { + flashing_options += + [ rebase_path("partition_cfg_4M.toml", root_out_dir, root_out_dir) ] + } else if (defined(invoker.enable_openthread_border_router) && + invoker.enable_openthread_border_router) { + flashing_options += [ rebase_path("partition_cfg_2M_noOTA.toml", + root_out_dir, + root_out_dir) ] + } else { + flashing_options += + [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] + } } # set 2000000 baudrate for image download by default diff --git a/third_party/bouffalolab/common/rsicv.gni b/third_party/bouffalolab/common/rsicv.gni index fea2acd4d10100..25b5c78bc99f1e 100644 --- a/third_party/bouffalolab/common/rsicv.gni +++ b/third_party/bouffalolab/common/rsicv.gni @@ -17,5 +17,10 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/platform/device.gni") -riscv_arch = "rv32imfc" +if (chip_device_platform == "bl616") { + riscv_arch = "rv32imafcpzpsfoperand_xtheade" +} else { + riscv_arch = "rv32imfc" +} + riscv_abi = "ilp32f" From 2a76d678a993ac73a75b4837edaede4b9d7c5e17 Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Wed, 15 Jan 2025 00:32:25 +0800 Subject: [PATCH 4/7] =?UTF-8?q?[bouffalo=20lab]=20add=20bl704l=20thread=20?= =?UTF-8?q?sed,=20low=20power,=20support=20on=20contact=20s=E2=80=A6=20(#3?= =?UTF-8?q?6953)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [bouffalo lab] add bl704l thread sed, low power, support on contact sensor example * update zap file --- .github/workflows/examples-bouffalolab.yaml | 18 + .../contact-sensor-app/bouffalolab/bl702l/.gn | 28 + .../bouffalolab/bl702l/BUILD.gn | 262 + .../bouffalolab/bl702l/CHIPProjectConfig.h | 118 + .../bouffalolab/bl702l/FreeRTOSConfig.h | 193 + .../bouffalolab/bl702l/app_pds.cpp | 170 + .../bouffalolab/bl702l/args.gni | 29 + .../bouffalolab/bl702l/build_overrides | 1 + .../bouffalolab/bl702l/mboard.h | 43 + .../bl702l/third_party/connectedhomeip | 1 + .../bouffalolab/bl702l/with_pw_rpc.gni | 25 + .../bouffalolab/common/AppTask.cpp | 236 + .../bouffalolab/common/AppTask.h | 130 + .../bouffalolab/common/ZclCallbacks.cpp | 45 + .../data_model/contact-sensor-app.matter | 2301 +++++++++ .../data_model/contact-sensor-app.zap | 4518 +++++++++++++++++ .../lighting-app/bouffalolab/bl602/BUILD.gn | 2 +- .../bouffalolab/bl602/FreeRTOSConfig.h | 222 + .../lighting-app/bouffalolab/bl602/args.gni | 3 +- .../lighting-app/bouffalolab/bl702/BUILD.gn | 4 +- .../bouffalolab/bl702/FreeRTOSConfig.h | 194 + .../lighting-app/bouffalolab/bl702l/BUILD.gn | 8 +- .../bouffalolab/bl702l/FreeRTOSConfig.h | 182 + .../lighting-app/bouffalolab/bl702l/args.gni | 2 + .../lighting-app/bouffalolab/bl702l/mboard.h | 5 + .../bouffalolab/bl602/ldscripts/flash_rom.ld | 109 +- .../bl702/ldscripts/psram_flash.ld | 120 +- .../bl702l/ldscripts/psram_flash.ld | 318 ++ .../common/iot_sdk/platform_port.cpp | 63 +- .../platform/bouffalolab/common/plat/plat.h | 5 +- .../bouffalolab/common/plat/platform.cpp | 7 +- scripts/build/build/targets.py | 1 + scripts/build/builders/bouffalolab.py | 8 +- .../build/testdata/all_targets_linux_x64.txt | 2 +- third_party/bouffalolab/bl602/bl_iot_sdk.gni | 53 +- third_party/bouffalolab/bl702/bl_iot_sdk.gni | 52 +- third_party/bouffalolab/bl702l/bl_iot_sdk.gni | 95 +- third_party/bouffalolab/repo | 2 +- 38 files changed, 9385 insertions(+), 190 deletions(-) create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/.gn create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/BUILD.gn create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/CHIPProjectConfig.h create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/FreeRTOSConfig.h create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/args.gni create mode 120000 examples/contact-sensor-app/bouffalolab/bl702l/build_overrides create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/mboard.h create mode 120000 examples/contact-sensor-app/bouffalolab/bl702l/third_party/connectedhomeip create mode 100644 examples/contact-sensor-app/bouffalolab/bl702l/with_pw_rpc.gni create mode 100644 examples/contact-sensor-app/bouffalolab/common/AppTask.cpp create mode 100644 examples/contact-sensor-app/bouffalolab/common/AppTask.h create mode 100644 examples/contact-sensor-app/bouffalolab/common/ZclCallbacks.cpp create mode 100644 examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter create mode 100644 examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap create mode 100644 examples/lighting-app/bouffalolab/bl602/FreeRTOSConfig.h create mode 100644 examples/lighting-app/bouffalolab/bl702/FreeRTOSConfig.h create mode 100644 examples/lighting-app/bouffalolab/bl702l/FreeRTOSConfig.h create mode 100644 examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 9a6989881e5e0c..5af3b4cc90d9ab 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -141,6 +141,24 @@ jobs: - name: Clean out build output run: rm -rf ./out + - name: Build example BL702L Contact Sensor + timeout-minutes: 30 + run: | + ./scripts/run_in_build_env.sh \ + "./scripts/build/build_examples.py \ + --target bouffalolab-bl704ldk-contact-sensor-thread-mtd-littlefs-mfd \ + build \ + --copy-artifacts-to out/artifacts \ + " + - name: Prepare some bloat report from the previous builds + run: | + .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ + bl702l bl702l+mfd+littlefs contact-sensor-app \ + out/artifacts/bouffalolab-bl704ldk-contact-sensor-thread-mtd-littlefs-mfd/chip-bl702l-contact-sensor-example.out \ + /tmp/bloat_reports/ + - name: Clean out build output + run: rm -rf ./out + - name: Uploading Size Reports uses: ./.github/actions/upload-size-reports if: ${{ !env.ACT }} diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/.gn b/examples/contact-sensor-app/bouffalolab/bl702l/.gn new file mode 100644 index 00000000000000..b4b90985dae681 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "riscv" + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/BUILD.gn b/examples/contact-sensor-app/bouffalolab/bl702l/BUILD.gn new file mode 100644 index 00000000000000..7a9a5c7abd8761 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/BUILD.gn @@ -0,0 +1,262 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +import("${bouffalolab_iot_sdk_build_root}/bl702l/bl_iot_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/common/bouffalolab_executable.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") +import("${chip_root}/src/platform/device.gni") + +import("${chip_root}/src/app/chip_data_model.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") +} + +assert(current_os == "freertos") + +example_dir = "${chip_root}/examples/contact-sensor-app/bouffalolab" +examples_plat_dir = "${chip_root}/examples/platform/bouffalolab" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = true + + # OTA periodic query timeout in seconds + ota_periodic_query_timeout_seconds = 86400 + + # reboot delay in seconds to apply new OTA image + ota_auto_reboot_delay_seconds = 5 + + enable_heap_monitoring = false + + setupPinCode = 20202021 + setupDiscriminator = 3840 + + board = "BL704L-EVB" + module_type = "BL704L" + baudrate = 2000000 + + enable_psram = true +} + +bl_iot_sdk("sdk") { + include_dirs = [ + "${example_dir}/bl702l", + "${example_dir}/bl702l/include", + "${examples_plat_dir}", + "${chip_root}/src/platform/bouffalolab/BL702L", + "${chip_root}/src/platform/bouffalolab/common", + ] + + freertos_config = "${example_dir}/bl702l/FreeRTOSConfig.h" + + defines = [ + "INCLUDE_xSemaphoreGetMutexHolder=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_seconds}", + "OTA_AUTO_REBOOT_DELAY=${ota_auto_reboot_delay_seconds}", + "PRINT_DEBUG=0", + ] + + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + include_dirs += [ "${examples_plat_dir}/common/rpc" ] + defines += [ "DISABLE_PRINT=1" ] + } else if (chip_build_libshell) { + include_dirs += [ "${examples_plat_dir}/common/plat" ] + } + + if (chip_enable_openthread) { + defines += [ "OPENTHREAD_CONFIG_PLATFORM_XTAL_ACCURACY=40" ] + } + + assert(enable_psram == true, "BL702L must have psram for this application") + defines += [ "CFG_USE_PSRAM=1" ] +} + +chip_data_model("bouffalolab_contact_sensor") { + zap_file = "${example_dir}/data_model/contact-sensor-app.zap" + is_server = true +} + +bouffalolab_executable("contact_sensor_app") { + output_name = "chip-bl702l-contact-sensor-example.out" + bl_plat_name = "bl702l" + + defines = [ + "APP_TASK_STACK_SIZE=2048", + "CHIP_UART_BAUDRATE=${baudrate}", + "START_ENTRY=bl702_main", + ] + + defines += + [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] + if (chip_config_network_layer_ble) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=1" ] + } + + if ("BL704LDK" == board) { + defines += [ "XT_ZB6_DevKit" ] + } + + include_dirs = [ + "${chip_root}/src/platform/bouffalolab/BL702L", + "${example_dir}/common", + "${example_dir}/bl702l", + "${examples_plat_dir}/common/plat", + "${examples_plat_dir}/common/iot_sdk", + ] + + sources = [ + "${example_dir}/bl702l/app_pds.cpp", + "${example_dir}/common/AppTask.cpp", + "${example_dir}/common/ZclCallbacks.cpp", + "${examples_plat_dir}/common/iot_sdk/aos_task.c", + "${examples_plat_dir}/common/iot_sdk/platform_port.cpp", + "${examples_plat_dir}/common/iot_sdk/uart.cpp", + "${examples_plat_dir}/common/plat/OTAConfig.cpp", + "${examples_plat_dir}/common/plat/main.cpp", + "${examples_plat_dir}/common/plat/platform.cpp", + ] + + deps = [ + ":bouffalolab_contact_sensor", + ":sdk", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/platform/logging:default", + "${chip_root}/src/setup_payload", + ] + + if (chip_enable_openthread) { + deps += [ + "${chip_root}/third_party/openthread/platforms:libopenthread-platform", + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + ] + + assert(chip_openthread_ftd == false, + "Only Thread MTD support on contact sensor application.") + defines += [ "CHIP_DEVICE_CONFIG_THREAD_FTD=0" ] + deps += [ "${openthread_root}:libopenthread-mtd" ] + if (chip_build_libshell) { + deps += [ "${openthread_root}:libopenthread-cli-mtd" ] + } + } + + defines += [ "CONFIG_ENABLE_CHIP_SHELL=${chip_build_libshell}" ] + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + defines += [ + "PW_RPC_ATTRIBUTE_SERVICE=1", + "PW_RPC_BUTTON_SERVICE=1", + "PW_RPC_DESCRIPTOR_SERVICE=1", + "PW_RPC_DEVICE_SERVICE=1", + "PW_RPC_LIGHTING_SERVICE=1", + + "PW_RPC_OTCLI_SERVICE=1", + "PW_RPC_THREAD_SERVICE=1", + + #"PW_RPC_TRACING_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/common/pigweed/RpcService.cpp", + "${chip_root}/examples/common/pigweed/bouffalolab/PigweedLoggerMutex.cpp", + "${examples_plat_dir}/common/rpc/PigweedLogger.cpp", + "${examples_plat_dir}/common/rpc/Rpc.cpp", + ] + + deps += [ + "$dir_pw_hdlc:default_addresses", + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_stream:sys_io_stream", + + #"$dir_pw_trace", + #"$dir_pw_trace_tokenized", + #"$dir_pw_trace_tokenized:trace_rpc_service", + "${chip_root}/config/bouffalolab/common/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:attributes_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:button_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:descriptor_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:device_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:lighting_service.nanopb_rpc", + "${examples_plat_dir}/common/rpc/pw_sys_io:pw_sys_io", + ] + + if (chip_enable_openthread) { + deps += [ + "${chip_root}/examples/common/pigweed:ot_cli_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:thread_service.nanopb_rpc", + ] + } + + deps += pw_build_LINK_DEPS + + include_dirs += [ + "${chip_root}/examples/common", + "${chip_root}/examples/common/pigweed/bouffalolab", + ] + } else { + if (chip_build_libshell) { + include_dirs += [ + "${chip_root}/src/lib/shell", + "${chip_root}/examples/shell/shell_common/include", + ] + + deps += [ "${chip_root}/examples/shell/shell_common:shell_common" ] + } + } + + defines += [ "HEAP_MONITORING=${enable_heap_monitoring}" ] + if (enable_heap_monitoring) { + sources += [ "${examples_plat_dir}/common/plat/MemMonitoring.cpp" ] + } + + assert(enable_psram == true, "BL702L must have psram for this application") + defines += [ "CFG_USE_PSRAM=1" ] + ldscript = "${examples_plat_dir}/bl702l/ldscripts/psram_flash.ld" + + inputs = [ ldscript ] + + ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + cflags_c = [ + "-Wno-unused-variable", + "-Wno-old-style-declaration", + ] + cflags = [ "-Wno-unused-variable" ] + if (chip_print_memory_usage) { + ldflags += [ + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("bl702l") { + deps = [ ":contact_sensor_app" ] +} + +group("default") { + deps = [ ":bl702l" ] +} diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/CHIPProjectConfig.h b/examples/contact-sensor-app/bouffalolab/bl702l/CHIPProjectConfig.h new file mode 100644 index 00000000000000..9cce9e85b9aafe --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/CHIPProjectConfig.h @@ -0,0 +1,118 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif + +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * + * 0x130D: Chip's Vendor Id. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * + * 0x8005: example lighting app + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8005 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION + * + * The product revision number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software revisions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "0.1ALPHA" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 0x0001 +#endif + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS + * + * Enable recording UTC timestamps. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_UTC_TIMESTAMPS 1 + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +#define CHIP_BLE_DEVICE_NAME "ContactSensor" + +// #define CHIP_DEVICE_CONFIG_ICD_SLOW_POLL_INTERVAL chip::System::Clock::Milliseconds32(1000) diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/FreeRTOSConfig.h b/examples/contact-sensor-app/bouffalolab/bl702l/FreeRTOSConfig.h new file mode 100644 index 00000000000000..5f0447acf49367 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/FreeRTOSConfig.h @@ -0,0 +1,193 @@ +/* + FreeRTOS V8.2.3 - Copyright (C) 2015 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#include "platform.h" + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configSUPPORT_STATIC_ALLOCATION 1 + +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 +#define configUSE_TICKLESS_IDLE 1 +#define configCPU_CLOCK_HZ (2000000) /*QEMU*/ +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +/* Creating idle task */ +/* -1 -> prvInitialiseNewTask: (subtract 1 to get top of stack) pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 + * ] ); */ +/* -1 -> prvInitialiseNewTask: (subtract 1 in case not matching 8 bytes alignment) pxTopOfStack = ( StackType_t * ) ( ( ( + * portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); */ +/* Running idle task */ +/* -12 -> prvIdleTask: addi sp, sp, -48 */ +/* -16 -> prvIdleTask.xTaskResumeAll: addi sp, sp, -64 */ +/* Here comes an interrupt after prvIdleTask.xTaskResumeAll.vTaskExitCritical */ +/* -30 -> freertos_risc_v_trap_handler: addi sp, sp, -portCONTEXT_SIZE */ +/* -34 -> portasmSAVE_ADDITIONAL_REGISTERS: addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) */ +/* Checking for stack overflow */ +/* 4 -> taskCHECK_FOR_STACK_OVERFLOW: if( ( pulStack[ 0 ] != ulCheckValue ) || ( pulStack[ 1 ] != ulCheckValue ) || ( pulStack[ 2 + * ] != ulCheckValue ) || ( pulStack[ 3 ] != ulCheckValue ) ) */ +#define configMINIMAL_STACK_SIZE ((unsigned short) 256) /* SIZE-1-1-12-16-30-34>=4 */ +#define configTOTAL_HEAP_SIZE ((size_t) 14100) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH (400) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_xTaskGetHandle 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +#ifdef __cplusplus +extern "C" void vAssertCalled(void); +#else +extern void vAssertCalled(void); +#endif + +#define configASSERT(x) \ + if ((x) == 0) \ + vAssertCalled() + +/* Overwrite some of the stack sizes allocated to various test and demo tasks. +Like all task stack sizes, the value is the number of words, not bytes. */ +#define bktBLOCK_TIME_TASK_STACK_SIZE 100 +#define notifyNOTIFIED_TASK_STACK_SIZE 120 +#define priSUSPENDED_RX_TASK_STACK_SIZE 90 +#define tmrTIMER_TEST_TASK_STACK_SIZE 100 +#define ebRENDESVOUS_TEST_TASK_STACK_SIZE 100 +#define ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE 115 +#define genqMUTEX_TEST_TASK_STACK_SIZE 90 +#define genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE 100 +#define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE 90 + +#if (configUSE_TICKLESS_IDLE != 0) +#include "portmacro.h" +#ifdef __cplusplus +extern "C" void vApplicationSleep(TickType_t xExpectedIdleTime); +#else +extern void vApplicationSleep(TickType_t xExpectedIdleTime); +#endif +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif + +#endif /* FREERTOS_CONFIG_H */ diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp b/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp new file mode 100644 index 00000000000000..e3ed09ae6393c1 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp @@ -0,0 +1,170 @@ + +#include + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +} + +#define PDS_TOLERANCE_TIME_32768CYCLE (164) +#define PDS_MIN_TIME_32768CYCLE (PDS_WARMUP_LATENCY_CNT + 33) +#define PDS_SLEEP_MAX_MS 3600000 + +btble_app_conf_t app_pds_conf = { + .print_enable = 0, // 1: enable uart print in library; 0: disable uart print in library + .gpio_irq_restore = 1, // 1: restore gpio irq after pds wakeup; 0: do not restore gpio irq after pds wakeup + .gpio_num = 2, // 3, + .gpio_index = { CHIP_RESET_PIN, CHIP_CONTACT_PIN }, + .pull_type = { INPUT_PULL_DOWN, INPUT_PULL_DOWN }, + .trigger_type = { HOSAL_IRQ_TRIG_SYNC_FALLING_RISING_EDGE, HOSAL_IRQ_TRIG_SYNC_FALLING_RISING_EDGE }, +}; + +static uint32_t low_power_pds_lmac154_backup[72]; +static hosal_gpio_dev_t gpio_key = { .port = CHIP_RESET_PIN, .config = INPUT_PULL_DOWN, .priv = NULL }; +static hosal_gpio_dev_t gpio_contact = { .port = CHIP_CONTACT_PIN, .config = INPUT_PULL_DOWN, .priv = NULL }; +static hosal_gpio_irq_handler_t app_pds_irq_handler = NULL; +static int app_pds_wakeup_source = -1; +static uint32_t app_pds_wakeup_pin = -1; + +extern "C" void btble_pds_fastboot_done_callback(void); + +uint64_t wakeup_time = 0; +uint64_t sleep_calling_time = 0; +uint64_t sleep_time = 0; + +extern "C" void vApplicationSleep(TickType_t xExpectedIdleTime) +{ + uint64_t sleep_before = bl_rtc_get_timestamp_ms(); + + sleep_calling_time = bl_rtc_get_timestamp_ms(); + + btble_vApplicationSleepExt(xExpectedIdleTime); + + extern BaseType_t TrapNetCounter, *pTrapNetCounter; + if (app_pds_wakeup_source == PDS_WAKEUP_BY_RTC) + { + extern void * pxCurrentTCB; + + ChipLogProgress(NotSpecified, "wakeup source: rtc. %lu vs %lu ms @ %lu\r\n", xExpectedIdleTime, + (uint32_t) (bl_rtc_get_timestamp_ms() - sleep_before), (uint32_t) bl_rtc_get_timestamp_ms()); + + ChipLogProgress(NotSpecified, "application_sleep; %lu, %lu, %lu\r\n", (uint32_t) sleep_calling_time, (uint32_t) sleep_time, + (uint32_t) wakeup_time); + } + else if (app_pds_wakeup_source == PDS_WAKEUP_BY_GPIO) + { + + if (((1 << CHIP_RESET_PIN) & app_pds_wakeup_pin) && app_pds_irq_handler) + { + app_pds_irq_handler(&gpio_key); + } + + if (((1 << CHIP_CONTACT_PIN) & app_pds_wakeup_pin) && app_pds_irq_handler) + { + app_pds_irq_handler(&gpio_contact); + } + + ChipLogProgress(NotSpecified, "wakeup source: gpio -> 0x%08lX. %lu vs %lu ms @ %lu\r\n", app_pds_wakeup_pin, + xExpectedIdleTime, (uint32_t) (bl_rtc_get_timestamp_ms() - sleep_before), + (uint32_t) bl_rtc_get_timestamp_ms()); + } + + app_pds_wakeup_source = -1; + app_pds_wakeup_pin = -1; +} + +void app_pds_config_pin(void) +{ + uint8_t wakeup_pin[] = { gpio_key.port, gpio_contact.port }; + + hosal_gpio_init(&gpio_key); + hosal_gpio_init(&gpio_contact); + hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_SYNC_FALLING_RISING_EDGE, app_pds_irq_handler, &gpio_key); + hosal_gpio_irq_set(&gpio_contact, HOSAL_IRQ_TRIG_SYNC_FALLING_RISING_EDGE, app_pds_irq_handler, &gpio_contact); + + bl_pds_gpio_wakeup_cfg(wakeup_pin, sizeof(wakeup_pin) / sizeof(wakeup_pin[0]), PDS_GPIO_EDGE_BOTH); +} + +void app_pds_fastboot_done_callback(void) +{ + wakeup_time = bl_rtc_get_timestamp_ms(); + +#if CHIP_PROGRESS_LOGGING || CHIP_ERROR_LOGGING + extern hosal_uart_dev_t uart_stdio; + bl_uart_init(uart_stdio.config.uart_id, uart_stdio.config.tx_pin, uart_stdio.config.rx_pin, uart_stdio.config.cts_pin, + uart_stdio.config.rts_pin, uart_stdio.config.baud_rate); +#endif + + btble_pds_fastboot_done_callback(); + + bl_psram_init(); + + // app_pds_config_pin(); + + app_pds_wakeup_source = bl_pds_get_wakeup_source(); + app_pds_wakeup_pin = bl_pds_get_wakeup_gpio(); +} + +int app_pds_before_sleep_callback(void) +{ + if (otr_isStackIdle()) + { + + bl_pds_set_psram_retention(1); + lmac154_sleepStoreRegs(low_power_pds_lmac154_backup); + + sleep_time = bl_rtc_get_timestamp_ms(); + + return 0; + } + + return -1; +} + +void app_pds_after_sleep_callback(void) +{ + if (lmac154_isDisabled()) + { + + lmac154_sleepRestoreRegs(low_power_pds_lmac154_backup); + lmac154_disableRx(); + + zb_timer_cfg(bl_rtc_get_counter() * (32768 >> LMAC154_US_PER_SYMBOL_BITS)); + + zb_timer_restore_events(true); + + bl_irq_enable(M154_IRQn); + } + bl_sec_init(); +} + +void app_pds_init(hosal_gpio_irq_handler_t pinHandler) +{ + btble_pds_init(&app_pds_conf); + + btble_set_before_sleep_callback(app_pds_before_sleep_callback); + btble_set_after_sleep_callback(app_pds_after_sleep_callback); + + bl_pds_register_fastboot_done_callback(app_pds_fastboot_done_callback); + + app_pds_irq_handler = pinHandler; + app_pds_config_pin(); + + btble_pds_enable(1); +} diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/args.gni b/examples/contact-sensor-app/bouffalolab/bl702l/args.gni new file mode 100644 index 00000000000000..2b8c88f59bf1ed --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/args.gni @@ -0,0 +1,29 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/src/platform/bouffalolab/BL702L/args.gni") + +bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +chip_detail_logging = false +is_debug = false +chip_progress_logging = true +chip_error_logging = true + +chip_enable_icd_server = true +chip_enable_icd_lit = true +chip_enable_icd_dsls = true diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/build_overrides b/examples/contact-sensor-app/bouffalolab/bl702l/build_overrides new file mode 120000 index 00000000000000..995884e6163eb5 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/build_overrides @@ -0,0 +1 @@ +../../../build_overrides \ No newline at end of file diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/mboard.h b/examples/contact-sensor-app/bouffalolab/bl702l/mboard.h new file mode 100644 index 00000000000000..0c7568f3beadb3 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/mboard.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes dev borad compile-time configuration constants for BL702L. + * + */ + +#pragma once + +#define CHIP_UART_PORT 0 +#define CHIP_UART_RX_BUFFSIZE 256 +#define CHIP_UART_PIN_RX 15 +#define CHIP_UART_PIN_TX 14 + +#define CHIP_CONTACT_PIN 20 +#define CHIP_RESET_PIN 16 diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/third_party/connectedhomeip b/examples/contact-sensor-app/bouffalolab/bl702l/third_party/connectedhomeip new file mode 120000 index 00000000000000..59307833b4fee9 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../.. \ No newline at end of file diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/with_pw_rpc.gni b/examples/contact-sensor-app/bouffalolab/bl702l/with_pw_rpc.gni new file mode 100644 index 00000000000000..5d7ce27c99df3d --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/bl702l/with_pw_rpc.gni @@ -0,0 +1,25 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# add this gni as import in your build args to use pigweed in the example +# 'import("//with_pw_rpc.gni")' + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("${chip_root}/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni") +import("${chip_root}/examples/platform/bouffalolab/bl702l/args.gni") + +chip_enable_pw_rpc = true +chip_build_pw_trace_lib = false +#pw_trace_BACKEND = "$dir_pw_trace_tokenized" diff --git a/examples/contact-sensor-app/bouffalolab/common/AppTask.cpp b/examples/contact-sensor-app/bouffalolab/common/AppTask.cpp new file mode 100644 index 00000000000000..5990e4201e6d07 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/common/AppTask.cpp @@ -0,0 +1,236 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#if HEAP_MONITORING +#include "MemMonitoring.h" +#endif + +#if CHIP_ENABLE_OPENTHREAD +#include +#include +#include +#include +#endif + +#if CONFIG_ENABLE_CHIP_SHELL +#include +#include +#endif + +#include + +extern "C" { +#include +#include +#include +#include +} + +#include "AppTask.h" +#include "mboard.h" + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::Credentials; +using namespace ::chip::DeviceLayer; + +AppTask AppTask::sAppTask; +StackType_t AppTask::appStack[APP_TASK_STACK_SIZE / sizeof(StackType_t)]; +StaticTask_t AppTask::appTaskStruct; + +#if CONFIG_ENABLE_CHIP_SHELL +void AppTask::AppShellTask(void * args) +{ + Shell::Engine::Root().RunMainLoop(); +} + +CHIP_ERROR AppTask::StartAppShellTask() +{ + static TaskHandle_t shellTask; + + Shell::Engine::Root().Init(); + + cmd_misc_init(); + + xTaskCreate(AppTask::AppShellTask, "chip_shell", 1024 / sizeof(configSTACK_DEPTH_TYPE), NULL, APP_TASK_PRIORITY, &shellTask); + + return CHIP_NO_ERROR; +} +#endif + +void StartAppTask(void) +{ + GetAppTask().sAppTaskHandle = xTaskCreateStatic(GetAppTask().AppTaskMain, APP_TASK_NAME, ArraySize(GetAppTask().appStack), NULL, + APP_TASK_PRIORITY, GetAppTask().appStack, &GetAppTask().appTaskStruct); + if (GetAppTask().sAppTaskHandle == NULL) + { + ChipLogError(NotSpecified, "Failed to create app task"); + appError(APP_ERROR_EVENT_QUEUE_FAILED); + } +} + +void AppTask::PostEvent(app_event_t event) +{ + if (xPortIsInsideInterrupt()) + { + BaseType_t higherPrioTaskWoken = pdFALSE; + xTaskNotifyFromISR(sAppTaskHandle, event, eSetBits, &higherPrioTaskWoken); + } + else + { + xTaskNotify(sAppTaskHandle, event, eSetBits); + } +} + +void AppTask::ButtonEventHandler(void * arg) +{ + hosal_gpio_dev_t * p_gpio = (hosal_gpio_dev_t *) arg; + uint8_t val = 1; + + hosal_gpio_input_get(p_gpio, &val); + + if (CHIP_RESET_PIN == p_gpio->port) + { + if (val) + { + GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count(); + } + else + { + if (GetAppTask().mButtonPressedTime) + { + uint64_t pressed_time = + System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime; + + if (pressed_time > APP_BUTTON_PRESS_LONG) + { + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); + } + else if (APP_BUTTON_PRESS_JITTER < pressed_time && pressed_time < APP_BUTTON_PRESS_SHORT) + { + GetAppTask().PostEvent(APP_EVENT_BUTTON_PRESSED); + } + + GetAppTask().mButtonPressedTime = 0; + } + } + } + else if (CHIP_CONTACT_PIN == p_gpio->port) + { + if (val) + { + GetAppTask().PostEvent(APP_EVENT_CONTACT_SENSOR_TRUE); + } + else + { + GetAppTask().PostEvent(APP_EVENT_CONTACT_SENSOR_FALSE); + } + } +} + +void AppTask::AppTaskMain(void * pvParameter) +{ + app_event_t appEvent; + bool stateValueAttrValue = false; + uint64_t currentHeapFree = 0; + + app_pds_init(GetAppTask().ButtonEventHandler); + + ChipLogProgress(NotSpecified, "Starting Platform Manager Event Loop"); + CHIP_ERROR ret = PlatformMgr().StartEventLoopTask(); + if (ret != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "PlatformMgr().StartEventLoopTask() failed"); + appError(ret); + } + + vTaskSuspend(NULL); +#if CHIP_DETAIL_LOGGING + Server::GetInstance().GetICDManager().RegisterObserver(&sAppTask); +#endif + + DiagnosticDataProviderImpl::GetDefaultInstance().GetCurrentHeapFree(currentHeapFree); + ChipLogProgress(NotSpecified, "App Task started, with SRAM heap %lld left", currentHeapFree); + + while (true) + { + appEvent = APP_EVENT_NONE; + BaseType_t eventReceived = xTaskNotifyWait(0, APP_EVENT_ALL_MASK, (uint32_t *) &appEvent, portMAX_DELAY); + + if (eventReceived) + { + PlatformMgr().LockChipStack(); + + if (APP_EVENT_BUTTON_PRESSED & appEvent) + { + ChipLogProgress(NotSpecified, "APP_EVENT_BUTTON_PRESSED"); + } + + if (APP_EVENT_FACTORY_RESET & appEvent) + { + DeviceLayer::ConfigurationMgr().InitiateFactoryReset(); + } + + if (APP_EVENT_CONTACT_SENSOR_TRUE & appEvent) + { + stateValueAttrValue = 1; + app::Clusters::BooleanState::Attributes::StateValue::Set(1, stateValueAttrValue); + } + + if (APP_EVENT_CONTACT_SENSOR_FALSE & appEvent) + { + stateValueAttrValue = 0; + app::Clusters::BooleanState::Attributes::StateValue::Set(1, stateValueAttrValue); + } + + PlatformMgr().UnlockChipStack(); + } + } +} + +#if CHIP_DETAIL_LOGGING +void AppTask::OnEnterActiveMode() +{ + ChipLogProgress(NotSpecified, "App ICD enter active mode."); +} + +void AppTask::OnEnterIdleMode() +{ + ChipLogProgress(NotSpecified, "App ICD enter idle mode."); +} + +void AppTask::OnTransitionToIdle() +{ + ChipLogProgress(NotSpecified, "App ICD transit to idle."); +} + +void AppTask::OnICDModeChange() +{ + ChipLogProgress(NotSpecified, "App ICD mode change."); +} +#endif diff --git a/examples/contact-sensor-app/bouffalolab/common/AppTask.h b/examples/contact-sensor-app/bouffalolab/common/AppTask.h new file mode 100644 index 00000000000000..92b3ba7c45d2f9 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/common/AppTask.h @@ -0,0 +1,130 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "FreeRTOS.h" +#include "timers.h" + +#include +#include + +extern "C" { +#include +#include +#include +} + +using namespace ::chip; +using namespace ::chip::DeviceLayer; + +#define APP_BUTTON_PRESS_JITTER 100 +#define APP_BUTTON_PRESS_SHORT 1000 +#define APP_BUTTON_PRESS_LONG 3000 + +#define APP_LIGHT_ENDPOINT_ID 1 + +// Application-defined error codes in the CHIP_ERROR space. +#define APP_ERROR_EVENT_QUEUE_FAILED CHIP_APPLICATION_ERROR(0x01) +#define APP_ERROR_CREATE_TASK_FAILED CHIP_APPLICATION_ERROR(0x02) +#define APP_ERROR_UNHANDLED_EVENT CHIP_APPLICATION_ERROR(0x03) +#define APP_ERROR_CREATE_TIMER_FAILED CHIP_APPLICATION_ERROR(0x04) +#define APP_ERROR_START_TIMER_FAILED CHIP_APPLICATION_ERROR(0x05) +#define APP_ERROR_STOP_TIMER_FAILED CHIP_APPLICATION_ERROR(0x06) + +struct Identify; + +#if CHIP_DETAIL_LOGGING +class AppTask : public chip::app::ICDStateObserver +#else +class AppTask +#endif +{ +public: + friend AppTask & GetAppTask(void); + + enum app_event_t + { + APP_EVENT_NONE = 0x00000000, + + APP_EVENT_BUTTON_PRESSED = 0x00000010, + APP_EVENT_FACTORY_RESET = 0x00000020, + APP_EVENT_COMMISSION_COMPLETE = 0x00000080, + APP_EVENT_BUTTON_MASK = APP_EVENT_BUTTON_PRESSED | APP_EVENT_FACTORY_RESET | APP_EVENT_COMMISSION_COMPLETE, + + APP_EVENT_CONTACT_SENSOR_TRUE = 0x00000100, + APP_EVENT_CONTACT_SENSOR_FALSE = 0x00000200, + APP_EVENT_CONTACT_SENSOR_MASK = APP_EVENT_CONTACT_SENSOR_TRUE | APP_EVENT_CONTACT_SENSOR_FALSE, + + APP_EVENT_IDENTIFY_START = 0x01000000, + APP_EVENT_IDENTIFY_IDENTIFY = 0x02000000, + APP_EVENT_IDENTIFY_STOP = 0x04000000, + APP_EVENT_IDENTIFY_MASK = APP_EVENT_IDENTIFY_START | APP_EVENT_IDENTIFY_IDENTIFY | APP_EVENT_IDENTIFY_STOP, + + APP_EVENT_ALL_MASK = APP_EVENT_BUTTON_MASK | APP_EVENT_CONTACT_SENSOR_MASK | APP_EVENT_IDENTIFY_MASK, + }; + + void SetEndpointId(EndpointId endpointId) + { + if (mEndpointId != (EndpointId) -1) + mEndpointId = endpointId; + } + + EndpointId GetEndpointId(void) { return mEndpointId; } + void PostEvent(app_event_t event); + static void ButtonEventHandler(void * arg); + +#if CHIP_DETAIL_LOGGING + void OnEnterActiveMode(); + void OnEnterIdleMode(); + void OnTransitionToIdle(); + void OnICDModeChange(); +#endif + +private: + friend void StartAppTask(void); + friend PlatformManagerImpl; + + static void ScheduleInit(intptr_t arg); + static void AppTaskMain(void * pvParameter); + +#if CONFIG_ENABLE_CHIP_SHELL + static CHIP_ERROR StartAppShellTask(); + static void AppShellTask(void * args); +#endif + + uint64_t mButtonPressedTime; + + EndpointId mEndpointId = (EndpointId) 1; + TaskHandle_t sAppTaskHandle; + QueueHandle_t sAppEventQueue; + + static StackType_t appStack[APP_TASK_STACK_SIZE / sizeof(StackType_t)]; + static StaticTask_t appTaskStruct; + static AppTask sAppTask; +}; + +inline AppTask & GetAppTask(void) +{ + return AppTask::sAppTask; +} + +void StartAppTask(); diff --git a/examples/contact-sensor-app/bouffalolab/common/ZclCallbacks.cpp b/examples/contact-sensor-app/bouffalolab/common/ZclCallbacks.cpp new file mode 100644 index 00000000000000..f9899fafe5c491 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/common/ZclCallbacks.cpp @@ -0,0 +1,45 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::app; +using namespace ::chip::app::Clusters; +using namespace ::chip::app::Clusters::BooleanState; + +void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & path, uint8_t type, uint16_t size, uint8_t * value) +{ + ChipLogProgress(Zcl, "Cluster callback: " ChipLogFormatMEI " " ChipLogFormatMEI, ChipLogValueMEI(path.mClusterId), + ChipLogValueMEI(path.mAttributeId)); + + if (path.mClusterId == BooleanState::Id && path.mAttributeId == BooleanState::Attributes::StateValue::Id) + { + ChipLogProgress(Zcl, "Cluster BooleanState: attribute StateValue set to %u", *value); + return; + } +} + +void emberAfBooleanStateClusterInitCallback(EndpointId endpoint) +{ + ChipLogProgress(Zcl, "emberAfBooleanStateClusterInitCallback\n"); +} diff --git a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter new file mode 100644 index 00000000000000..f12c88c86598a1 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter @@ -0,0 +1,2301 @@ +// This IDL was generated automatically by ZAP. +// It is for view/code review purposes only. + +enum AreaTypeTag : enum8 { + kAisle = 0; + kAttic = 1; + kBackDoor = 2; + kBackYard = 3; + kBalcony = 4; + kBallroom = 5; + kBathroom = 6; + kBedroom = 7; + kBorder = 8; + kBoxroom = 9; + kBreakfastRoom = 10; + kCarport = 11; + kCellar = 12; + kCloakroom = 13; + kCloset = 14; + kConservatory = 15; + kCorridor = 16; + kCraftRoom = 17; + kCupboard = 18; + kDeck = 19; + kDen = 20; + kDining = 21; + kDrawingRoom = 22; + kDressingRoom = 23; + kDriveway = 24; + kElevator = 25; + kEnsuite = 26; + kEntrance = 27; + kEntryway = 28; + kFamilyRoom = 29; + kFoyer = 30; + kFrontDoor = 31; + kFrontYard = 32; + kGameRoom = 33; + kGarage = 34; + kGarageDoor = 35; + kGarden = 36; + kGardenDoor = 37; + kGuestBathroom = 38; + kGuestBedroom = 39; + kGuestRestroom = 40; + kGuestRoom = 41; + kGym = 42; + kHallway = 43; + kHearthRoom = 44; + kKidsRoom = 45; + kKidsBedroom = 46; + kKitchen = 47; + kLarder = 48; + kLaundryRoom = 49; + kLawn = 50; + kLibrary = 51; + kLivingRoom = 52; + kLounge = 53; + kMediaTVRoom = 54; + kMudRoom = 55; + kMusicRoom = 56; + kNursery = 57; + kOffice = 58; + kOutdoorKitchen = 59; + kOutside = 60; + kPantry = 61; + kParkingLot = 62; + kParlor = 63; + kPatio = 64; + kPlayRoom = 65; + kPoolRoom = 66; + kPorch = 67; + kPrimaryBathroom = 68; + kPrimaryBedroom = 69; + kRamp = 70; + kReceptionRoom = 71; + kRecreationRoom = 72; + kRestroom = 73; + kRoof = 74; + kSauna = 75; + kScullery = 76; + kSewingRoom = 77; + kShed = 78; + kSideDoor = 79; + kSideYard = 80; + kSittingRoom = 81; + kSnug = 82; + kSpa = 83; + kStaircase = 84; + kSteamRoom = 85; + kStorageRoom = 86; + kStudio = 87; + kStudy = 88; + kSunRoom = 89; + kSwimmingPool = 90; + kTerrace = 91; + kUtilityRoom = 92; + kWard = 93; + kWorkshop = 94; +} + +enum AtomicRequestTypeEnum : enum8 { + kBeginWrite = 0; + kCommitWrite = 1; + kRollbackWrite = 2; +} + +enum FloorSurfaceTag : enum8 { + kCarpet = 0; + kCeramic = 1; + kConcrete = 2; + kCork = 3; + kDeepCarpet = 4; + kDirt = 5; + kEngineeredWood = 6; + kGlass = 7; + kGrass = 8; + kHardwood = 9; + kLaminate = 10; + kLinoleum = 11; + kMat = 12; + kMetal = 13; + kPlastic = 14; + kPolishedConcrete = 15; + kRubber = 16; + kRug = 17; + kSand = 18; + kStone = 19; + kTatami = 20; + kTerrazzo = 21; + kTile = 22; + kVinyl = 23; +} + +enum LandmarkTag : enum8 { + kAirConditioner = 0; + kAirPurifier = 1; + kBackDoor = 2; + kBarStool = 3; + kBathMat = 4; + kBathtub = 5; + kBed = 6; + kBookshelf = 7; + kChair = 8; + kChristmasTree = 9; + kCoatRack = 10; + kCoffeeTable = 11; + kCookingRange = 12; + kCouch = 13; + kCountertop = 14; + kCradle = 15; + kCrib = 16; + kDesk = 17; + kDiningTable = 18; + kDishwasher = 19; + kDoor = 20; + kDresser = 21; + kLaundryDryer = 22; + kFan = 23; + kFireplace = 24; + kFreezer = 25; + kFrontDoor = 26; + kHighChair = 27; + kKitchenIsland = 28; + kLamp = 29; + kLitterBox = 30; + kMirror = 31; + kNightstand = 32; + kOven = 33; + kPetBed = 34; + kPetBowl = 35; + kPetCrate = 36; + kRefrigerator = 37; + kScratchingPost = 38; + kShoeRack = 39; + kShower = 40; + kSideDoor = 41; + kSink = 42; + kSofa = 43; + kStove = 44; + kTable = 45; + kToilet = 46; + kTrashCan = 47; + kLaundryWasher = 48; + kWindow = 49; + kWineCooler = 50; +} + +enum PositionTag : enum8 { + kLeft = 0; + kRight = 1; + kTop = 2; + kBottom = 3; + kMiddle = 4; + kRow = 5; + kColumn = 6; +} + +enum RelativePositionTag : enum8 { + kUnder = 0; + kNextTo = 1; + kAround = 2; + kOn = 3; + kAbove = 4; + kFrontOf = 5; + kBehind = 6; +} + +enum TestGlobalEnum : enum8 { + kSomeValue = 0; + kSomeOtherValue = 1; + kFinalValue = 2; +} + +enum ThreeLevelAutoEnum : enum8 { + kLow = 0; + kMedium = 1; + kHigh = 2; + kAutomatic = 3; +} + +bitmap TestGlobalBitmap : bitmap32 { + kFirstBit = 0x1; + kSecondBit = 0x2; +} + +struct TestGlobalStruct { + char_string<128> name = 0; + nullable TestGlobalBitmap myBitmap = 1; + optional nullable TestGlobalEnum myEnum = 2; +} + +struct LocationDescriptorStruct { + char_string<128> locationName = 0; + nullable int16s floorNumber = 1; + nullable AreaTypeTag areaType = 2; +} + +struct AtomicAttributeStatusStruct { + attrib_id attributeID = 0; + status statusCode = 1; +} + +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + +/** Attributes and commands for group configuration and manipulation. */ +cluster Groups = 4 { + revision 4; + + bitmap Feature : bitmap32 { + kGroupNames = 0x1; + } + + bitmap NameSupportBitmap : bitmap8 { + kGroupNames = 0x80; + } + + readonly attribute NameSupportBitmap nameSupport = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct AddGroupRequest { + group_id groupID = 0; + char_string<16> groupName = 1; + } + + response struct AddGroupResponse = 0 { + enum8 status = 0; + group_id groupID = 1; + } + + request struct ViewGroupRequest { + group_id groupID = 0; + } + + response struct ViewGroupResponse = 1 { + enum8 status = 0; + group_id groupID = 1; + char_string<16> groupName = 2; + } + + request struct GetGroupMembershipRequest { + group_id groupList[] = 0; + } + + response struct GetGroupMembershipResponse = 2 { + nullable int8u capacity = 0; + group_id groupList[] = 1; + } + + request struct RemoveGroupRequest { + group_id groupID = 0; + } + + response struct RemoveGroupResponse = 3 { + enum8 status = 0; + group_id groupID = 1; + } + + request struct AddGroupIfIdentifyingRequest { + group_id groupID = 0; + char_string<16> groupName = 1; + } + + /** Command description for AddGroup */ + fabric command access(invoke: manage) AddGroup(AddGroupRequest): AddGroupResponse = 0; + /** Command description for ViewGroup */ + fabric command ViewGroup(ViewGroupRequest): ViewGroupResponse = 1; + /** Command description for GetGroupMembership */ + fabric command GetGroupMembership(GetGroupMembershipRequest): GetGroupMembershipResponse = 2; + /** Command description for RemoveGroup */ + fabric command access(invoke: manage) RemoveGroup(RemoveGroupRequest): RemoveGroupResponse = 3; + /** Command description for RemoveAllGroups */ + fabric command access(invoke: manage) RemoveAllGroups(): DefaultSuccess = 4; + /** Command description for AddGroupIfIdentifying */ + fabric command access(invoke: manage) AddGroupIfIdentifying(AddGroupIfIdentifyingRequest): DefaultSuccess = 5; +} + +/** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ +cluster Descriptor = 29 { + revision 2; + + bitmap Feature : bitmap32 { + kTagList = 0x1; + } + + struct DeviceTypeStruct { + devtype_id deviceType = 0; + int16u revision = 1; + } + + struct SemanticTagStruct { + nullable vendor_id mfgCode = 0; + enum8 namespaceID = 1; + enum8 tag = 2; + optional nullable char_string label = 3; + } + + readonly attribute DeviceTypeStruct deviceTypeList[] = 0; + readonly attribute cluster_id serverList[] = 1; + readonly attribute cluster_id clientList[] = 2; + readonly attribute endpoint_no partsList[] = 3; + readonly attribute optional SemanticTagStruct tagList[] = 4; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** The Access Control Cluster exposes a data model view of a + Node's Access Control List (ACL), which codifies the rules used to manage + and enforce Access Control for the Node's endpoints and their associated + cluster instances. */ +cluster AccessControl = 31 { + revision 2; + + enum AccessControlEntryAuthModeEnum : enum8 { + kPASE = 1; + kCASE = 2; + kGroup = 3; + } + + enum AccessControlEntryPrivilegeEnum : enum8 { + kView = 1; + kProxyView = 2; + kOperate = 3; + kManage = 4; + kAdminister = 5; + } + + enum AccessRestrictionTypeEnum : enum8 { + kAttributeAccessForbidden = 0; + kAttributeWriteForbidden = 1; + kCommandForbidden = 2; + kEventForbidden = 3; + } + + enum ChangeTypeEnum : enum8 { + kChanged = 0; + kAdded = 1; + kRemoved = 2; + } + + bitmap Feature : bitmap32 { + kExtension = 0x1; + kManagedDevice = 0x2; + } + + struct AccessRestrictionStruct { + AccessRestrictionTypeEnum type = 0; + nullable int32u id = 1; + } + + struct CommissioningAccessRestrictionEntryStruct { + endpoint_no endpoint = 0; + cluster_id cluster = 1; + AccessRestrictionStruct restrictions[] = 2; + } + + fabric_scoped struct AccessRestrictionEntryStruct { + fabric_sensitive endpoint_no endpoint = 0; + fabric_sensitive cluster_id cluster = 1; + fabric_sensitive AccessRestrictionStruct restrictions[] = 2; + fabric_idx fabricIndex = 254; + } + + struct AccessControlTargetStruct { + nullable cluster_id cluster = 0; + nullable endpoint_no endpoint = 1; + nullable devtype_id deviceType = 2; + } + + fabric_scoped struct AccessControlEntryStruct { + fabric_sensitive AccessControlEntryPrivilegeEnum privilege = 1; + fabric_sensitive AccessControlEntryAuthModeEnum authMode = 2; + nullable fabric_sensitive int64u subjects[] = 3; + nullable fabric_sensitive AccessControlTargetStruct targets[] = 4; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct AccessControlExtensionStruct { + fabric_sensitive octet_string<128> data = 1; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) AccessControlEntryChanged = 0 { + nullable node_id adminNodeID = 1; + nullable int16u adminPasscodeID = 2; + ChangeTypeEnum changeType = 3; + nullable AccessControlEntryStruct latestValue = 4; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) AccessControlExtensionChanged = 1 { + nullable node_id adminNodeID = 1; + nullable int16u adminPasscodeID = 2; + ChangeTypeEnum changeType = 3; + nullable AccessControlExtensionStruct latestValue = 4; + fabric_idx fabricIndex = 254; + } + + fabric_sensitive info event access(read: administer) FabricRestrictionReviewUpdate = 2 { + int64u token = 0; + optional long_char_string instruction = 1; + optional long_char_string ARLRequestFlowUrl = 2; + fabric_idx fabricIndex = 254; + } + + attribute access(read: administer, write: administer) AccessControlEntryStruct acl[] = 0; + attribute access(read: administer, write: administer) optional AccessControlExtensionStruct extension[] = 1; + readonly attribute int16u subjectsPerAccessControlEntry = 2; + readonly attribute int16u targetsPerAccessControlEntry = 3; + readonly attribute int16u accessControlEntriesPerFabric = 4; + readonly attribute optional CommissioningAccessRestrictionEntryStruct commissioningARL[] = 5; + readonly attribute optional AccessRestrictionEntryStruct arl[] = 6; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ReviewFabricRestrictionsRequest { + CommissioningAccessRestrictionEntryStruct arl[] = 0; + } + + response struct ReviewFabricRestrictionsResponse = 1 { + int64u token = 0; + } + + /** This command signals to the service associated with the device vendor that the fabric administrator would like a review of the current restrictions on the accessing fabric. */ + fabric command access(invoke: administer) ReviewFabricRestrictions(ReviewFabricRestrictionsRequest): ReviewFabricRestrictionsResponse = 0; +} + +/** This cluster provides attributes and events for determining basic information about Nodes, which supports both + Commissioning and operational determination of Node characteristics, such as Vendor ID, Product ID and serial number, + which apply to the whole Node. Also allows setting user device information such as location. */ +cluster BasicInformation = 40 { + revision 3; + + enum ColorEnum : enum8 { + kBlack = 0; + kNavy = 1; + kGreen = 2; + kTeal = 3; + kMaroon = 4; + kPurple = 5; + kOlive = 6; + kGray = 7; + kBlue = 8; + kLime = 9; + kAqua = 10; + kRed = 11; + kFuchsia = 12; + kYellow = 13; + kWhite = 14; + kNickel = 15; + kChrome = 16; + kBrass = 17; + kCopper = 18; + kSilver = 19; + kGold = 20; + } + + enum ProductFinishEnum : enum8 { + kOther = 0; + kMatte = 1; + kSatin = 2; + kPolished = 3; + kRugged = 4; + kFabric = 5; + } + + struct CapabilityMinimaStruct { + int16u caseSessionsPerFabric = 0; + int16u subscriptionsPerFabric = 1; + } + + struct ProductAppearanceStruct { + ProductFinishEnum finish = 0; + nullable ColorEnum primaryColor = 1; + } + + critical event StartUp = 0 { + int32u softwareVersion = 0; + } + + critical event ShutDown = 1 { + } + + info event Leave = 2 { + fabric_idx fabricIndex = 0; + } + + info event ReachableChanged = 3 { + boolean reachableNewValue = 0; + } + + readonly attribute int16u dataModelRevision = 0; + readonly attribute char_string<32> vendorName = 1; + readonly attribute vendor_id vendorID = 2; + readonly attribute char_string<32> productName = 3; + readonly attribute int16u productID = 4; + attribute access(write: manage) char_string<32> nodeLabel = 5; + attribute access(write: administer) char_string<2> location = 6; + readonly attribute int16u hardwareVersion = 7; + readonly attribute char_string<64> hardwareVersionString = 8; + readonly attribute int32u softwareVersion = 9; + readonly attribute char_string<64> softwareVersionString = 10; + readonly attribute optional char_string<16> manufacturingDate = 11; + readonly attribute optional char_string<32> partNumber = 12; + readonly attribute optional long_char_string<256> productURL = 13; + readonly attribute optional char_string<64> productLabel = 14; + readonly attribute optional char_string<32> serialNumber = 15; + attribute access(write: manage) optional boolean localConfigDisabled = 16; + readonly attribute optional boolean reachable = 17; + readonly attribute char_string<32> uniqueID = 18; + readonly attribute CapabilityMinimaStruct capabilityMinima = 19; + readonly attribute optional ProductAppearanceStruct productAppearance = 20; + readonly attribute int32u specificationVersion = 21; + readonly attribute int16u maxPathsPerInvoke = 22; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + command MfgSpecificPing(): DefaultSuccess = 0; +} + +/** Provides an interface for providing OTA software updates */ +cluster OtaSoftwareUpdateProvider = 41 { + revision 1; // NOTE: Default/not specifically set + + enum ApplyUpdateActionEnum : enum8 { + kProceed = 0; + kAwaitNextAction = 1; + kDiscontinue = 2; + } + + enum DownloadProtocolEnum : enum8 { + kBDXSynchronous = 0; + kBDXAsynchronous = 1; + kHTTPS = 2; + kVendorSpecific = 3; + } + + enum StatusEnum : enum8 { + kUpdateAvailable = 0; + kBusy = 1; + kNotAvailable = 2; + kDownloadProtocolNotSupported = 3; + } + + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct QueryImageRequest { + vendor_id vendorID = 0; + int16u productID = 1; + int32u softwareVersion = 2; + DownloadProtocolEnum protocolsSupported[] = 3; + optional int16u hardwareVersion = 4; + optional char_string<2> location = 5; + optional boolean requestorCanConsent = 6; + optional octet_string<512> metadataForProvider = 7; + } + + response struct QueryImageResponse = 1 { + StatusEnum status = 0; + optional int32u delayedActionTime = 1; + optional char_string<256> imageURI = 2; + optional int32u softwareVersion = 3; + optional char_string<64> softwareVersionString = 4; + optional octet_string<32> updateToken = 5; + optional boolean userConsentNeeded = 6; + optional octet_string<512> metadataForRequestor = 7; + } + + request struct ApplyUpdateRequestRequest { + octet_string<32> updateToken = 0; + int32u newVersion = 1; + } + + response struct ApplyUpdateResponse = 3 { + ApplyUpdateActionEnum action = 0; + int32u delayedActionTime = 1; + } + + request struct NotifyUpdateAppliedRequest { + octet_string<32> updateToken = 0; + int32u softwareVersion = 1; + } + + /** Determine availability of a new Software Image */ + command QueryImage(QueryImageRequest): QueryImageResponse = 0; + /** Determine next action to take for a downloaded Software Image */ + command ApplyUpdateRequest(ApplyUpdateRequestRequest): ApplyUpdateResponse = 2; + /** Notify OTA Provider that an update was applied */ + command NotifyUpdateApplied(NotifyUpdateAppliedRequest): DefaultSuccess = 4; +} + +/** Provides an interface for downloading and applying OTA software updates */ +cluster OtaSoftwareUpdateRequestor = 42 { + revision 1; // NOTE: Default/not specifically set + + enum AnnouncementReasonEnum : enum8 { + kSimpleAnnouncement = 0; + kUpdateAvailable = 1; + kUrgentUpdateAvailable = 2; + } + + enum ChangeReasonEnum : enum8 { + kUnknown = 0; + kSuccess = 1; + kFailure = 2; + kTimeOut = 3; + kDelayByProvider = 4; + } + + enum UpdateStateEnum : enum8 { + kUnknown = 0; + kIdle = 1; + kQuerying = 2; + kDelayedOnQuery = 3; + kDownloading = 4; + kApplying = 5; + kDelayedOnApply = 6; + kRollingBack = 7; + kDelayedOnUserConsent = 8; + } + + fabric_scoped struct ProviderLocation { + node_id providerNodeID = 1; + endpoint_no endpoint = 2; + fabric_idx fabricIndex = 254; + } + + info event StateTransition = 0 { + UpdateStateEnum previousState = 0; + UpdateStateEnum newState = 1; + ChangeReasonEnum reason = 2; + nullable int32u targetSoftwareVersion = 3; + } + + critical event VersionApplied = 1 { + int32u softwareVersion = 0; + int16u productID = 1; + } + + info event DownloadError = 2 { + int32u softwareVersion = 0; + int64u bytesDownloaded = 1; + nullable int8u progressPercent = 2; + nullable int64s platformCode = 3; + } + + attribute access(write: administer) ProviderLocation defaultOTAProviders[] = 0; + readonly attribute boolean updatePossible = 1; + readonly attribute UpdateStateEnum updateState = 2; + readonly attribute nullable int8u updateStateProgress = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct AnnounceOTAProviderRequest { + node_id providerNodeID = 0; + vendor_id vendorID = 1; + AnnouncementReasonEnum announcementReason = 2; + optional octet_string<512> metadataForNode = 3; + endpoint_no endpoint = 4; + } + + /** Announce the presence of an OTA Provider */ + command AnnounceOTAProvider(AnnounceOTAProviderRequest): DefaultSuccess = 0; +} + +/** Nodes should be expected to be deployed to any and all regions of the world. These global regions + may have differing common languages, units of measurements, and numerical formatting + standards. As such, Nodes that visually or audibly convey information need a mechanism by which + they can be configured to use a user’s preferred language, units, etc */ +cluster LocalizationConfiguration = 43 { + revision 1; // NOTE: Default/not specifically set + + attribute access(write: manage) char_string<35> activeLocale = 0; + readonly attribute char_string supportedLocales[] = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** This cluster is used to manage global aspects of the Commissioning flow. */ +cluster GeneralCommissioning = 48 { + revision 1; // NOTE: Default/not specifically set + + enum CommissioningErrorEnum : enum8 { + kOK = 0; + kValueOutsideRange = 1; + kInvalidAuthentication = 2; + kNoFailSafe = 3; + kBusyWithOtherAdmin = 4; + kRequiredTCNotAccepted = 5; + kTCAcknowledgementsNotReceived = 6; + kTCMinVersionNotMet = 7; + } + + enum RegulatoryLocationTypeEnum : enum8 { + kIndoor = 0; + kOutdoor = 1; + kIndoorOutdoor = 2; + } + + bitmap Feature : bitmap32 { + kTermsAndConditions = 0x1; + } + + struct BasicCommissioningInfo { + int16u failSafeExpiryLengthSeconds = 0; + int16u maxCumulativeFailsafeSeconds = 1; + } + + attribute access(write: administer) int64u breadcrumb = 0; + readonly attribute BasicCommissioningInfo basicCommissioningInfo = 1; + readonly attribute RegulatoryLocationTypeEnum regulatoryConfig = 2; + readonly attribute RegulatoryLocationTypeEnum locationCapability = 3; + readonly attribute boolean supportsConcurrentConnection = 4; + provisional readonly attribute access(read: administer) optional int16u TCAcceptedVersion = 5; + provisional readonly attribute access(read: administer) optional int16u TCMinRequiredVersion = 6; + provisional readonly attribute access(read: administer) optional bitmap16 TCAcknowledgements = 7; + provisional readonly attribute access(read: administer) optional boolean TCAcknowledgementsRequired = 8; + provisional readonly attribute access(read: administer) optional int32u TCUpdateDeadline = 9; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ArmFailSafeRequest { + int16u expiryLengthSeconds = 0; + int64u breadcrumb = 1; + } + + response struct ArmFailSafeResponse = 1 { + CommissioningErrorEnum errorCode = 0; + char_string<128> debugText = 1; + } + + request struct SetRegulatoryConfigRequest { + RegulatoryLocationTypeEnum newRegulatoryConfig = 0; + char_string<2> countryCode = 1; + int64u breadcrumb = 2; + } + + response struct SetRegulatoryConfigResponse = 3 { + CommissioningErrorEnum errorCode = 0; + char_string debugText = 1; + } + + response struct CommissioningCompleteResponse = 5 { + CommissioningErrorEnum errorCode = 0; + char_string debugText = 1; + } + + request struct SetTCAcknowledgementsRequest { + int16u TCVersion = 0; + bitmap16 TCUserResponse = 1; + } + + response struct SetTCAcknowledgementsResponse = 7 { + CommissioningErrorEnum errorCode = 0; + } + + /** Arm the persistent fail-safe timer with an expiry time of now + ExpiryLengthSeconds using device clock */ + command access(invoke: administer) ArmFailSafe(ArmFailSafeRequest): ArmFailSafeResponse = 0; + /** Set the regulatory configuration to be used during commissioning */ + command access(invoke: administer) SetRegulatoryConfig(SetRegulatoryConfigRequest): SetRegulatoryConfigResponse = 2; + /** Signals the Server that the Client has successfully completed all steps of Commissioning/Recofiguration needed during fail-safe period. */ + fabric command access(invoke: administer) CommissioningComplete(): CommissioningCompleteResponse = 4; + /** This command sets the user acknowledgements received in the Enhanced Setup Flow Terms and Conditions into the node. */ + command access(invoke: administer) SetTCAcknowledgements(SetTCAcknowledgementsRequest): SetTCAcknowledgementsResponse = 6; +} + +/** Functionality to configure, enable, disable network credentials and access on a Matter device. */ +cluster NetworkCommissioning = 49 { + revision 1; // NOTE: Default/not specifically set + + enum NetworkCommissioningStatusEnum : enum8 { + kSuccess = 0; + kOutOfRange = 1; + kBoundsExceeded = 2; + kNetworkIDNotFound = 3; + kDuplicateNetworkID = 4; + kNetworkNotFound = 5; + kRegulatoryError = 6; + kAuthFailure = 7; + kUnsupportedSecurity = 8; + kOtherConnectionFailure = 9; + kIPV6Failed = 10; + kIPBindFailed = 11; + kUnknownError = 12; + } + + enum WiFiBandEnum : enum8 { + k2G4 = 0; + k3G65 = 1; + k5G = 2; + k6G = 3; + k60G = 4; + k1G = 5; + } + + bitmap Feature : bitmap32 { + kWiFiNetworkInterface = 0x1; + kThreadNetworkInterface = 0x2; + kEthernetNetworkInterface = 0x4; + kPerDeviceCredentials = 0x8; + } + + bitmap ThreadCapabilitiesBitmap : bitmap16 { + kIsBorderRouterCapable = 0x1; + kIsRouterCapable = 0x2; + kIsSleepyEndDeviceCapable = 0x4; + kIsFullThreadDevice = 0x8; + kIsSynchronizedSleepyEndDeviceCapable = 0x10; + } + + bitmap WiFiSecurityBitmap : bitmap8 { + kUnencrypted = 0x1; + kWEP = 0x2; + kWPAPersonal = 0x4; + kWPA2Personal = 0x8; + kWPA3Personal = 0x10; + kWPA3MatterPDC = 0x20; + } + + struct NetworkInfoStruct { + octet_string<32> networkID = 0; + boolean connected = 1; + optional nullable octet_string<20> networkIdentifier = 2; + optional nullable octet_string<20> clientIdentifier = 3; + } + + struct ThreadInterfaceScanResultStruct { + int16u panId = 0; + int64u extendedPanId = 1; + char_string<16> networkName = 2; + int16u channel = 3; + int8u version = 4; + octet_string<8> extendedAddress = 5; + int8s rssi = 6; + int8u lqi = 7; + } + + struct WiFiInterfaceScanResultStruct { + WiFiSecurityBitmap security = 0; + octet_string<32> ssid = 1; + octet_string<6> bssid = 2; + int16u channel = 3; + WiFiBandEnum wiFiBand = 4; + int8s rssi = 5; + } + + readonly attribute access(read: administer) int8u maxNetworks = 0; + readonly attribute access(read: administer) NetworkInfoStruct networks[] = 1; + readonly attribute optional int8u scanMaxTimeSeconds = 2; + readonly attribute optional int8u connectMaxTimeSeconds = 3; + attribute access(write: administer) boolean interfaceEnabled = 4; + readonly attribute access(read: administer) nullable NetworkCommissioningStatusEnum lastNetworkingStatus = 5; + readonly attribute access(read: administer) nullable octet_string<32> lastNetworkID = 6; + readonly attribute access(read: administer) nullable int32s lastConnectErrorValue = 7; + provisional readonly attribute optional WiFiBandEnum supportedWiFiBands[] = 8; + provisional readonly attribute optional ThreadCapabilitiesBitmap supportedThreadFeatures = 9; + provisional readonly attribute optional int16u threadVersion = 10; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct ScanNetworksRequest { + optional nullable octet_string<32> ssid = 0; + optional int64u breadcrumb = 1; + } + + response struct ScanNetworksResponse = 1 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string debugText = 1; + optional WiFiInterfaceScanResultStruct wiFiScanResults[] = 2; + optional ThreadInterfaceScanResultStruct threadScanResults[] = 3; + } + + request struct AddOrUpdateWiFiNetworkRequest { + octet_string<32> ssid = 0; + octet_string<64> credentials = 1; + optional int64u breadcrumb = 2; + optional octet_string<140> networkIdentity = 3; + optional octet_string<20> clientIdentifier = 4; + optional octet_string<32> possessionNonce = 5; + } + + request struct AddOrUpdateThreadNetworkRequest { + octet_string<254> operationalDataset = 0; + optional int64u breadcrumb = 1; + } + + request struct RemoveNetworkRequest { + octet_string<32> networkID = 0; + optional int64u breadcrumb = 1; + } + + response struct NetworkConfigResponse = 5 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string<512> debugText = 1; + optional int8u networkIndex = 2; + optional octet_string<140> clientIdentity = 3; + optional octet_string<64> possessionSignature = 4; + } + + request struct ConnectNetworkRequest { + octet_string<32> networkID = 0; + optional int64u breadcrumb = 1; + } + + response struct ConnectNetworkResponse = 7 { + NetworkCommissioningStatusEnum networkingStatus = 0; + optional char_string debugText = 1; + nullable int32s errorValue = 2; + } + + request struct ReorderNetworkRequest { + octet_string<32> networkID = 0; + int8u networkIndex = 1; + optional int64u breadcrumb = 2; + } + + request struct QueryIdentityRequest { + octet_string<20> keyIdentifier = 0; + optional octet_string<32> possessionNonce = 1; + } + + response struct QueryIdentityResponse = 10 { + octet_string<140> identity = 0; + optional octet_string<64> possessionSignature = 1; + } + + /** Detemine the set of networks the device sees as available. */ + command access(invoke: administer) ScanNetworks(ScanNetworksRequest): ScanNetworksResponse = 0; + /** Add or update the credentials for a given Wi-Fi network. */ + command access(invoke: administer) AddOrUpdateWiFiNetwork(AddOrUpdateWiFiNetworkRequest): NetworkConfigResponse = 2; + /** Add or update the credentials for a given Thread network. */ + command access(invoke: administer) AddOrUpdateThreadNetwork(AddOrUpdateThreadNetworkRequest): NetworkConfigResponse = 3; + /** Remove the definition of a given network (including its credentials). */ + command access(invoke: administer) RemoveNetwork(RemoveNetworkRequest): NetworkConfigResponse = 4; + /** Connect to the specified network, using previously-defined credentials. */ + command access(invoke: administer) ConnectNetwork(ConnectNetworkRequest): ConnectNetworkResponse = 6; + /** Modify the order in which networks will be presented in the Networks attribute. */ + command access(invoke: administer) ReorderNetwork(ReorderNetworkRequest): NetworkConfigResponse = 8; + /** Retrieve details about and optionally proof of possession of a network client identity. */ + command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; +} + +/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ +cluster DiagnosticLogs = 50 { + revision 1; // NOTE: Default/not specifically set + + enum IntentEnum : enum8 { + kEndUserSupport = 0; + kNetworkDiag = 1; + kCrashLogs = 2; + } + + enum StatusEnum : enum8 { + kSuccess = 0; + kExhausted = 1; + kNoLogs = 2; + kBusy = 3; + kDenied = 4; + } + + enum TransferProtocolEnum : enum8 { + kResponsePayload = 0; + kBDX = 1; + } + + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct RetrieveLogsRequestRequest { + IntentEnum intent = 0; + TransferProtocolEnum requestedProtocol = 1; + optional char_string<32> transferFileDesignator = 2; + } + + response struct RetrieveLogsResponse = 1 { + StatusEnum status = 0; + long_octet_string logContent = 1; + optional epoch_us UTCTimeStamp = 2; + optional systime_us timeSinceBoot = 3; + } + + /** Retrieving diagnostic logs from a Node */ + command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; +} + +/** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ +cluster GeneralDiagnostics = 51 { + revision 2; + + enum BootReasonEnum : enum8 { + kUnspecified = 0; + kPowerOnReboot = 1; + kBrownOutReset = 2; + kSoftwareWatchdogReset = 3; + kHardwareWatchdogReset = 4; + kSoftwareUpdateCompleted = 5; + kSoftwareReset = 6; + } + + enum HardwareFaultEnum : enum8 { + kUnspecified = 0; + kRadio = 1; + kSensor = 2; + kResettableOverTemp = 3; + kNonResettableOverTemp = 4; + kPowerSource = 5; + kVisualDisplayFault = 6; + kAudioOutputFault = 7; + kUserInterfaceFault = 8; + kNonVolatileMemoryError = 9; + kTamperDetected = 10; + } + + enum InterfaceTypeEnum : enum8 { + kUnspecified = 0; + kWiFi = 1; + kEthernet = 2; + kCellular = 3; + kThread = 4; + } + + enum NetworkFaultEnum : enum8 { + kUnspecified = 0; + kHardwareFailure = 1; + kNetworkJammed = 2; + kConnectionFailed = 3; + } + + enum RadioFaultEnum : enum8 { + kUnspecified = 0; + kWiFiFault = 1; + kCellularFault = 2; + kThreadFault = 3; + kNFCFault = 4; + kBLEFault = 5; + kEthernetFault = 6; + } + + bitmap Feature : bitmap32 { + kDataModelTest = 0x1; + } + + struct NetworkInterface { + char_string<32> name = 0; + boolean isOperational = 1; + nullable boolean offPremiseServicesReachableIPv4 = 2; + nullable boolean offPremiseServicesReachableIPv6 = 3; + octet_string<8> hardwareAddress = 4; + octet_string IPv4Addresses[] = 5; + octet_string IPv6Addresses[] = 6; + InterfaceTypeEnum type = 7; + } + + critical event HardwareFaultChange = 0 { + HardwareFaultEnum current[] = 0; + HardwareFaultEnum previous[] = 1; + } + + critical event RadioFaultChange = 1 { + RadioFaultEnum current[] = 0; + RadioFaultEnum previous[] = 1; + } + + critical event NetworkFaultChange = 2 { + NetworkFaultEnum current[] = 0; + NetworkFaultEnum previous[] = 1; + } + + critical event BootReason = 3 { + BootReasonEnum bootReason = 0; + } + + readonly attribute NetworkInterface networkInterfaces[] = 0; + readonly attribute int16u rebootCount = 1; + readonly attribute optional int64u upTime = 2; + readonly attribute optional int32u totalOperationalHours = 3; + readonly attribute optional BootReasonEnum bootReason = 4; + readonly attribute optional HardwareFaultEnum activeHardwareFaults[] = 5; + readonly attribute optional RadioFaultEnum activeRadioFaults[] = 6; + readonly attribute optional NetworkFaultEnum activeNetworkFaults[] = 7; + readonly attribute boolean testEventTriggersEnabled = 8; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct TestEventTriggerRequest { + octet_string<16> enableKey = 0; + int64u eventTrigger = 1; + } + + response struct TimeSnapshotResponse = 2 { + systime_ms systemTimeMs = 0; + nullable posix_ms posixTimeMs = 1; + } + + request struct PayloadTestRequestRequest { + octet_string<16> enableKey = 0; + int8u value = 1; + int16u count = 2; + } + + response struct PayloadTestResponse = 4 { + octet_string payload = 0; + } + + /** Provide a means for certification tests to trigger some test-plan-specific events */ + command access(invoke: manage) TestEventTrigger(TestEventTriggerRequest): DefaultSuccess = 0; + /** Take a snapshot of system time and epoch time. */ + command TimeSnapshot(): TimeSnapshotResponse = 1; + /** Request a variable length payload response. */ + command access(invoke: manage) PayloadTestRequest(PayloadTestRequestRequest): PayloadTestResponse = 3; +} + +/** The Software Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ +cluster SoftwareDiagnostics = 52 { + revision 1; // NOTE: Default/not specifically set + + bitmap Feature : bitmap32 { + kWatermarks = 0x1; + } + + struct ThreadMetricsStruct { + int64u id = 0; + optional char_string<8> name = 1; + optional int32u stackFreeCurrent = 2; + optional int32u stackFreeMinimum = 3; + optional int32u stackSize = 4; + } + + info event SoftwareFault = 0 { + int64u id = 0; + optional char_string name = 1; + optional octet_string faultRecording = 2; + } + + readonly attribute optional ThreadMetricsStruct threadMetrics[] = 0; + readonly attribute optional int64u currentHeapFree = 1; + readonly attribute optional int64u currentHeapUsed = 2; + readonly attribute optional int64u currentHeapHighWatermark = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + /** Reception of this command SHALL reset the values: The StackFreeMinimum field of the ThreadMetrics attribute, CurrentHeapHighWaterMark attribute. */ + command access(invoke: manage) ResetWatermarks(): DefaultSuccess = 0; +} + +/** The Thread Network Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems */ +cluster ThreadNetworkDiagnostics = 53 { + revision 2; + + enum ConnectionStatusEnum : enum8 { + kConnected = 0; + kNotConnected = 1; + } + + enum NetworkFaultEnum : enum8 { + kUnspecified = 0; + kLinkDown = 1; + kHardwareFailure = 2; + kNetworkJammed = 3; + } + + enum RoutingRoleEnum : enum8 { + kUnspecified = 0; + kUnassigned = 1; + kSleepyEndDevice = 2; + kEndDevice = 3; + kREED = 4; + kRouter = 5; + kLeader = 6; + } + + bitmap Feature : bitmap32 { + kPacketCounts = 0x1; + kErrorCounts = 0x2; + kMLECounts = 0x4; + kMACCounts = 0x8; + } + + struct NeighborTableStruct { + int64u extAddress = 0; + int32u age = 1; + int16u rloc16 = 2; + int32u linkFrameCounter = 3; + int32u mleFrameCounter = 4; + int8u lqi = 5; + nullable int8s averageRssi = 6; + nullable int8s lastRssi = 7; + int8u frameErrorRate = 8; + int8u messageErrorRate = 9; + boolean rxOnWhenIdle = 10; + boolean fullThreadDevice = 11; + boolean fullNetworkData = 12; + boolean isChild = 13; + } + + struct OperationalDatasetComponents { + boolean activeTimestampPresent = 0; + boolean pendingTimestampPresent = 1; + boolean masterKeyPresent = 2; + boolean networkNamePresent = 3; + boolean extendedPanIdPresent = 4; + boolean meshLocalPrefixPresent = 5; + boolean delayPresent = 6; + boolean panIdPresent = 7; + boolean channelPresent = 8; + boolean pskcPresent = 9; + boolean securityPolicyPresent = 10; + boolean channelMaskPresent = 11; + } + + struct RouteTableStruct { + int64u extAddress = 0; + int16u rloc16 = 1; + int8u routerId = 2; + int8u nextHop = 3; + int8u pathCost = 4; + int8u LQIIn = 5; + int8u LQIOut = 6; + int8u age = 7; + boolean allocated = 8; + boolean linkEstablished = 9; + } + + struct SecurityPolicy { + int16u rotationTime = 0; + int16u flags = 1; + } + + info event ConnectionStatus = 0 { + ConnectionStatusEnum connectionStatus = 0; + } + + info event NetworkFaultChange = 1 { + NetworkFaultEnum current[] = 0; + NetworkFaultEnum previous[] = 1; + } + + readonly attribute nullable int16u channel = 0; + readonly attribute nullable RoutingRoleEnum routingRole = 1; + readonly attribute nullable char_string<16> networkName = 2; + readonly attribute nullable int16u panId = 3; + readonly attribute nullable int64u extendedPanId = 4; + readonly attribute nullable octet_string<17> meshLocalPrefix = 5; + readonly attribute optional int64u overrunCount = 6; + readonly attribute NeighborTableStruct neighborTable[] = 7; + readonly attribute RouteTableStruct routeTable[] = 8; + readonly attribute nullable int32u partitionId = 9; + readonly attribute nullable int16u weighting = 10; + readonly attribute nullable int16u dataVersion = 11; + readonly attribute nullable int16u stableDataVersion = 12; + readonly attribute nullable int8u leaderRouterId = 13; + readonly attribute optional int16u detachedRoleCount = 14; + readonly attribute optional int16u childRoleCount = 15; + readonly attribute optional int16u routerRoleCount = 16; + readonly attribute optional int16u leaderRoleCount = 17; + readonly attribute optional int16u attachAttemptCount = 18; + readonly attribute optional int16u partitionIdChangeCount = 19; + readonly attribute optional int16u betterPartitionAttachAttemptCount = 20; + readonly attribute optional int16u parentChangeCount = 21; + readonly attribute optional int32u txTotalCount = 22; + readonly attribute optional int32u txUnicastCount = 23; + readonly attribute optional int32u txBroadcastCount = 24; + readonly attribute optional int32u txAckRequestedCount = 25; + readonly attribute optional int32u txAckedCount = 26; + readonly attribute optional int32u txNoAckRequestedCount = 27; + readonly attribute optional int32u txDataCount = 28; + readonly attribute optional int32u txDataPollCount = 29; + readonly attribute optional int32u txBeaconCount = 30; + readonly attribute optional int32u txBeaconRequestCount = 31; + readonly attribute optional int32u txOtherCount = 32; + readonly attribute optional int32u txRetryCount = 33; + readonly attribute optional int32u txDirectMaxRetryExpiryCount = 34; + readonly attribute optional int32u txIndirectMaxRetryExpiryCount = 35; + readonly attribute optional int32u txErrCcaCount = 36; + readonly attribute optional int32u txErrAbortCount = 37; + readonly attribute optional int32u txErrBusyChannelCount = 38; + readonly attribute optional int32u rxTotalCount = 39; + readonly attribute optional int32u rxUnicastCount = 40; + readonly attribute optional int32u rxBroadcastCount = 41; + readonly attribute optional int32u rxDataCount = 42; + readonly attribute optional int32u rxDataPollCount = 43; + readonly attribute optional int32u rxBeaconCount = 44; + readonly attribute optional int32u rxBeaconRequestCount = 45; + readonly attribute optional int32u rxOtherCount = 46; + readonly attribute optional int32u rxAddressFilteredCount = 47; + readonly attribute optional int32u rxDestAddrFilteredCount = 48; + readonly attribute optional int32u rxDuplicatedCount = 49; + readonly attribute optional int32u rxErrNoFrameCount = 50; + readonly attribute optional int32u rxErrUnknownNeighborCount = 51; + readonly attribute optional int32u rxErrInvalidSrcAddrCount = 52; + readonly attribute optional int32u rxErrSecCount = 53; + readonly attribute optional int32u rxErrFcsCount = 54; + readonly attribute optional int32u rxErrOtherCount = 55; + readonly attribute optional nullable int64u activeTimestamp = 56; + readonly attribute optional nullable int64u pendingTimestamp = 57; + readonly attribute optional nullable int32u delay = 58; + readonly attribute nullable SecurityPolicy securityPolicy = 59; + readonly attribute nullable octet_string<4> channelPage0Mask = 60; + readonly attribute nullable OperationalDatasetComponents operationalDatasetComponents = 61; + readonly attribute NetworkFaultEnum activeNetworkFaultsList[] = 62; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + /** Reception of this command SHALL reset the OverrunCount attributes to 0 */ + command access(invoke: manage) ResetCounts(): DefaultSuccess = 0; +} + +/** Commands to trigger a Node to allow a new Administrator to commission it. */ +cluster AdministratorCommissioning = 60 { + revision 1; // NOTE: Default/not specifically set + + enum CommissioningWindowStatusEnum : enum8 { + kWindowNotOpen = 0; + kEnhancedWindowOpen = 1; + kBasicWindowOpen = 2; + } + + enum StatusCode : enum8 { + kBusy = 2; + kPAKEParameterError = 3; + kWindowNotOpen = 4; + } + + bitmap Feature : bitmap32 { + kBasic = 0x1; + } + + readonly attribute CommissioningWindowStatusEnum windowStatus = 0; + readonly attribute nullable fabric_idx adminFabricIndex = 1; + readonly attribute nullable vendor_id adminVendorId = 2; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct OpenCommissioningWindowRequest { + int16u commissioningTimeout = 0; + octet_string PAKEPasscodeVerifier = 1; + int16u discriminator = 2; + int32u iterations = 3; + octet_string<32> salt = 4; + } + + request struct OpenBasicCommissioningWindowRequest { + int16u commissioningTimeout = 0; + } + + /** This command is used by a current Administrator to instruct a Node to go into commissioning mode using enhanced commissioning method. */ + timed command access(invoke: administer) OpenCommissioningWindow(OpenCommissioningWindowRequest): DefaultSuccess = 0; + /** This command is used by a current Administrator to instruct a Node to go into commissioning mode using basic commissioning method, if the node supports it. */ + timed command access(invoke: administer) OpenBasicCommissioningWindow(OpenBasicCommissioningWindowRequest): DefaultSuccess = 1; + /** This command is used by a current Administrator to instruct a Node to revoke any active Open Commissioning Window or Open Basic Commissioning Window command. */ + timed command access(invoke: administer) RevokeCommissioning(): DefaultSuccess = 2; +} + +/** This cluster is used to add or remove Operational Credentials on a Commissionee or Node, as well as manage the associated Fabrics. */ +cluster OperationalCredentials = 62 { + revision 1; // NOTE: Default/not specifically set + + enum CertificateChainTypeEnum : enum8 { + kDACCertificate = 1; + kPAICertificate = 2; + } + + enum NodeOperationalCertStatusEnum : enum8 { + kOK = 0; + kInvalidPublicKey = 1; + kInvalidNodeOpId = 2; + kInvalidNOC = 3; + kMissingCsr = 4; + kTableFull = 5; + kInvalidAdminSubject = 6; + kFabricConflict = 9; + kLabelConflict = 10; + kInvalidFabricIndex = 11; + } + + fabric_scoped struct FabricDescriptorStruct { + octet_string<65> rootPublicKey = 1; + vendor_id vendorID = 2; + fabric_id fabricID = 3; + node_id nodeID = 4; + char_string<32> label = 5; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct NOCStruct { + fabric_sensitive octet_string noc = 1; + nullable fabric_sensitive octet_string icac = 2; + fabric_idx fabricIndex = 254; + } + + readonly attribute access(read: administer) NOCStruct NOCs[] = 0; + readonly attribute FabricDescriptorStruct fabrics[] = 1; + readonly attribute int8u supportedFabrics = 2; + readonly attribute int8u commissionedFabrics = 3; + readonly attribute octet_string trustedRootCertificates[] = 4; + readonly attribute int8u currentFabricIndex = 5; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct AttestationRequestRequest { + octet_string<32> attestationNonce = 0; + } + + response struct AttestationResponse = 1 { + octet_string<900> attestationElements = 0; + octet_string<64> attestationSignature = 1; + } + + request struct CertificateChainRequestRequest { + CertificateChainTypeEnum certificateType = 0; + } + + response struct CertificateChainResponse = 3 { + octet_string<600> certificate = 0; + } + + request struct CSRRequestRequest { + octet_string<32> CSRNonce = 0; + optional boolean isForUpdateNOC = 1; + } + + response struct CSRResponse = 5 { + octet_string NOCSRElements = 0; + octet_string attestationSignature = 1; + } + + request struct AddNOCRequest { + octet_string<400> NOCValue = 0; + optional octet_string<400> ICACValue = 1; + octet_string<16> IPKValue = 2; + int64u caseAdminSubject = 3; + vendor_id adminVendorId = 4; + } + + request struct UpdateNOCRequest { + octet_string NOCValue = 0; + optional octet_string ICACValue = 1; + } + + response struct NOCResponse = 8 { + NodeOperationalCertStatusEnum statusCode = 0; + optional fabric_idx fabricIndex = 1; + optional char_string<128> debugText = 2; + } + + request struct UpdateFabricLabelRequest { + char_string<32> label = 0; + } + + request struct RemoveFabricRequest { + fabric_idx fabricIndex = 0; + } + + request struct AddTrustedRootCertificateRequest { + octet_string rootCACertificate = 0; + } + + /** Sender is requesting attestation information from the receiver. */ + command access(invoke: administer) AttestationRequest(AttestationRequestRequest): AttestationResponse = 0; + /** Sender is requesting a device attestation certificate from the receiver. */ + command access(invoke: administer) CertificateChainRequest(CertificateChainRequestRequest): CertificateChainResponse = 2; + /** Sender is requesting a certificate signing request (CSR) from the receiver. */ + command access(invoke: administer) CSRRequest(CSRRequestRequest): CSRResponse = 4; + /** Sender is requesting to add the new node operational certificates. */ + command access(invoke: administer) AddNOC(AddNOCRequest): NOCResponse = 6; + /** Sender is requesting to update the node operational certificates. */ + fabric command access(invoke: administer) UpdateNOC(UpdateNOCRequest): NOCResponse = 7; + /** This command SHALL be used by an Administrative Node to set the user-visible Label field for a given Fabric, as reflected by entries in the Fabrics attribute. */ + fabric command access(invoke: administer) UpdateFabricLabel(UpdateFabricLabelRequest): NOCResponse = 9; + /** This command is used by Administrative Nodes to remove a given fabric index and delete all associated fabric-scoped data. */ + command access(invoke: administer) RemoveFabric(RemoveFabricRequest): NOCResponse = 10; + /** This command SHALL add a Trusted Root CA Certificate, provided as its CHIP Certificate representation. */ + command access(invoke: administer) AddTrustedRootCertificate(AddTrustedRootCertificateRequest): DefaultSuccess = 11; +} + +/** The Group Key Management Cluster is the mechanism by which group keys are managed. */ +cluster GroupKeyManagement = 63 { + revision 1; // NOTE: Default/not specifically set + + enum GroupKeySecurityPolicyEnum : enum8 { + kTrustFirst = 0; + kCacheAndSync = 1; + } + + bitmap Feature : bitmap32 { + kCacheAndSync = 0x1; + } + + fabric_scoped struct GroupInfoMapStruct { + group_id groupId = 1; + endpoint_no endpoints[] = 2; + optional char_string<16> groupName = 3; + fabric_idx fabricIndex = 254; + } + + fabric_scoped struct GroupKeyMapStruct { + group_id groupId = 1; + int16u groupKeySetID = 2; + fabric_idx fabricIndex = 254; + } + + struct GroupKeySetStruct { + int16u groupKeySetID = 0; + GroupKeySecurityPolicyEnum groupKeySecurityPolicy = 1; + nullable octet_string<16> epochKey0 = 2; + nullable epoch_us epochStartTime0 = 3; + nullable octet_string<16> epochKey1 = 4; + nullable epoch_us epochStartTime1 = 5; + nullable octet_string<16> epochKey2 = 6; + nullable epoch_us epochStartTime2 = 7; + } + + attribute access(write: manage) GroupKeyMapStruct groupKeyMap[] = 0; + readonly attribute GroupInfoMapStruct groupTable[] = 1; + readonly attribute int16u maxGroupsPerFabric = 2; + readonly attribute int16u maxGroupKeysPerFabric = 3; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct KeySetWriteRequest { + GroupKeySetStruct groupKeySet = 0; + } + + request struct KeySetReadRequest { + int16u groupKeySetID = 0; + } + + response struct KeySetReadResponse = 2 { + GroupKeySetStruct groupKeySet = 0; + } + + request struct KeySetRemoveRequest { + int16u groupKeySetID = 0; + } + + response struct KeySetReadAllIndicesResponse = 5 { + int16u groupKeySetIDs[] = 0; + } + + /** Write a new set of keys for the given key set id. */ + fabric command access(invoke: administer) KeySetWrite(KeySetWriteRequest): DefaultSuccess = 0; + /** Read the keys for a given key set id. */ + fabric command access(invoke: administer) KeySetRead(KeySetReadRequest): KeySetReadResponse = 1; + /** Revoke a Root Key from a Group */ + fabric command access(invoke: administer) KeySetRemove(KeySetRemoveRequest): DefaultSuccess = 3; + /** Return the list of Group Key Sets associated with the accessing fabric */ + fabric command access(invoke: administer) KeySetReadAllIndices(): KeySetReadAllIndicesResponse = 4; +} + +/** The Fixed Label Cluster provides a feature for the device to tag an endpoint with zero or more read only +labels. */ +cluster FixedLabel = 64 { + revision 1; // NOTE: Default/not specifically set + + struct LabelStruct { + char_string<16> label = 0; + char_string<16> value = 1; + } + + readonly attribute LabelStruct labelList[] = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** The User Label Cluster provides a feature to tag an endpoint with zero or more labels. */ +cluster UserLabel = 65 { + revision 1; // NOTE: Default/not specifically set + + struct LabelStruct { + char_string<16> label = 0; + char_string<16> value = 1; + } + + attribute access(write: manage) LabelStruct labelList[] = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** This cluster provides an interface to a boolean state called StateValue. */ +cluster BooleanState = 69 { + revision 1; + + info event StateChange = 0 { + boolean stateValue = 0; + } + + readonly attribute boolean stateValue = 0; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +/** Allows servers to ensure that listed clients are notified when a server is available for communication. */ +cluster IcdManagement = 70 { + revision 3; + + enum ClientTypeEnum : enum8 { + kPermanent = 0; + kEphemeral = 1; + } + + enum OperatingModeEnum : enum8 { + kSIT = 0; + kLIT = 1; + } + + bitmap Feature : bitmap32 { + kCheckInProtocolSupport = 0x1; + kUserActiveModeTrigger = 0x2; + kLongIdleTimeSupport = 0x4; + kDynamicSitLitSupport = 0x8; + } + + bitmap UserActiveModeTriggerBitmap : bitmap32 { + kPowerCycle = 0x1; + kSettingsMenu = 0x2; + kCustomInstruction = 0x4; + kDeviceManual = 0x8; + kActuateSensor = 0x10; + kActuateSensorSeconds = 0x20; + kActuateSensorTimes = 0x40; + kActuateSensorLightsBlink = 0x80; + kResetButton = 0x100; + kResetButtonLightsBlink = 0x200; + kResetButtonSeconds = 0x400; + kResetButtonTimes = 0x800; + kSetupButton = 0x1000; + kSetupButtonSeconds = 0x2000; + kSetupButtonLightsBlink = 0x4000; + kSetupButtonTimes = 0x8000; + kAppDefinedButton = 0x10000; + } + + fabric_scoped struct MonitoringRegistrationStruct { + fabric_sensitive node_id checkInNodeID = 1; + fabric_sensitive int64u monitoredSubject = 2; + fabric_sensitive ClientTypeEnum clientType = 4; + fabric_idx fabricIndex = 254; + } + + readonly attribute int32u idleModeDuration = 0; + readonly attribute int32u activeModeDuration = 1; + readonly attribute int16u activeModeThreshold = 2; + readonly attribute access(read: administer) optional MonitoringRegistrationStruct registeredClients[] = 3; + readonly attribute access(read: administer) optional int32u ICDCounter = 4; + readonly attribute optional int16u clientsSupportedPerFabric = 5; + readonly attribute optional UserActiveModeTriggerBitmap userActiveModeTriggerHint = 6; + readonly attribute optional char_string<128> userActiveModeTriggerInstruction = 7; + readonly attribute optional OperatingModeEnum operatingMode = 8; + readonly attribute optional int32u maximumCheckInBackOff = 9; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct RegisterClientRequest { + node_id checkInNodeID = 0; + int64u monitoredSubject = 1; + octet_string<16> key = 2; + optional octet_string<16> verificationKey = 3; + ClientTypeEnum clientType = 4; + } + + response struct RegisterClientResponse = 1 { + int32u ICDCounter = 0; + } + + request struct UnregisterClientRequest { + node_id checkInNodeID = 0; + optional octet_string<16> verificationKey = 1; + } + + request struct StayActiveRequestRequest { + int32u stayActiveDuration = 0; + } + + response struct StayActiveResponse = 4 { + int32u promisedActiveDuration = 0; + } + + /** Register a client to the end device */ + fabric command access(invoke: manage) RegisterClient(RegisterClientRequest): RegisterClientResponse = 0; + /** Unregister a client from an end device */ + fabric command access(invoke: manage) UnregisterClient(UnregisterClientRequest): DefaultSuccess = 2; + /** Request the end device to stay in Active Mode for an additional ActiveModeThreshold */ + command access(invoke: manage) StayActiveRequest(StayActiveRequestRequest): StayActiveResponse = 3; +} + +/** The server cluster provides an interface to occupancy sensing functionality based on one or more sensing modalities, including configuration and provision of notifications of occupancy status. */ +cluster OccupancySensing = 1030 { + revision 5; + + enum OccupancySensorTypeEnum : enum8 { + kPIR = 0; + kUltrasonic = 1; + kPIRAndUltrasonic = 2; + kPhysicalContact = 3; + } + + bitmap Feature : bitmap32 { + kOther = 0x1; + kPassiveInfrared = 0x2; + kUltrasonic = 0x4; + kPhysicalContact = 0x8; + kActiveInfrared = 0x10; + kRadar = 0x20; + kRFSensing = 0x40; + kVision = 0x80; + } + + bitmap OccupancyBitmap : bitmap8 { + kOccupied = 0x1; + } + + bitmap OccupancySensorTypeBitmap : bitmap8 { + kPIR = 0x1; + kUltrasonic = 0x2; + kPhysicalContact = 0x4; + } + + struct HoldTimeLimitsStruct { + int16u holdTimeMin = 0; + int16u holdTimeMax = 1; + int16u holdTimeDefault = 2; + } + + info event OccupancyChanged = 0 { + OccupancyBitmap occupancy = 0; + } + + readonly attribute OccupancyBitmap occupancy = 0; + readonly attribute OccupancySensorTypeEnum occupancySensorType = 1; + readonly attribute OccupancySensorTypeBitmap occupancySensorTypeBitmap = 2; + attribute access(write: manage) optional int16u holdTime = 3; + readonly attribute optional HoldTimeLimitsStruct holdTimeLimits = 4; + attribute access(write: manage) optional int16u PIROccupiedToUnoccupiedDelay = 16; + attribute access(write: manage) optional int16u PIRUnoccupiedToOccupiedDelay = 17; + attribute access(write: manage) optional int8u PIRUnoccupiedToOccupiedThreshold = 18; + attribute access(write: manage) optional int16u ultrasonicOccupiedToUnoccupiedDelay = 32; + attribute access(write: manage) optional int16u ultrasonicUnoccupiedToOccupiedDelay = 33; + attribute access(write: manage) optional int8u ultrasonicUnoccupiedToOccupiedThreshold = 34; + attribute access(write: manage) optional int16u physicalContactOccupiedToUnoccupiedDelay = 48; + attribute access(write: manage) optional int16u physicalContactUnoccupiedToOccupiedDelay = 49; + attribute access(write: manage) optional int8u physicalContactUnoccupiedToOccupiedThreshold = 50; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; +} + +endpoint 0 { + device type ma_rootdevice = 22, version 2; + + binding cluster OtaSoftwareUpdateProvider; + + server cluster Groups { + ram attribute nameSupport; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command AddGroup; + handle command AddGroupResponse; + handle command ViewGroup; + handle command ViewGroupResponse; + handle command GetGroupMembership; + handle command GetGroupMembershipResponse; + handle command RemoveGroup; + handle command RemoveGroupResponse; + handle command RemoveAllGroups; + handle command AddGroupIfIdentifying; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster AccessControl { + emits event AccessControlEntryChanged; + emits event AccessControlExtensionChanged; + callback attribute acl; + callback attribute extension; + callback attribute subjectsPerAccessControlEntry; + callback attribute targetsPerAccessControlEntry; + callback attribute accessControlEntriesPerFabric; + callback attribute attributeList; + ram attribute featureMap default = 0; + callback attribute clusterRevision; + } + + server cluster BasicInformation { + emits event StartUp; + emits event ShutDown; + emits event Leave; + callback attribute dataModelRevision; + callback attribute vendorName; + callback attribute vendorID; + callback attribute productName; + callback attribute productID; + persist attribute nodeLabel; + callback attribute location; + callback attribute hardwareVersion; + callback attribute hardwareVersionString; + callback attribute softwareVersion; + callback attribute softwareVersionString; + callback attribute manufacturingDate; + callback attribute partNumber; + callback attribute productURL; + callback attribute productLabel; + callback attribute serialNumber; + persist attribute localConfigDisabled default = 0; + callback attribute uniqueID; + callback attribute capabilityMinima; + callback attribute specificationVersion; + callback attribute maxPathsPerInvoke; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 3; + } + + server cluster OtaSoftwareUpdateRequestor { + emits event StateTransition; + emits event VersionApplied; + emits event DownloadError; + callback attribute defaultOTAProviders; + ram attribute updatePossible default = 1; + ram attribute updateState default = 0; + ram attribute updateStateProgress default = 0; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + + handle command AnnounceOTAProvider; + } + + server cluster LocalizationConfiguration { + ram attribute activeLocale; + callback attribute supportedLocales; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } + + server cluster GeneralCommissioning { + ram attribute breadcrumb default = 0x0000000000000000; + callback attribute basicCommissioningInfo; + callback attribute regulatoryConfig; + callback attribute locationCapability; + callback attribute supportsConcurrentConnection; + ram attribute featureMap default = 6; + ram attribute clusterRevision default = 1; + + handle command ArmFailSafe; + handle command ArmFailSafeResponse; + handle command SetRegulatoryConfig; + handle command SetRegulatoryConfigResponse; + handle command CommissioningComplete; + handle command CommissioningCompleteResponse; + } + + server cluster NetworkCommissioning { + ram attribute maxNetworks; + callback attribute networks; + ram attribute scanMaxTimeSeconds; + ram attribute connectMaxTimeSeconds; + ram attribute interfaceEnabled; + ram attribute lastNetworkingStatus; + ram attribute lastNetworkID; + ram attribute lastConnectErrorValue; + ram attribute featureMap default = 2; + ram attribute clusterRevision default = 1; + + handle command ScanNetworks; + handle command ScanNetworksResponse; + handle command AddOrUpdateWiFiNetwork; + handle command AddOrUpdateThreadNetwork; + handle command RemoveNetwork; + handle command NetworkConfigResponse; + handle command ConnectNetwork; + handle command ConnectNetworkResponse; + handle command ReorderNetwork; + } + + server cluster DiagnosticLogs { + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + + handle command RetrieveLogsRequest; + handle command RetrieveLogsResponse; + } + + server cluster GeneralDiagnostics { + emits event BootReason; + callback attribute networkInterfaces; + callback attribute rebootCount; + callback attribute upTime; + callback attribute totalOperationalHours; + callback attribute bootReason; + callback attribute activeHardwareFaults; + callback attribute activeRadioFaults; + callback attribute activeNetworkFaults; + callback attribute testEventTriggersEnabled default = false; + callback attribute featureMap; + callback attribute clusterRevision; + + handle command TestEventTrigger; + handle command TimeSnapshot; + handle command TimeSnapshotResponse; + } + + server cluster SoftwareDiagnostics { + callback attribute threadMetrics; + callback attribute currentHeapFree; + callback attribute currentHeapUsed; + callback attribute currentHeapHighWatermark; + callback attribute featureMap; + ram attribute clusterRevision default = 1; + + handle command ResetWatermarks; + } + + server cluster ThreadNetworkDiagnostics { + callback attribute channel; + callback attribute routingRole; + callback attribute networkName; + callback attribute panId; + callback attribute extendedPanId; + callback attribute meshLocalPrefix; + callback attribute overrunCount; + callback attribute neighborTable; + callback attribute routeTable; + callback attribute partitionId; + callback attribute weighting; + callback attribute dataVersion; + callback attribute stableDataVersion; + callback attribute leaderRouterId; + callback attribute detachedRoleCount; + callback attribute childRoleCount; + callback attribute routerRoleCount; + callback attribute leaderRoleCount; + callback attribute attachAttemptCount; + callback attribute partitionIdChangeCount; + callback attribute betterPartitionAttachAttemptCount; + callback attribute parentChangeCount; + callback attribute txTotalCount; + callback attribute txUnicastCount; + callback attribute txBroadcastCount; + callback attribute txAckRequestedCount; + callback attribute txAckedCount; + callback attribute txNoAckRequestedCount; + callback attribute txDataCount; + callback attribute txDataPollCount; + callback attribute txBeaconCount; + callback attribute txBeaconRequestCount; + callback attribute txOtherCount; + callback attribute txRetryCount; + callback attribute txDirectMaxRetryExpiryCount; + callback attribute txIndirectMaxRetryExpiryCount; + callback attribute txErrCcaCount; + callback attribute txErrAbortCount; + callback attribute txErrBusyChannelCount; + callback attribute rxTotalCount; + callback attribute rxUnicastCount; + callback attribute rxBroadcastCount; + callback attribute rxDataCount; + callback attribute rxDataPollCount; + callback attribute rxBeaconCount; + callback attribute rxBeaconRequestCount; + callback attribute rxOtherCount; + callback attribute rxAddressFilteredCount; + callback attribute rxDestAddrFilteredCount; + callback attribute rxDuplicatedCount; + callback attribute rxErrNoFrameCount; + callback attribute rxErrUnknownNeighborCount; + callback attribute rxErrInvalidSrcAddrCount; + callback attribute rxErrSecCount; + callback attribute rxErrFcsCount; + callback attribute rxErrOtherCount; + callback attribute activeTimestamp; + callback attribute pendingTimestamp; + callback attribute delay; + callback attribute securityPolicy; + callback attribute channelPage0Mask; + callback attribute operationalDatasetComponents; + callback attribute activeNetworkFaultsList; + ram attribute featureMap default = 0x000F; + ram attribute clusterRevision default = 2; + + handle command ResetCounts; + } + + server cluster AdministratorCommissioning { + callback attribute windowStatus; + callback attribute adminFabricIndex; + callback attribute adminVendorId; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + + handle command OpenCommissioningWindow; + handle command OpenBasicCommissioningWindow; + handle command RevokeCommissioning; + } + + server cluster OperationalCredentials { + callback attribute NOCs; + callback attribute fabrics; + callback attribute supportedFabrics; + callback attribute commissionedFabrics; + callback attribute trustedRootCertificates; + callback attribute currentFabricIndex; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + + handle command AttestationRequest; + handle command AttestationResponse; + handle command CertificateChainRequest; + handle command CertificateChainResponse; + handle command CSRRequest; + handle command CSRResponse; + handle command AddNOC; + handle command UpdateNOC; + handle command NOCResponse; + handle command UpdateFabricLabel; + handle command RemoveFabric; + handle command AddTrustedRootCertificate; + } + + server cluster GroupKeyManagement { + callback attribute groupKeyMap; + callback attribute groupTable; + callback attribute maxGroupsPerFabric; + callback attribute maxGroupKeysPerFabric; + callback attribute featureMap; + callback attribute clusterRevision; + + handle command KeySetWrite; + handle command KeySetRead; + handle command KeySetReadResponse; + handle command KeySetRemove; + handle command KeySetReadAllIndices; + handle command KeySetReadAllIndicesResponse; + } + + server cluster FixedLabel { + callback attribute labelList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } + + server cluster UserLabel { + callback attribute labelList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } + + server cluster IcdManagement { + callback attribute idleModeDuration; + callback attribute activeModeDuration; + callback attribute activeModeThreshold; + callback attribute registeredClients; + callback attribute ICDCounter; + callback attribute clientsSupportedPerFabric; + ram attribute userActiveModeTriggerHint default = 0x100; + ram attribute userActiveModeTriggerInstruction default = "Push setup button for Active Mode"; + ram attribute operatingMode default = 0; + callback attribute maximumCheckInBackOff; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0x000f; + ram attribute clusterRevision default = 3; + + handle command RegisterClient; + handle command RegisterClientResponse; + handle command UnregisterClient; + handle command StayActiveRequest; + handle command StayActiveResponse; + } +} +endpoint 1 { + device type ma_contactsensor = 21, version 1; + + + server cluster Identify { + ram attribute identifyTime default = 0x0000; + ram attribute identifyType default = 0x0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command Identify; + handle command TriggerEffect; + } + + server cluster Descriptor { + callback attribute deviceTypeList; + callback attribute serverList; + callback attribute clientList; + callback attribute partsList; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + callback attribute featureMap; + callback attribute clusterRevision; + } + + server cluster BooleanState { + emits event StateChange; + ram attribute stateValue default = 0; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 1; + } + + server cluster OccupancySensing { + ram attribute occupancy; + ram attribute occupancySensorType; + ram attribute occupancySensorTypeBitmap; + callback attribute featureMap; + ram attribute clusterRevision default = 5; + } +} + + diff --git a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap new file mode 100644 index 00000000000000..bce092c500a726 --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap @@ -0,0 +1,4518 @@ +{ + "fileFormat": 2, + "featureLevel": 104, + "creator": "zap", + "keyValuePairs": [ + { + "key": "commandDiscovery", + "value": "1" + }, + { + "key": "defaultResponsePolicy", + "value": "always" + }, + { + "key": "manufacturerCodes", + "value": "0x1002" + } + ], + "package": [ + { + "pathRelativity": "relativeToZap", + "path": "../../../../src/app/zap-templates/zcl/zcl.json", + "type": "zcl-properties", + "category": "matter", + "version": 1, + "description": "Matter SDK ZCL data" + }, + { + "pathRelativity": "relativeToZap", + "path": "../../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "category": "matter", + "version": "chip-v1" + } + ], + "endpointTypes": [ + { + "id": 1, + "name": "MA-rootdevice", + "deviceTypeRef": { + "code": 22, + "profileId": 259, + "label": "MA-rootdevice", + "name": "MA-rootdevice", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 22, + "profileId": 259, + "label": "MA-rootdevice", + "name": "MA-rootdevice", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 2 + ], + "deviceIdentifiers": [ + 22 + ], + "deviceTypeName": "MA-rootdevice", + "deviceTypeCode": 22, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Groups", + "code": 4, + "mfgCode": null, + "define": "GROUPS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "AddGroup", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddGroupResponse", + "code": 0, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ViewGroup", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ViewGroupResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "GetGroupMembership", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "GetGroupMembershipResponse", + "code": 2, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "RemoveGroup", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RemoveGroupResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "RemoveAllGroups", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddGroupIfIdentifying", + "code": 5, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "NameSupport", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "NameSupportBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Access Control", + "code": 31, + "mfgCode": null, + "define": "ACCESS_CONTROL_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "ACL", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Extension", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SubjectsPerAccessControlEntry", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TargetsPerAccessControlEntry", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AccessControlEntriesPerFabric", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "AccessControlEntryChanged", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "AccessControlExtensionChanged", + "code": 1, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Basic Information", + "code": 40, + "mfgCode": null, + "define": "BASIC_INFORMATION_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DataModelRevision", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "VendorName", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "VendorID", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "vendor_id", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductName", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductID", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "NodeLabel", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "NVM", + "singleton": 1, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "Location", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "HardwareVersion", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "HardwareVersionString", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SoftwareVersion", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SoftwareVersionString", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ManufacturingDate", + "code": 11, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "PartNumber", + "code": 12, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductURL", + "code": 13, + "mfgCode": null, + "side": "server", + "type": "long_char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ProductLabel", + "code": 14, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SerialNumber", + "code": 15, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "LocalConfigDisabled", + "code": 16, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "NVM", + "singleton": 1, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UniqueID", + "code": 18, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CapabilityMinima", + "code": 19, + "mfgCode": null, + "side": "server", + "type": "CapabilityMinimaStruct", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SpecificationVersion", + "code": 21, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxPathsPerInvoke", + "code": 22, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 1, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 1, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "StartUp", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "ShutDown", + "code": 1, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "Leave", + "code": 2, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "OTA Software Update Provider", + "code": 41, + "mfgCode": null, + "define": "OTA_SOFTWARE_UPDATE_PROVIDER_CLUSTER", + "side": "client", + "enabled": 1, + "commands": [ + { + "name": "QueryImage", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "QueryImageResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ApplyUpdateRequest", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ApplyUpdateResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "NotifyUpdateApplied", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 0, + "isEnabled": 1 + } + ] + }, + { + "name": "OTA Software Update Requestor", + "code": 42, + "mfgCode": null, + "define": "OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "AnnounceOTAProvider", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "DefaultOTAProviders", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "UpdatePossible", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UpdateState", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "UpdateStateEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UpdateStateProgress", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "StateTransition", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "VersionApplied", + "code": 1, + "mfgCode": null, + "side": "server", + "included": 1 + }, + { + "name": "DownloadError", + "code": 2, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Localization Configuration", + "code": 43, + "mfgCode": null, + "define": "LOCALIZATION_CONFIGURATION_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "ActiveLocale", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SupportedLocales", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "General Commissioning", + "code": 48, + "mfgCode": null, + "define": "GENERAL_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ArmFailSafe", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ArmFailSafeResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "SetRegulatoryConfig", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "SetRegulatoryConfigResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CommissioningComplete", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CommissioningCompleteResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "Breadcrumb", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0000000000000000", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "BasicCommissioningInfo", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "BasicCommissioningInfo", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RegulatoryConfig", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "RegulatoryLocationTypeEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LocationCapability", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "RegulatoryLocationTypeEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SupportsConcurrentConnection", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "6", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Network Commissioning", + "code": 49, + "mfgCode": null, + "define": "NETWORK_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ScanNetworks", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ScanNetworksResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "AddOrUpdateWiFiNetwork", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddOrUpdateThreadNetwork", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RemoveNetwork", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "NetworkConfigResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ConnectNetwork", + "code": 6, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "ConnectNetworkResponse", + "code": 7, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "ReorderNetwork", + "code": 8, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "MaxNetworks", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Networks", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ScanMaxTimeSeconds", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ConnectMaxTimeSeconds", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "InterfaceEnabled", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastNetworkingStatus", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "NetworkCommissioningStatusEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastNetworkID", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "octet_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "LastConnectErrorValue", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "int32s", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Diagnostic Logs", + "code": 50, + "mfgCode": null, + "define": "DIAGNOSTIC_LOGS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "RetrieveLogsRequest", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RetrieveLogsResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "General Diagnostics", + "code": 51, + "mfgCode": null, + "define": "GENERAL_DIAGNOSTICS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "TestEventTrigger", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TimeSnapshot", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TimeSnapshotResponse", + "code": 2, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "NetworkInterfaces", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RebootCount", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "UpTime", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TotalOperationalHours", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "BootReason", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "BootReasonEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveHardwareFaults", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveRadioFaults", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveNetworkFaults", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "TestEventTriggersEnabled", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "false", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "BootReason", + "code": 3, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Software Diagnostics", + "code": 52, + "mfgCode": null, + "define": "SOFTWARE_DIAGNOSTICS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ResetWatermarks", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "ThreadMetrics", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapFree", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapUsed", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "CurrentHeapHighWatermark", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Thread Network Diagnostics", + "code": 53, + "mfgCode": null, + "define": "THREAD_NETWORK_DIAGNOSTICS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "ResetCounts", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "Channel", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RoutingRole", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "RoutingRoleEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "NetworkName", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "PanId", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ExtendedPanId", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "MeshLocalPrefix", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "octet_string", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "OverrunCount", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "NeighborTable", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RouteTable", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "PartitionId", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "Weighting", + "code": 10, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "DataVersion", + "code": 11, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "StableDataVersion", + "code": 12, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "LeaderRouterId", + "code": 13, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "DetachedRoleCount", + "code": 14, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ChildRoleCount", + "code": 15, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RouterRoleCount", + "code": 16, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "LeaderRoleCount", + "code": 17, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "AttachAttemptCount", + "code": 18, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "PartitionIdChangeCount", + "code": 19, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "BetterPartitionAttachAttemptCount", + "code": 20, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ParentChangeCount", + "code": 21, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxTotalCount", + "code": 22, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxUnicastCount", + "code": 23, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxBroadcastCount", + "code": 24, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxAckRequestedCount", + "code": 25, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxAckedCount", + "code": 26, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxNoAckRequestedCount", + "code": 27, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxDataCount", + "code": 28, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxDataPollCount", + "code": 29, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxBeaconCount", + "code": 30, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxBeaconRequestCount", + "code": 31, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxOtherCount", + "code": 32, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxRetryCount", + "code": 33, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxDirectMaxRetryExpiryCount", + "code": 34, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxIndirectMaxRetryExpiryCount", + "code": 35, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxErrCcaCount", + "code": 36, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxErrAbortCount", + "code": 37, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TxErrBusyChannelCount", + "code": 38, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxTotalCount", + "code": 39, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxUnicastCount", + "code": 40, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxBroadcastCount", + "code": 41, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxDataCount", + "code": 42, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxDataPollCount", + "code": 43, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxBeaconCount", + "code": 44, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxBeaconRequestCount", + "code": 45, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxOtherCount", + "code": 46, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxAddressFilteredCount", + "code": 47, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxDestAddrFilteredCount", + "code": 48, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxDuplicatedCount", + "code": 49, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrNoFrameCount", + "code": 50, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrUnknownNeighborCount", + "code": 51, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrInvalidSrcAddrCount", + "code": 52, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrSecCount", + "code": 53, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrFcsCount", + "code": 54, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "RxErrOtherCount", + "code": 55, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ActiveTimestamp", + "code": 56, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PendingTimestamp", + "code": 57, + "mfgCode": null, + "side": "server", + "type": "int64u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Delay", + "code": 58, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "SecurityPolicy", + "code": 59, + "mfgCode": null, + "side": "server", + "type": "SecurityPolicy", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ChannelPage0Mask", + "code": 60, + "mfgCode": null, + "side": "server", + "type": "octet_string", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "OperationalDatasetComponents", + "code": 61, + "mfgCode": null, + "side": "server", + "type": "OperationalDatasetComponents", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "ActiveNetworkFaultsList", + "code": 62, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x000F", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "2", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Administrator Commissioning", + "code": 60, + "mfgCode": null, + "define": "ADMINISTRATOR_COMMISSIONING_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "OpenCommissioningWindow", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "OpenBasicCommissioningWindow", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RevokeCommissioning", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "WindowStatus", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "CommissioningWindowStatusEnum", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AdminFabricIndex", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "fabric_idx", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AdminVendorId", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "vendor_id", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Operational Credentials", + "code": 62, + "mfgCode": null, + "define": "OPERATIONAL_CREDENTIALS_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "AttestationRequest", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AttestationResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CertificateChainRequest", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CertificateChainResponse", + "code": 3, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "CSRRequest", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "CSRResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "AddNOC", + "code": 6, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "UpdateNOC", + "code": 7, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "NOCResponse", + "code": 8, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "UpdateFabricLabel", + "code": 9, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RemoveFabric", + "code": 10, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "AddTrustedRootCertificate", + "code": 11, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "NOCs", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "Fabrics", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "SupportedFabrics", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CommissionedFabrics", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "TrustedRootCertificates", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "CurrentFabricIndex", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int8u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Group Key Management", + "code": 63, + "mfgCode": null, + "define": "GROUP_KEY_MANAGEMENT_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "KeySetWrite", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetRead", + "code": 1, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadResponse", + "code": 2, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "KeySetRemove", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadAllIndices", + "code": 4, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "KeySetReadAllIndicesResponse", + "code": 5, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "GroupKeyMap", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GroupTable", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxGroupsPerFabric", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaxGroupKeysPerFabric", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Fixed Label", + "code": 64, + "mfgCode": null, + "define": "FIXED_LABEL_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "LabelList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "User Label", + "code": 65, + "mfgCode": null, + "define": "USER_LABEL_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "LabelList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "ICD Management", + "code": 70, + "mfgCode": null, + "define": "ICD_MANAGEMENT_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "RegisterClient", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "RegisterClientResponse", + "code": 1, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + }, + { + "name": "UnregisterClient", + "code": 2, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "StayActiveRequest", + "code": 3, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "StayActiveResponse", + "code": 4, + "mfgCode": null, + "source": "server", + "isIncoming": 0, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdleModeDuration", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeDuration", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ActiveModeThreshold", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "RegisteredClients", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ICDCounter", + "code": 4, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientsSupportedPerFabric", + "code": 5, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "UserActiveModeTriggerHint", + "code": 6, + "mfgCode": null, + "side": "server", + "type": "UserActiveModeTriggerBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x100", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "UserActiveModeTriggerInstruction", + "code": 7, + "mfgCode": null, + "side": "server", + "type": "char_string", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "Push setup button for Active Mode", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "OperatingMode", + "code": 8, + "mfgCode": null, + "side": "server", + "type": "OperatingModeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "MaximumCheckInBackOff", + "code": 9, + "mfgCode": null, + "side": "server", + "type": "int32u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x000f", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "3", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + } + ] + }, + { + "id": 2, + "name": "MA-dimmablelight", + "deviceTypeRef": { + "code": 21, + "profileId": 259, + "label": "MA-contactsensor", + "name": "MA-contactsensor", + "deviceTypeOrder": 0 + }, + "deviceTypes": [ + { + "code": 21, + "profileId": 259, + "label": "MA-contactsensor", + "name": "MA-contactsensor", + "deviceTypeOrder": 0 + } + ], + "deviceVersions": [ + 1 + ], + "deviceIdentifiers": [ + 21 + ], + "deviceTypeName": "MA-contactsensor", + "deviceTypeCode": 21, + "deviceTypeProfileId": 259, + "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0000", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + }, + { + "name": "Descriptor", + "code": 29, + "mfgCode": null, + "define": "DESCRIPTOR_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "DeviceTypeList", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ServerList", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClientList", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "PartsList", + "code": 3, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, + { + "name": "Boolean State", + "code": 69, + "mfgCode": null, + "define": "BOOLEAN_STATE_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "StateValue", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "boolean", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "1", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ], + "events": [ + { + "name": "StateChange", + "code": 0, + "mfgCode": null, + "side": "server", + "included": 1 + } + ] + }, + { + "name": "Occupancy Sensing", + "code": 1030, + "mfgCode": null, + "define": "OCCUPANCY_SENSING_CLUSTER", + "side": "server", + "enabled": 1, + "attributes": [ + { + "name": "Occupancy", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "OccupancyBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "OccupancySensorType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "OccupancySensorTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "OccupancySensorTypeBitmap", + "code": 2, + "mfgCode": null, + "side": "server", + "type": "OccupancySensorTypeBitmap", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": null, + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "5", + "reportable": 1, + "minInterval": 0, + "maxInterval": 65344, + "reportableChange": 0 + } + ] + } + ] + } + ], + "endpoints": [ + { + "endpointTypeName": "MA-rootdevice", + "endpointTypeIndex": 0, + "profileId": 259, + "endpointId": 0, + "networkId": 0, + "parentEndpointIdentifier": null + }, + { + "endpointTypeName": "MA-dimmablelight", + "endpointTypeIndex": 1, + "profileId": 259, + "endpointId": 1, + "networkId": 0, + "parentEndpointIdentifier": null + } + ] +} \ No newline at end of file diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index e9c45f338a81ef..c45251824fefbb 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -66,7 +66,7 @@ bl_iot_sdk("sdk") { "${chip_root}/src/platform/bouffalolab/common", ] - freertos_config = "${examples_plat_dir}/bl602/FreeRTOSConfig.h" + freertos_config = "${example_dir}/bl602/FreeRTOSConfig.h" defines = [ "INCLUDE_xSemaphoreGetMutexHolder=1", diff --git a/examples/lighting-app/bouffalolab/bl602/FreeRTOSConfig.h b/examples/lighting-app/bouffalolab/bl602/FreeRTOSConfig.h new file mode 100644 index 00000000000000..ac502b98e094e1 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl602/FreeRTOSConfig.h @@ -0,0 +1,222 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/*************************************************************************** + * # License + * + * The licensor of this software is Silicon Laboratories Inc. Your use of this + * software is governed by the terms of Silicon Labs Master Software License + * Agreement (MSLA) available at + * www.silabs.com/about-us/legal/master-software-license-agreement. This + * software is Third Party Software licensed by Silicon Labs from a third party + * and is governed by the sections of the MSLA applicable to Third Party + * Software and the additional terms set forth below. + * + ******************************************************************************/ +/* + FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#include "platform.h" +#include + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configSUPPORT_STATIC_ALLOCATION 1 + +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 0 +#ifndef configUSE_TICKLESS_IDLE +// Maybe Compile flags is passed by command line +#define configUSE_TICKLESS_IDLE 1 +#endif +#define configCPU_CLOCK_HZ (10 * 1000 * 1000) /*QEMU*/ +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +/* Creating idle task */ +/* -1 -> prvInitialiseNewTask: (subtract 1 to get top of stack) pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 + * ] ); */ +/* -1 -> prvInitialiseNewTask: (subtract 1 in case not matching 8 bytes alignment) pxTopOfStack = ( StackType_t * ) ( ( ( + * portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); */ +/* Running idle task */ +/* -12 -> prvIdleTask: addi sp, sp, -48 */ +/* -16 -> prvIdleTask.xTaskResumeAll: addi sp, sp, -64 */ +/* Here comes an interrupt after prvIdleTask.xTaskResumeAll.vTaskExitCritical */ +/* -30 -> freertos_risc_v_trap_handler: addi sp, sp, -portCONTEXT_SIZE */ +/* -34 -> portasmSAVE_ADDITIONAL_REGISTERS: addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) */ +/* Checking for stack overflow */ +/* 4 -> taskCHECK_FOR_STACK_OVERFLOW: if( ( pulStack[ 0 ] != ulCheckValue ) || ( pulStack[ 1 ] != ulCheckValue ) || ( pulStack[ 2 + * ] != ulCheckValue ) || ( pulStack[ 3 ] != ulCheckValue ) ) */ +#define configMINIMAL_STACK_SIZE ((unsigned short) 114) /* SIZE-1-1-12-16-30-34>=4 */ +#define configTOTAL_HEAP_SIZE ((size_t) 14100) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 2) +#define configTIMER_QUEUE_LENGTH 10 +#define configTIMER_TASK_STACK_DEPTH (configMINIMAL_STACK_SIZE * 4) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Optional functions - most linkers will remove unused functions anyway. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 + +/* Overwrite some of the stack sizes allocated to various test and demo tasks. +Like all task stack sizes, the value is the number of words, not bytes. */ +#define bktBLOCK_TIME_TASK_STACK_SIZE 100 +#define notifyNOTIFIED_TASK_STACK_SIZE 120 +#define priSUSPENDED_RX_TASK_STACK_SIZE 90 +#define tmrTIMER_TEST_TASK_STACK_SIZE 100 +#define ebRENDESVOUS_TEST_TASK_STACK_SIZE 100 +#define ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE 115 +#define genqMUTEX_TEST_TASK_STACK_SIZE 90 +#define genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE 100 +#define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE 90 + +#ifdef __cplusplus +extern "C" void vAssertCalled(void); +#else +extern void vAssertCalled(void); +#endif +/* Stop if an assertion fails. */ +#define configASSERT(x) \ + if ((x) == 0) \ + vAssertCalled() + +#if (configUSE_TICKLESS_IDLE != 0) +#include "portmacro.h" +#ifdef __cplusplus +extern "C" void vApplicationSleep(TickType_t xExpectedIdleTime); +#else +extern void vApplicationSleep(TickType_t xExpectedIdleTime); +#endif +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif + +#endif diff --git a/examples/lighting-app/bouffalolab/bl602/args.gni b/examples/lighting-app/bouffalolab/bl602/args.gni index 0fcb5aac2edc9b..f3965ca63255c4 100644 --- a/examples/lighting-app/bouffalolab/bl602/args.gni +++ b/examples/lighting-app/bouffalolab/bl602/args.gni @@ -25,7 +25,8 @@ pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false -#is_debug = false +# use -Os instead of -Og +is_debug = false pw_build_LINK_DEPS = [ "$dir_pw_assert:impl", diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index d441eb118205bd..9cec7d240e0ff7 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -56,7 +56,6 @@ declare_args() { baudrate = 2000000 enable_cdc_module = false - config_cache_size = 16384 enable_psram = true } @@ -71,7 +70,7 @@ bl_iot_sdk("sdk") { "${chip_root}/src/platform/bouffalolab/common", ] - freertos_config = "${examples_plat_dir}/bl702/FreeRTOSConfig.h" + freertos_config = "${example_dir}/bl702/FreeRTOSConfig.h" defines = [ "INCLUDE_xSemaphoreGetMutexHolder=1", @@ -310,7 +309,6 @@ bouffalolab_executable("lighting_app") { if (chip_print_memory_usage) { ldflags += [ "-Wl,--print-memory-usage", - "-Wl,--defsym=__CACHE_SIZE=${config_cache_size}", "-fstack-usage", ] } diff --git a/examples/lighting-app/bouffalolab/bl702/FreeRTOSConfig.h b/examples/lighting-app/bouffalolab/bl702/FreeRTOSConfig.h new file mode 100644 index 00000000000000..a3a3a78a8b0d2c --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl702/FreeRTOSConfig.h @@ -0,0 +1,194 @@ +/* + FreeRTOS V8.2.3 - Copyright (C) 2015 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#include "platform.h" + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configSUPPORT_STATIC_ALLOCATION 1 + +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 +#define configUSE_TICKLESS_IDLE 1 +#define configCPU_CLOCK_HZ (4000000) /*QEMU*/ +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +/* Creating idle task */ +/* -1 -> prvInitialiseNewTask: (subtract 1 to get top of stack) pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 + * ] ); */ +/* -1 -> prvInitialiseNewTask: (subtract 1 in case not matching 8 bytes alignment) pxTopOfStack = ( StackType_t * ) ( ( ( + * portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); */ +/* Running idle task */ +/* -12 -> prvIdleTask: addi sp, sp, -48 */ +/* -16 -> prvIdleTask.xTaskResumeAll: addi sp, sp, -64 */ +/* Here comes an interrupt after prvIdleTask.xTaskResumeAll.vTaskExitCritical */ +/* -30 -> freertos_risc_v_trap_handler: addi sp, sp, -portCONTEXT_SIZE */ +/* -34 -> portasmSAVE_ADDITIONAL_REGISTERS: addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) */ +/* Checking for stack overflow */ +/* 4 -> taskCHECK_FOR_STACK_OVERFLOW: if( ( pulStack[ 0 ] != ulCheckValue ) || ( pulStack[ 1 ] != ulCheckValue ) || ( pulStack[ 2 + * ] != ulCheckValue ) || ( pulStack[ 3 ] != ulCheckValue ) ) */ +#define configMINIMAL_STACK_SIZE ((unsigned short) 114) /* SIZE-1-1-12-16-30-34>=4 */ +#define configTOTAL_HEAP_SIZE ((size_t) 14100) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH (configMINIMAL_STACK_SIZE * 2) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xSemaphoreGetMutexHolder 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +#ifdef __cplusplus +extern "C" void vAssertCalled(void); +#else +extern void vAssertCalled(void); +#endif +#define configASSERT(x) \ + if ((x) == 0) \ + vAssertCalled() +// #define configASSERT( x ) if( ( x ) == 0 ) portABORT() + +/* Overwrite some of the stack sizes allocated to various test and demo tasks. +Like all task stack sizes, the value is the number of words, not bytes. */ +#define bktBLOCK_TIME_TASK_STACK_SIZE 100 +#define notifyNOTIFIED_TASK_STACK_SIZE 120 +#define priSUSPENDED_RX_TASK_STACK_SIZE 90 +#define tmrTIMER_TEST_TASK_STACK_SIZE 100 +#define ebRENDESVOUS_TEST_TASK_STACK_SIZE 100 +#define ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE 115 +#define genqMUTEX_TEST_TASK_STACK_SIZE 90 +#define genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE 100 +#define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE 90 + +#if (configUSE_TICKLESS_IDLE != 0) +#include "portmacro.h" +#ifdef __cplusplus +extern "C" void vApplicationSleep(TickType_t xExpectedIdleTime); +#else +extern void vApplicationSleep(TickType_t xExpectedIdleTime); +#endif +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif + +#endif /* FREERTOS_CONFIG_H */ diff --git a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn index 036b31479dab05..c004af4134dfc2 100644 --- a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn @@ -55,7 +55,6 @@ declare_args() { module_type = "BL704L" baudrate = 2000000 - config_cache_size = 8192 enable_psram = true } @@ -69,7 +68,7 @@ bl_iot_sdk("sdk") { "${chip_root}/src/platform/bouffalolab/common", ] - freertos_config = "${examples_plat_dir}/bl702l/FreeRTOSConfig.h" + freertos_config = "${example_dir}/bl702l/FreeRTOSConfig.h" defines = [ "INCLUDE_xSemaphoreGetMutexHolder=1", @@ -123,7 +122,7 @@ bouffalolab_executable("lighting_app") { } if ("BL704LDK" == board) { - defines += [ "XT_ZB6_DevKit" ] + defines += [ "BL704LDK" ] } sources = [ @@ -256,7 +255,7 @@ bouffalolab_executable("lighting_app") { if (enable_psram) { defines += [ "CFG_USE_PSRAM=1" ] - ldscript = "${examples_plat_dir}/bl702l/ldscripts/psram_flash_rom.ld" + ldscript = "${examples_plat_dir}/bl702l/ldscripts/psram_flash.ld" } else { ldscript = "${examples_plat_dir}/bl702l/ldscripts/flash_rom.ld" } @@ -272,7 +271,6 @@ bouffalolab_executable("lighting_app") { if (chip_print_memory_usage) { ldflags += [ "-Wl,--print-memory-usage", - "-Wl,--defsym=__CACHE_SIZE=${config_cache_size}", "-fstack-usage", ] } diff --git a/examples/lighting-app/bouffalolab/bl702l/FreeRTOSConfig.h b/examples/lighting-app/bouffalolab/bl702l/FreeRTOSConfig.h new file mode 100644 index 00000000000000..211c471007e947 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl702l/FreeRTOSConfig.h @@ -0,0 +1,182 @@ +/* + FreeRTOS V8.2.3 - Copyright (C) 2015 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#include "platform.h" + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configSUPPORT_STATIC_ALLOCATION 1 + +#define configCLINT_BASE_ADDRESS CLINT_CTRL_ADDR +#define configCLIC_TIMER_ENABLE_ADDRESS (0x02800407) +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 +#define configUSE_TICKLESS_IDLE 1 +#define configCPU_CLOCK_HZ (2000000) /*QEMU*/ +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +/* Creating idle task */ +/* -1 -> prvInitialiseNewTask: (subtract 1 to get top of stack) pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 + * ] ); */ +/* -1 -> prvInitialiseNewTask: (subtract 1 in case not matching 8 bytes alignment) pxTopOfStack = ( StackType_t * ) ( ( ( + * portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); */ +/* Running idle task */ +/* -12 -> prvIdleTask: addi sp, sp, -48 */ +/* -16 -> prvIdleTask.xTaskResumeAll: addi sp, sp, -64 */ +/* Here comes an interrupt after prvIdleTask.xTaskResumeAll.vTaskExitCritical */ +/* -30 -> freertos_risc_v_trap_handler: addi sp, sp, -portCONTEXT_SIZE */ +/* -34 -> portasmSAVE_ADDITIONAL_REGISTERS: addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE * portWORD_SIZE) */ +/* Checking for stack overflow */ +/* 4 -> taskCHECK_FOR_STACK_OVERFLOW: if( ( pulStack[ 0 ] != ulCheckValue ) || ( pulStack[ 1 ] != ulCheckValue ) || ( pulStack[ 2 + * ] != ulCheckValue ) || ( pulStack[ 3 ] != ulCheckValue ) ) */ +#define configMINIMAL_STACK_SIZE ((unsigned short) 256) /* SIZE-1-1-12-16-30-34>=4 */ +#define configTOTAL_HEAP_SIZE ((size_t) 14100) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 0 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH (400) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_xTaskGetHandle 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +#ifdef __cplusplus +extern "C" void vAssertCalled(void); +#else +extern void vAssertCalled(void); +#endif +#define configASSERT(x) \ + if ((x) == 0) \ + vAssertCalled() + +/* Overwrite some of the stack sizes allocated to various test and demo tasks. +Like all task stack sizes, the value is the number of words, not bytes. */ +#define bktBLOCK_TIME_TASK_STACK_SIZE 100 +#define notifyNOTIFIED_TASK_STACK_SIZE 120 +#define priSUSPENDED_RX_TASK_STACK_SIZE 90 +#define tmrTIMER_TEST_TASK_STACK_SIZE 100 +#define ebRENDESVOUS_TEST_TASK_STACK_SIZE 100 +#define ebEVENT_GROUP_SET_BITS_TEST_TASK_STACK_SIZE 115 +#define genqMUTEX_TEST_TASK_STACK_SIZE 90 +#define genqGENERIC_QUEUE_TEST_TASK_STACK_SIZE 100 +#define recmuRECURSIVE_MUTEX_TEST_TASK_STACK_SIZE 90 + +#endif /* FREERTOS_CONFIG_H */ diff --git a/examples/lighting-app/bouffalolab/bl702l/args.gni b/examples/lighting-app/bouffalolab/bl702l/args.gni index 3120af1cce60f6..1a576926abeb16 100644 --- a/examples/lighting-app/bouffalolab/bl702l/args.gni +++ b/examples/lighting-app/bouffalolab/bl702l/args.gni @@ -24,6 +24,8 @@ pw_assert_BACKEND = "$dir_pw_assert_log" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false + +# use -Os instead of -Og is_debug = false pw_build_LINK_DEPS = [ diff --git a/examples/lighting-app/bouffalolab/bl702l/mboard.h b/examples/lighting-app/bouffalolab/bl702l/mboard.h index e83529bc168440..ceb458547e8189 100644 --- a/examples/lighting-app/bouffalolab/bl702l/mboard.h +++ b/examples/lighting-app/bouffalolab/bl702l/mboard.h @@ -66,6 +66,11 @@ #define MAX_PWM_CHANNEL 1 +#elif defined(BL704LDK) +#define LED_PIN_PORT 1 +#define LED_PIN 18 + +#define MAX_PWM_CHANNEL 1 #else #define LED_PIN_PORT 2 diff --git a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld index 98afa0e551f64c..206f89bd077fd3 100644 --- a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld +++ b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld @@ -20,6 +20,7 @@ MEMORY flash (rxai!w) : ORIGIN = 0x23000000, LENGTH = 4M ram_tcm (wxa) : ORIGIN = __RAM_START, LENGTH = __RAM_TCM_LEN ram_wifi (wxa) : ORIGIN = __RAM_START + __RAM_TCM_LEN, LENGTH = __RAM_WIFI_LEN + bugkill (rxai!w) : ORIGIN = 0xD0000000, LENGTH = 16M } SECTIONS @@ -44,7 +45,17 @@ SECTIONS . = ORIGIN(flash) + __RFTLV_SIZE_OFFSET + __RFTLV_SIZE_HOLE; } > flash - .text : + .blverinf 0 : AT (ORIGIN(flash) + 3K) + { + LONG(0x42464c42); /* BLFB */ + LONG(0x46524556); /* VERF */ + KEEP (*component_version.obj(.blverinf)) + LONG(0x42464c42); /* BLFB */ + LONG(0x46524556); /* VERF */ + KEEP (*component_version.obj(.rodata*)) + } + + .text ORIGIN(flash) + 4K: AT(ORIGIN(flash) + 4K) { *(.text.unlikely .text.unlikely.*) *(.text.startup .text.startup.*) @@ -52,8 +63,21 @@ SECTIONS *(.gnu.linkonce.t.*) } > flash + .bugkiller_command : + { + PROVIDE( __bugkiller_command_start = ADDR(.bugkiller_command) ); + PROVIDE( __bugkiller_command_end = ADDR(.bugkiller_command) + SIZEOF(.bugkiller_command) ); + KEEP (*(.static_bugkiller_command)) + } > bugkill + .bugkiller : + { + KEEP (*(.bugkiller_code)) + KEEP (*bugkiller*.o(.rodata* .text* .data* .sdata* .sbss*)) + } > bugkill + .rodata : { + *(.rdata) *(.rodata .rodata.*) *(.sdata2.*) @@ -96,6 +120,12 @@ SECTIONS *(.static_blogpri_code*) _bl_static_blogpri_code_end = .; + /* section information for components's version */ + . = ALIGN(4); + _version_info_section_start = .; + KEEP(*(.version.*)) + _version_info_section_end = .; + *(.gnu.linkonce.r.*) /*Framework table section, use ALIGN here to avoid fill section*/ @@ -198,13 +228,13 @@ SECTIONS .boot2 (NOLOAD) : { - PROVIDE ( __boot2_pt_addr_start = . ); - *(.bss.boot2_partition_table) - PROVIDE ( __boot2_pt_addr_end = . ); + PROVIDE ( __boot2_pt_addr_start = . ); + *(.bss.boot2_partition_table) + PROVIDE ( __boot2_pt_addr_end = . ); - PROVIDE ( __boot2_flashCfg_start = . ); - *(.bss.boot2_flashCfg) - PROVIDE ( __boot2_flashCfg_end = . ); + PROVIDE ( __boot2_flashCfg_start = . ); + *(.bss.boot2_flashCfg) + PROVIDE ( __boot2_flashCfg_end = . ); } > ram_tcm @@ -213,16 +243,11 @@ SECTIONS PROVIDE( __bss_start = ADDR(.bss) ); PROVIDE( __bss_end = ADDR(.bss) + SIZEOF(.bss) ); - *(.sbss) - *(EXCLUDE_FILE(*libCHIP.a:BL602.PlatformManagerImpl.cpp.o) .sbss.*) + *(.sbss*) *(.gnu.linkonce.sb.*) - *(.bss) - *(EXCLUDE_FILE(*libCHIP.a:BL602.PlatformManagerImpl.cpp.o) .bss.*) + *(.bss .bss.*) *(.gnu.linkonce.b.*) - *(EXCLUDE_FILE(*libCHIP.a:BL602.PlatformManagerImpl.cpp.o) COMMON) - - . = ALIGN(4); - *libCHIP.a:BL602.PlatformManagerImpl.cpp.o(.sbss.* .bss.* COMMON) + *(COMMON) } > ram_tcm .stack (NOLOAD) : @@ -260,10 +285,64 @@ SECTIONS PROVIDE( _ld_ram_size2 = LENGTH(ram_wifi) ); PROVIDE( _ld_ram_addr2 = ORIGIN(ram_wifi) ); + /*BOOT2 sections*/ PROVIDE ( __boot2_pt_addr_src = BOOT2_PT_ADDR ); PROVIDE ( __boot2_flashCfg_src = BOOT2_FLASHCFG_ADDR ); + PROVIDE(xTaskGetTickCount = 0x0000000021017694); + PROVIDE(xTaskGetTickCountFromISR = 0x00000000210176aa); + PROVIDE(pvPortMalloc = 0x0000000021019662); + PROVIDE(vPortFree = 0x000000002101973a); + PROVIDE(vTaskNotifyGiveFromISR = 0x00000000210188e8); + PROVIDE(vTaskSwitchContext = 0x0000000021017a04); + PROVIDE(ulTaskNotifyTake = 0x0000000021018548); + PROVIDE(vTaskExitCritical = 0x00000000210183f4); + PROVIDE(vTaskEnterCritical = 0x00000000210183e4); + PROVIDE(xTaskGetCurrentTaskHandle = 0x0000000021018152); + PROVIDE(xQueueSemaphoreTake = 0x0000000021015ce8); + PROVIDE(xQueueGenericSend = 0x0000000021015834); + PROVIDE(xQueueGenericSendFromISR = 0x0000000021015a4c); + PROVIDE(xTaskCreateStatic = 0x00000000210170a2); + PROVIDE(xTaskCreate = 0x000000002101713a); + PROVIDE(xQueueCreateMutex = 0x0000000021015a1c); + PROVIDE(xQueueCreateMutexStatic = 0x0000000021015994); + PROVIDE(vQueueDelete = 0x00000000210161d8); + PROVIDE(xQueueGenericCreateStatic = 0x00000000210156c2); + PROVIDE(xQueueGenericCreate = 0x0000000021015744); + PROVIDE(xQueueReceive = 0x0000000021015b8a); + PROVIDE(uxQueueMessagesWaiting = 0x0000000021016168); + PROVIDE(vTaskDelay = 0x00000000210179c6); + PROVIDE(vTaskDelayUntil = 0x0000000021017952); + PROVIDE(xPortGetFreeHeapSize = 0x00000000210197ce); + PROVIDE(vTaskList = 0x0000000021018408); + PROVIDE(xTimerGenericCommand = 0x0000000021018bec); + PROVIDE(xTimerCreateTimerTask = 0x0000000021018a9e); + PROVIDE(xTimerCreate = 0x0000000021018af6); + PROVIDE(xTimerCreateStatic = 0x0000000021018b66); + PROVIDE(xQueueCreateCountingSemaphoreStatic = 0x00000000210157c2); + PROVIDE(xQueueCreateCountingSemaphore = 0x0000000021015800); + PROVIDE(pTrapNetCounter = __global_pointer_head$); + PROVIDE(TrapNetCounter = __global_pointer_head$ + 0x58); + PROVIDE(vEventGroupDelete = 0x00000000210153be); + PROVIDE(xEventGroupWaitBits = 0x0000000021015086); + PROVIDE(xEventGroupCreateStatic = 0x0000000021015000); + PROVIDE(xEventGroupSetBits = 0x00000000210151e0); + PROVIDE(xStreamBufferGenericCreateStatic = 0x00000000210165c0); + PROVIDE(xStreamBufferReceive = 0x00000000210169ae); + PROVIDE(xStreamBufferSend = 0x00000000210167a8); + PROVIDE(pvTimerGetTimerID = 0x0000000021018fd4); + PROVIDE(xTaskGenericNotify = 0x00000000210186be); + PROVIDE(xTaskGenericNotifyFromISR = 0x00000000210187de); + PROVIDE(xQueueGiveMutexRecursive = 0x00000000210159c8); + PROVIDE(xQueueTakeMutexRecursive = 0x0000000021015e70); + PROVIDE(xTaskGetTickCount2 = 0x000000002101769a); + PROVIDE(xQueueGiveFromISR = 0x0000000021015b0e); + PROVIDE(vTaskDelete = 0x00000000210171b6); + PROVIDE(uxTaskGetStackHighWaterMark = 0x0000000021018110); + PROVIDE(pcTaskGetName = 0x00000000210176b6); + PROVIDE(vTaskStartScheduler = 0x0000000021017610); + PROVIDE(vPortDefineHeapRegions = 0x00000000210197da); PROVIDE(__LD_CONFIG_EM_SEL = __EM_SIZE); PROVIDE( _ld_symbol_rom_framework_audio_device_start = _rom_framework_audio_device_start); diff --git a/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld b/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld index 9bf4d4390b9270..a9ed71746418e8 100644 --- a/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld +++ b/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld @@ -2,24 +2,24 @@ OUTPUT_ARCH( "riscv" ) ENTRY( bl702_start ) -__EM_SIZE = DEFINED(ble_controller_init) ? 8K : 0K; -__OCRAM_BSS_REGION_SIZE = 12K; -__CACHE_SIZE = DEFINED(__CACHE_SIZE) ? __CACHE_SIZE : 16K; +__EM_SIZE = DEFINED(ble_controller_init) ? (DEFINED(em_16k_init) ? 16K : 8K) : 0K; +__CACHE_SIZE = 16K; __stack_size = DEFINED(__stack_size) ? __stack_size : 2K; +__sha_ocram_size = DEFINED(__sha_ocram_size) ? __sha_ocram_size : 128; MEMORY { flash (rxai!w) : ORIGIN = 0x23000000, LENGTH = (2M) - tcm_ocram (wxa) : ORIGIN = 0x42010000 + __CACHE_SIZE, LENGTH = (64K - __CACHE_SIZE + 64K - __OCRAM_BSS_REGION_SIZE - __stack_size - __EM_SIZE) - ocram_bss (wxa) : ORIGIN = ORIGIN(tcm_ocram) + LENGTH(tcm_ocram), LENGTH = __OCRAM_BSS_REGION_SIZE - sys_stack (wxa) : ORIGIN = ORIGIN(tcm_ocram) + LENGTH(tcm_ocram) + __OCRAM_BSS_REGION_SIZE, LENGTH = __stack_size + tcm_ocram (wxa) : ORIGIN = 0x42010000 + __CACHE_SIZE, LENGTH = (64K - __CACHE_SIZE + 64K - __EM_SIZE - __stack_size - __sha_ocram_size) + sys_stack (wxa) : ORIGIN = 0x42030000 - __EM_SIZE - __stack_size - __sha_ocram_size, LENGTH = __stack_size + sha_ocram (wxa) : ORIGIN = 0x42030000 - __EM_SIZE - __sha_ocram_size, LENGTH = __sha_ocram_size hbnram (wxa) : ORIGIN = 0x40010000, LENGTH = (4K) psram (wxa) : ORIGIN = 0x26000000, LENGTH = (2M) + bugkill (rxai!w) : ORIGIN = 0xD0000000, LENGTH = 16M } SECTIONS { - __stack_size = DEFINED(__stack_size) ? __stack_size : 2K; BOOT2_PT_ADDR = 0x4202DC00; .init : @@ -35,6 +35,19 @@ SECTIONS *(.gnu.linkonce.t.*) } >flash + .bugkiller_command : + { + PROVIDE( __bugkiller_command_start = ADDR(.bugkiller_command) ); + PROVIDE( __bugkiller_command_end = ADDR(.bugkiller_command) + SIZEOF(.bugkiller_command) ); + KEEP (*(.static_bugkiller_command)) + } > bugkill + + .bugkiller : + { + KEEP (*(.bugkiller_code)) + KEEP (*bugkiller*.o(.rodata* .text* .data* .sdata* .sbss*)) + } > bugkill + .rodata : { *(.rdata) @@ -77,6 +90,12 @@ SECTIONS *(.static_blogpri_code*) _bl_static_blogpri_code_end = .; + /* section information for components's version */ + . = ALIGN(4); + _version_info_section_start = .; + KEEP(*(.version.*)) + _version_info_section_end = .; + *(.gnu.linkonce.r.*) } >flash @@ -101,7 +120,7 @@ SECTIONS { PROVIDE( _hbn_load = LOADADDR(.hbn) ); PROVIDE( _hbn_run = ADDR(.hbn) ); - PROVIDE( _hbn_run_end = ADDR(.hbn) + SIZEOF(.hbn)); + PROVIDE( _hbn_run_end = ADDR(.hbn) + SIZEOF(.hbn) ); /* put bl702_rf_private.o in hbnram to avoid ocram conflict during rf calibration */ *libbl702_rf.a:bl702_rf_private.o(.retention .retention_noinit) @@ -110,65 +129,60 @@ SECTIONS /* tcm code that should be retentive after hbn wakeup */ *libbl702_std.a:bl702_romapi.o(.tcm_code.* .sclock_rlt_code.*) + *libbl702_std.a:bl702_aon.o(.tcm_code.* .sclock_rlt_code.*) *libbl702_std.a:bl702_glb.o(.tcm_code.* .sclock_rlt_code.*) + *libbl702_std.a:bl702_hbn.o(.tcm_code.* .sclock_rlt_code.*) PROVIDE ( _hbn_restore_tcm_run_end = . ); /* data that should be retentive after hbn wakeup */ *liblmac154.a:*(.sdata.* .srodata.* .sbss.* .bss.* COMMON) *libbl702_std.a:*(.sdata.* .srodata.* .sbss.* .bss.* COMMON) - *libhosal.a:bl_adc.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) *libhosal.a:bl_gpio.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) - *libhosal.a:bl_sys.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) - *libhosal.a:bl_timer.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) + *libhosal.a:hosal_gpio.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) *libhosal.a:bl_uart.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) *libhosal.a:hosal_uart.o(.sdata.* .srodata.* .sbss.* .bss.* COMMON) PROVIDE ( _hbn_restore_data_run_end = . ); + *(.hbn_code.*) *(.hbn_data) *(.retention) - } >hbnram AT > flash + } >hbnram AT >flash .hbn_noinit (NOLOAD) : { *(.hbn_noinit) *(.retention_noinit) - - /* PDS backup address */ - . = ALIGN(4); - PROVIDE ( __ld_pds_bak_addr = . ); - . = . + 256; } >hbnram - .rsvd (NOLOAD) : + .tcmdata (NOLOAD) : { - *(.rsvd_data) - *(.ble_rsvd_mem) - } >hbnram + *(.tcm_data) + } >tcm_ocram .tcmcode : ALIGN(4) { PROVIDE( _tcm_load = LOADADDR(.tcmcode) ); PROVIDE( _tcm_run = ADDR(.tcmcode) ); - PROVIDE( _tcm_run_end = ADDR(.tcmcode) + SIZEOF(.tcmcode)); + PROVIDE( _tcm_run_end = ADDR(.tcmcode) + SIZEOF(.tcmcode) ); *(.tcm_code.*) *(.tcm_const.*) *(.sclock_rlt_code.*) *(.sclock_rlt_const.*) - } >tcm_ocram AT > flash + } >tcm_ocram AT >flash .data : ALIGN(4) { PROVIDE( _data_load = LOADADDR(.data) ); PROVIDE( _data_run = ADDR(.data) ); - PROVIDE( _data_run_end = ADDR(.data) + SIZEOF(.data)); + PROVIDE( _data_run_end = ADDR(.data) + SIZEOF(.data) ); *(.pds_code.*) *(.data .data.*) *(.gnu.linkonce.d.*) . = ALIGN(8); - /*always put freetos under global_pointer with the following order. No change!*/ + /*always put freertos under global_pointer with the following order. No change!*/ PROVIDE( __global_pointer$ = . + 0x7F0 ); KEEP(*libbl702_freertos.a:*(.sdata.*)) KEEP(*libbl702_freertos.a:*(.sbss.*)) @@ -194,7 +208,7 @@ SECTIONS _bt_l2cap_fixed_chan_list_start = .; KEEP(*(SORT_BY_NAME("._bt_l2cap_fixed_chan.static.*"))) _bt_l2cap_fixed_chan_list_end = .; - } >tcm_ocram AT > flash + } >tcm_ocram AT >flash .boot2 (NOLOAD) : { @@ -207,17 +221,6 @@ SECTIONS PROVIDE ( __boot2_flashCfg_end = . ); } >tcm_ocram - .ocram_bss (NOLOAD) : - { - PROVIDE( __ocram_bss_start = ADDR(.ocram_bss) ); - PROVIDE( __ocram_bss_end = ADDR(.ocram_bss) + SIZEOF(.ocram_bss) ); - - *libCHIP.a:BL702.PlatformManagerImpl.cpp.o(.sbss.* .bss.* COMMON) - . = ALIGN(4); - *(.sha_ocram*) - - } > ocram_bss - . = ALIGN(4); PROVIDE( _heap2_start = .); PROVIDE( _heap2_size = ADDR(.stack) - _heap2_start ); @@ -305,15 +308,37 @@ SECTIONS . = ALIGN(8); PROVIDE( _heap_start = . ); - PROVIDE( _heap_size = ADDR(.ocram_bss) - _heap_start ); + PROVIDE( _heap_size = ORIGIN(tcm_ocram) + LENGTH(tcm_ocram) - _heap_start ); + + PROVIDE( _heap2_start = 0 ); + PROVIDE( _heap2_size = 0 ); - .stack (NOLOAD) : + .stack (NOLOAD) : ALIGN(8) { - PROVIDE ( _sp_base = . ); + PROVIDE( _sp_base = . ); . = . + __stack_size; PROVIDE( _sp_main = . ); __freertos_irq_stack_top = .; - } > sys_stack + } >sys_stack + + .sha_ocram (NOLOAD) : + { + *(.sha_ocram*) + } >sha_ocram + + .psram (NOLOAD) : + { + . = ALIGN(16); + PROVIDE( _psram_start = . ); + *(.wifi_ram*) + . = ALIGN(16); + PROVIDE( _psram_end = . ); + } >psram + + . = ALIGN(8); + PROVIDE( _heap3_start = . ); + PROVIDE( _heap3_size = ORIGIN(psram) + LENGTH(psram) - _heap3_start ); + /* camera driver */ PROVIDE( _ld_bl_driver_camera_start = _bl_driver_camera_start ); @@ -334,16 +359,23 @@ SECTIONS /* ram information */ PROVIDE( _ld_ram_size0 = LENGTH(flash) ); PROVIDE( _ld_ram_addr0 = ORIGIN(flash) ); - PROVIDE( _ld_ram_size1 = LENGTH(tcm_ocram) - SIZEOF(.stack) ); + PROVIDE( _ld_ram_size1 = LENGTH(tcm_ocram) ); PROVIDE( _ld_ram_addr1 = ORIGIN(tcm_ocram) ); PROVIDE( _ld_ram_size2 = LENGTH(hbnram) ); PROVIDE( _ld_ram_addr2 = ORIGIN(hbnram) ); PROVIDE( _ld_ram_size3 = SIZEOF(.stack) ); PROVIDE( _ld_ram_addr3 = ADDR(.stack) ); + PROVIDE( _ld_ram_sha_size = LENGTH(sha_ocram) ); + PROVIDE( _ld_ram_sha_addr = ORIGIN(sha_ocram) ); + PROVIDE( _ld_psram_size = LENGTH(psram) ); + PROVIDE( _ld_psram_addr = ORIGIN(psram) ); /* BOOT2 parameter */ - PROVIDE ( __boot2_pt_addr_src = BOOT2_PT_ADDR ); + PROVIDE( __boot2_pt_addr_src = BOOT2_PT_ADDR ); /* EM size */ - PROVIDE(__LD_CONFIG_EM_SEL = __EM_SIZE); + PROVIDE( __LD_CONFIG_EM_SEL = __EM_SIZE ); + + /* BLE_CORE_REG size */ + PROVIDE( __LD_BLE_CORE_REG_SIZE = __EM_SIZE ? 0xA4 : 0 ); } diff --git a/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld b/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld new file mode 100644 index 00000000000000..597d98a4b11658 --- /dev/null +++ b/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld @@ -0,0 +1,318 @@ +OUTPUT_ARCH( "riscv" ) + +ENTRY( bl702_start ) + +__EM_SIZE = DEFINED(btble_controller_init) ? 8K : 0K; +__CACHE_SIZE = 16K; +__stack_size = DEFINED(__stack_size) ? __stack_size : 2K; + +MEMORY +{ + flash (rxai!w) : ORIGIN = 0x23000000, LENGTH = (2M) + tcm_ocram (wxa) : ORIGIN = 0x4201C000 + __CACHE_SIZE, LENGTH = (16K - __CACHE_SIZE + 80K - __EM_SIZE - __stack_size) + sys_stack (wxa) : ORIGIN = 0x42034000 - __EM_SIZE - __stack_size, LENGTH = __stack_size + hbnram (wxa) : ORIGIN = 0x40010000, LENGTH = (4K) + psram (wxa) : ORIGIN = 0x26000000, LENGTH = (2M) +} + +SECTIONS +{ + .init : + { + KEEP (*(SORT_NONE(.init))) + } >flash + + .ver : + { + . = ORIGIN(flash) + 0xC00; + LONG(0x42464c42); /* BLFB */ + LONG(0x46524556); /* VERF */ + KEEP(*(.blverinf)) + } >flash + + .text : + { + *(.text.unlikely .text.unlikely.*) + *(.text.startup .text.startup.*) + *(.text .text.*) + *(.gnu.linkonce.t.*) + } >flash + + .rodata : + { + *(.rdata) + *(.rodata .rodata.*) + *(.sdata2.*) + *(.gcc_except_table.*) + + /* static cli cmds */ + . = ALIGN(4); + _bl_static_cli_cmds_start = .; + KEEP(*(.static_cli_cmds)) + *(.static_cli_cmds) + _bl_static_cli_cmds_end = .; + + /* static blog code1 */ + . = ALIGN(4); + _bl_static_blogcomponent_code_start = .; + KEEP(SORT(*)(.static_blogcomponent_code*)) + *(.static_blogcomponent_code*) + _bl_static_blogcomponent_code_end = .; + + /* static blog code2 */ + . = ALIGN(4); + _bl_static_blogfile_code_start = .; + KEEP(SORT(*)(.static_blogfile_code*)) + *(.static_blogfile_code*) + _bl_static_blogfile_code_end = .; + + /* static blog code3 */ + . = ALIGN(4); + _bl_static_blogpri_code_start = .; + KEEP(SORT(*)(.static_blogpri_code*)) + *(.static_blogpri_code*) + _bl_static_blogpri_code_end = .; + + /* section information for components's version */ + . = ALIGN(4); + _version_info_section_start = .; + KEEP(*(.version.*)) + _version_info_section_end = .; + + *(.gnu.linkonce.r.*) + } >flash + + .init_array : + { + __init_array_start = .; + KEEP(*(.init_array)) + __init_array_end = .; + } >flash + + .bleromro : + { + KEEP(*(.bleromro)) + } >flash + + .bleromrw (NOLOAD) : + { + KEEP(*(.bleromrw)) + } >tcm_ocram + + .hbn : ALIGN(4) + { + PROVIDE( _hbn_load = LOADADDR(.hbn) ); + PROVIDE( _hbn_run = ADDR(.hbn) ); + PROVIDE( _hbn_run_end = ADDR(.hbn) + SIZEOF(.hbn) ); + + *(.hbn_code.*) + *(.hbn_data) + *(.retention) + } >hbnram AT >flash + + .hbn_noinit (NOLOAD) : + { + *(.hbn_noinit) + *(.retention_noinit) + } >hbnram + + .tcmdata (NOLOAD) : + { + *(.tcm_data) + } >tcm_ocram + + .tcmcode : ALIGN(4) + { + PROVIDE( _tcm_load = LOADADDR(.tcmcode) ); + PROVIDE( _tcm_run = ADDR(.tcmcode) ); + PROVIDE( _tcm_run_end = ADDR(.tcmcode) + SIZEOF(.tcmcode) ); + + *(.tcm_code.*) + *(.tcm_const.*) + *(.sclock_rlt_code.*) + *(.sclock_rlt_const.*) + } >tcm_ocram AT >flash + + .data : ALIGN(4) + { + PROVIDE( _data_load = LOADADDR(.data) ); + PROVIDE( _data_run = ADDR(.data) ); + PROVIDE( _data_run_end = ADDR(.data) + SIZEOF(.data) ); + + *(.pds_code.*) + *(.data .data.*) + *(.gnu.linkonce.d.*) + + . = ALIGN(8); + /*always put freertos under global_pointer with the following order. No change!*/ + PROVIDE( __global_pointer$ = . + 0x7F0 ); + KEEP(*libbl702l_freertos.a:*(.sdata.*)) + KEEP(*libbl702l_freertos.a:*(.sbss.*)) + KEEP(*libbl702l_freertos.a:*(.bss.*)) + KEEP(*libbl702l_freertos.a:*(COMMON)) + *(.sdata .sdata.*) + *(.gnu.linkonce.s.*) + + . = ALIGN(8); + *(.srodata.cst16) + *(.srodata.cst8) + *(.srodata.cst4) + *(.srodata.cst2) + *(.srodata .srodata.*) + + . = ALIGN(8); + *(._k_queue.static.*) + *(._k_sem.static.*) + *(._k_mutex.static.*) + _bt_gatt_service_static_list_start = .; + KEEP(*(SORT_BY_NAME("._bt_gatt_service_static.static.*"))) + _bt_gatt_service_static_list_end = .; + _bt_l2cap_fixed_chan_list_start = .; + KEEP(*(SORT_BY_NAME("._bt_l2cap_fixed_chan.static.*"))) + _bt_l2cap_fixed_chan_list_end = .; + } >tcm_ocram AT >flash + + .boot2 (NOLOAD) : + { + PROVIDE ( __boot2_pt_addr_start = . ); + *(.bss.boot2_partition_table) + PROVIDE ( __boot2_pt_addr_end = . ); + + PROVIDE ( __boot2_flashCfg_start = . ); + *(.bss.boot2_flashCfg) + PROVIDE ( __boot2_flashCfg_end = . ); + } >hbnram + + .bss_psram (NOLOAD) : + { + PROVIDE( __bss_psram_start = ADDR(.bss_psram) ); + PROVIDE( __bss_psram_end = ADDR(.bss_psram) + SIZEOF(.bss_psram) ); + + PROVIDE ( __psram_bss_init_start = . ); + /** put the bss data in psram between __psram_bss_init_start and __psram_bss_init_end will bet reset to 0 after psram init*/ + . = ALIGN(16); + KEEP(*libCHIP.a:*(.sbss.*)) + KEEP(*libCHIP.a:*(.bss.*)) + + . = ALIGN(16); + KEEP(*libCHIPAppServer.a:*(.sbss.*)) + KEEP(*libCHIPAppServer.a:*(.bss.*)) + + . = ALIGN(16); + KEEP(*libMatterDeviceInfoProviderExample.a:*(.sbss.*)) + KEEP(*libMatterDeviceInfoProviderExample.a:*(.bss.*)) + + . = ALIGN(16); + KEEP(*libopenthread-ftd.a:*(.sbss.*)) + KEEP(*libopenthread-ftd.a:*(.bss.*)) + KEEP(*libopenthread-mtd.a:*(.sbss.*)) + KEEP(*libopenthread-mtd.a:*(.bss.*)) + + . = ALIGN(16); + KEEP(*src/app/clusters/*/bouffalolab*.cpp.o(.sbss.*)) + KEEP(*src/app/clusters/*/bouffalolab*.cpp.o(.bss.*)) + + . = ALIGN(16); + KEEP(*examples/platform/bouffalolab/common/plat/chip*.c.o(.sbss.*)) + KEEP(*examples/platform/bouffalolab/common/plat/chip*.c.o(.sbss.*)) + KEEP(*examples/platform/bouffalolab/common/plat/chip*.cpp.o(.bss.*)) + KEEP(*examples/platform/bouffalolab/common/plat/chip*.cpp.o(.bss.*)) + + . = ALIGN(16); + KEEP(*examples/*/bouffalolab/common/chip*.c.o(.sbss.*)) + KEEP(*examples/*/bouffalolab/common/chip*.c.o(.sbss.*)) + KEEP(*examples/*/bouffalolab/common/chip*.cpp.o(.bss.*)) + KEEP(*examples/*/bouffalolab/common/chip*.cpp.o(.bss.*)) + + . = ALIGN(16); + KEEP(*sdk_lwip.*.c.o(.sbss.*)) + KEEP(*sdk_lwip.*.c.o(.bss.*)) + KEEP(*lwip.*.c.o(.bss.*)) + + . = ALIGN(16); + KEEP(*stack_main.o(.bss.*)) + + . = ALIGN(16); + *(.wifi_ram*) + PROVIDE ( __psram_bss_init_end = . ); + } > psram + + .bss (NOLOAD) : + { + PROVIDE( __bss_start = ADDR(.bss) ); + PROVIDE( __bss_end = ADDR(.bss) + SIZEOF(.bss) ); + + *(.sbss*) + *(.gnu.linkonce.sb.*) + *(.bss .bss.*) + *(.gnu.linkonce.b.*) + *(COMMON) + } >tcm_ocram + + .sha_ocram (NOLOAD) : + { + *(.sha_ocram*) + } >tcm_ocram + + . = ALIGN(8); + PROVIDE( _heap_start = . ); + PROVIDE( _heap_size = ORIGIN(tcm_ocram) + LENGTH(tcm_ocram) - _heap_start ); + + PROVIDE( _heap2_start = 0 ); + PROVIDE( _heap2_size = 0 ); + + .stack (NOLOAD) : ALIGN(8) + { + PROVIDE( _sp_base = . ); + . = . + __stack_size; + PROVIDE( _sp_main = . ); + __freertos_irq_stack_top = .; + } >sys_stack + + .psram (NOLOAD) : + { + . = ALIGN(16); + PROVIDE( _psram_start = . ); + *(.wifi_ram*) + . = ALIGN(16); + PROVIDE( _psram_end = . ); + } >psram + + . = ALIGN(8); + PROVIDE( _heap3_start = . ); + PROVIDE( _heap3_size = ORIGIN(psram) + LENGTH(psram) - _heap3_start ); + + + /* cli */ + PROVIDE( _ld_bl_static_cli_cmds_start = _bl_static_cli_cmds_start ); + PROVIDE( _ld_bl_static_cli_cmds_end = _bl_static_cli_cmds_end ); + + /* blog */ + PROVIDE( _ld_bl_static_blogcomponent_code_start = _bl_static_blogcomponent_code_start ); + PROVIDE( _ld_bl_static_blogcomponent_code_end = _bl_static_blogcomponent_code_end ); + PROVIDE( _ld_bl_static_blogfile_code_start = _bl_static_blogfile_code_start ); + PROVIDE( _ld_bl_static_blogfile_code_end = _bl_static_blogfile_code_end ); + PROVIDE( _ld_bl_static_blogpri_code_start = _bl_static_blogpri_code_start ); + PROVIDE( _ld_bl_static_blogpri_code_end = _bl_static_blogpri_code_end ); + + /* ram information */ + PROVIDE( _ld_ram_size0 = LENGTH(flash) ); + PROVIDE( _ld_ram_addr0 = ORIGIN(flash) ); + PROVIDE( _ld_ram_size1 = LENGTH(tcm_ocram) ); + PROVIDE( _ld_ram_addr1 = ORIGIN(tcm_ocram) ); + PROVIDE( _ld_ram_size2 = LENGTH(hbnram) ); + PROVIDE( _ld_ram_addr2 = ORIGIN(hbnram) ); + PROVIDE( _ld_ram_size3 = SIZEOF(.stack) ); + PROVIDE( _ld_ram_addr3 = ADDR(.stack) ); + PROVIDE( _ld_psram_size = LENGTH(psram) ); + PROVIDE( _ld_psram_addr = ORIGIN(psram) ); + + /* EM size */ + PROVIDE( __LD_CONFIG_EM_SEL = __EM_SIZE ); + + /* BLE_CORE_REG size */ + PROVIDE( __LD_BLE_CORE_REG_SIZE = __EM_SIZE ? 0x214 : 0 ); + + /* rom driver */ + INCLUDE ../../third_party/bouffalolab/repo/components/platform/soc/bl702l/bl702l/evb/ld/romdriver.ld +} diff --git a/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp index 5b18c866ed7c3f..64f8965ff8528e 100644 --- a/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp +++ b/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp @@ -42,8 +42,6 @@ #endif #include -#include - extern "C" { #include #include @@ -58,6 +56,8 @@ extern "C" { #endif } +#include + #include #include "mboard.h" @@ -103,6 +103,21 @@ extern "C" void vApplicationIdleHook(void) __asm volatile(" wfi "); } +#if (configUSE_TICK_HOOK != 0) +extern "C" void vApplicationTickHook(void) +{ +#if defined(CFG_USB_CDC_ENABLE) + extern void usb_cdc_monitor(void); + usb_cdc_monitor(); +#endif +} +#endif + +#if (configUSE_TICKLESS_IDLE != 0) +extern "C" __WEAK void vApplicationSleep(TickType_t xExpectedIdleTime) {} +#endif + +static StaticTask_t xIdleTaskTCB; extern "C" void vApplicationGetIdleTaskMemory(StaticTask_t ** ppxIdleTaskTCBBuffer, StackType_t ** ppxIdleTaskStackBuffer, uint32_t * pulIdleTaskStackSize) { @@ -146,18 +161,6 @@ extern "C" void vApplicationGetTimerTaskMemory(StaticTask_t ** ppxTimerTaskTCBBu *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH; } -#if (configUSE_TICK_HOOK != 0) -extern "C" void vApplicationTickHook(void) -{ -#if defined(CFG_USB_CDC_ENABLE) - extern void usb_cdc_monitor(void); - usb_cdc_monitor(); -#endif -} -#endif - -extern "C" void vApplicationSleep(TickType_t xExpectedIdleTime) {} - extern "C" void vAssertCalled(void) { void * ra = (void *) __builtin_return_address(0); @@ -280,16 +283,10 @@ extern "C" void setup_heap() bl_sys_em_config(); #endif -#if CHIP_DEVICE_LAYER_TARGET_BL702 - extern uint8_t __ocram_bss_start[], __ocram_bss_end[]; - if (NULL != __ocram_bss_start && NULL != __ocram_bss_end && __ocram_bss_end > __ocram_bss_start) - { - memset(__ocram_bss_start, 0, __ocram_bss_end - __ocram_bss_start); - } -#endif - vPortDefineHeapRegions(xHeapRegions); + bl_sys_early_init(); + #ifdef CFG_USE_PSRAM bl_psram_init(); do_psram_test(); @@ -302,10 +299,24 @@ extern "C" size_t get_heap_size(void) return (size_t) &_heap_size; } -extern "C" void app_init(void) +static void bl_show_component_version(void) { - bl_sys_early_init(); + extern uint8_t _version_info_section_start; + extern uint8_t _version_info_section_end; + char ** version_str_p = NULL; + + puts("Version of used components:\r\n"); + for (version_str_p = (char **) &_version_info_section_start; version_str_p < (char **) &_version_info_section_end; + version_str_p++) + { + puts("\tVersion: "); + puts(*version_str_p); + puts("\r\n"); + } +} +extern "C" void app_init(void) +{ #if CHIP_DEVICE_LAYER_TARGET_BL702L bl_flash_init(); #endif @@ -327,12 +338,14 @@ extern "C" void app_init(void) /* board config is set after system is init*/ hal_board_cfg(0); -#if CHIP_DEVICE_LAYER_TARGET_BL702L || CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET +#if CHIP_DEVICE_LAYER_TARGET_BL702 && (CHIP_DEVICE_CONFIG_ENABLE_WIFI || CHIP_DEVICE_CONFIG_ENABLE_ETHERNET) hosal_dma_init(); #endif #if CHIP_DEVICE_LAYER_TARGET_BL602 wifi_td_diagnosis_init(); #endif + + bl_show_component_version(); } extern "C" void platform_port_init(void) diff --git a/examples/platform/bouffalolab/common/plat/plat.h b/examples/platform/bouffalolab/common/plat/plat.h index ba85f03e88105f..f0360ff19a70c5 100644 --- a/examples/platform/bouffalolab/common/plat/plat.h +++ b/examples/platform/bouffalolab/common/plat/plat.h @@ -23,6 +23,8 @@ #define EXT_DISCOVERY_TIMEOUT_SECS 20 +typedef void (*app_pds_gpio_irq_handler_t)(void * arg); + #ifdef __cplusplus #include @@ -33,5 +35,6 @@ extern "C" void platform_port_init(void); void appError(int err); void platform_port_init(void); - #endif + +void app_pds_init(app_pds_gpio_irq_handler_t pinHandler); diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index 9564e5a07b0edd..ef6a2452cdbb04 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -211,8 +211,13 @@ CHIP_ERROR PlatformManagerImpl::PlatformInit(void) #if CHIP_DEVICE_CONFIG_THREAD_FTD ReturnLogErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_Router)); #else - ReturnLogErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice)); +#if CHIP_CONFIG_ENABLE_ICD_SERVER + ReturnErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_SleepyEndDevice)); +#else + ReturnErrorOnFailure(ConnectivityMgr().SetThreadDeviceType(ConnectivityManager::kThreadDeviceType_MinimalEndDevice)); +#endif #endif + #endif #if CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 0349cb7cc805ac..4af73192b578d4 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -707,6 +707,7 @@ def BuildBouffalolabTarget(): target.AppendFixedTargets([ TargetPart('light', app=BouffalolabApp.LIGHT), + TargetPart('contact-sensor', app=BouffalolabApp.CONTACT, enable_pds=True).OnlyIfRe('-(bl704l)'), ]) target.AppendFixedTargets([ diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index 049cacbb97eb7b..d575259aafab7a 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -28,6 +28,8 @@ class BouffalolabApp(Enum): def ExampleName(self): if self == BouffalolabApp.LIGHT: return 'lighting-app' + elif self == BouffalolabApp.CONTACT: + return 'contact-sensor-app' else: raise Exception('Unknown app type: %r' % self) @@ -35,7 +37,7 @@ def AppNamePrefix(self, chip_name): if self == BouffalolabApp.LIGHT: return ('chip-%s-lighting-example' % chip_name) elif self == BouffalolabApp.CONTACT: - return ('chip-%s-contact-example' % chip_name) + return ('chip-%s-contact-sensor-example' % chip_name) else: raise Exception('Unknown app type: %r' % self) @@ -100,6 +102,7 @@ def __init__(self, use_matter_openthread: bool = False, enable_easyflash: bool = False, enable_littlefs: bool = False, + enable_pds: bool = False, enable_debug_coredump: bool = False, ): @@ -237,6 +240,9 @@ def __init__(self, if enable_mfd: self.argsOpt.append("chip_enable_factory_data=true") + if enable_pds: + self.argsOpt.append("enable_pds=true") + self.argsOpt.append(f"enable_heap_monitoring={str(enable_heap_monitoring).lower()}") if enable_debug_coredump: self.argsOpt.append(f"enable_debug_coredump=true") diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index c396fe0525e655..875c964cb998fb 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,7 +1,7 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,light-switch,pigweed} asr-{asr582x,asr595x,asr550x}-{all-clusters,all-clusters-minimal,lighting,light-switch,lock,bridge,temperature-measurement,thermostat,ota-requestor,dishwasher,refrigerator}[-ota][-shell][-no_logging][-factory][-rotating_id][-rio] android-{arm,arm64,x86,x64,androidstudio-arm,androidstudio-arm64,androidstudio-x86,androidstudio-x64}-{chip-tool,chip-test,tv-server,tv-casting-app,java-matter-controller,kotlin-matter-controller,virtual-device-app}[-no-debug] -bouffalolab-{bl602dk,bl616dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-light-{ethernet,wifi,thread,thread-ftd,thread-mtd}-{easyflash,littlefs}[-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-memmonitor][-coredump] +bouffalolab-{bl602dk,bl616dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-{light,contact-sensor}-{ethernet,wifi,thread,thread-ftd,thread-mtd}-{easyflash,littlefs}[-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-memmonitor][-coredump] cc32xx-{lock,air-purifier} ti-cc13x4_26x4-{lighting,lock,pump,pump-controller}[-mtd][-ftd] cyw30739-{cyw30739b2_p5_evk_01,cyw30739b2_p5_evk_02,cyw30739b2_p5_evk_03,cyw930739m2evb_01,cyw930739m2evb_02}-{light,light-switch,lock,thermostat} diff --git a/third_party/bouffalolab/bl602/bl_iot_sdk.gni b/third_party/bouffalolab/bl602/bl_iot_sdk.gni index 77b40cf306aa08..ba564db1469bec 100644 --- a/third_party/bouffalolab/bl602/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl602/bl_iot_sdk.gni @@ -20,8 +20,8 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" - enable_debug_frame_ptr = false - debug_output_file = "" + enable_debug_coredump = false + coredump_binary_id = 0 } assert(bl_iot_sdk_root != "", "bl_iot_sdk_root must be specified") @@ -63,11 +63,6 @@ template("bl_iot_sdk") { "-include", rebase_path("${invoker.freertos_config}", root_build_dir), ] - - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - cflags += [ "-fno-omit-frame-pointer" ] - } } source_set("${sdk_target_name}_soc") { @@ -162,14 +157,6 @@ template("bl_iot_sdk") { source_set("${sdk_target_name}_bl602_freertos") { defines = [ "portasmHANDLE_INTERRUPT=interrupt_entry" ] - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - defines += [ - "CONF_ENABLE_FRAME_PTR=1", - "CONF_ENABLE_FUNC_BACKTRACE_ELF=${invoker.debug_output_file}", - ] - } - include_dirs = [ "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single" ] sources = [ @@ -210,10 +197,18 @@ template("bl_iot_sdk") { } source_set("${sdk_target_name}_hosal") { - defines = [ - "CFG_BLE_ENABLE", - "CONF_BL602_USE_1M_FLASH=0", - ] + defines = [ "CONF_BL602_USE_1M_FLASH=0" ] + + if (defined(invoker.chip_config_network_layer_ble) && + invoker.chip_config_network_layer_ble) { + defines += [ "CFG_BLE_ENABLE" ] + } + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "SYS_ENABLE_COREDUMP" ] + } + sources = [ "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_adc.c", "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_boot2.c", @@ -368,13 +363,15 @@ template("bl_iot_sdk") { [ "${bl_iot_sdk_root}/components/stage/littlefs/littlefs" ] include_dirs += [ "${bl_iot_sdk_root}/components/stage/littlefs/port" ] } + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + include_dirs += [ "${bl_iot_sdk_root}/components/stage/coredump/inc" ] + } } source_set("${sdk_target_name}_stage") { - defines = [ - "EF_ENV_CACHE_TABLE_SIZE=64", - "RHINO_CONFIG_WORKQUEUE=0", - ] + defines = [ "RHINO_CONFIG_WORKQUEUE=0" ] sources = [ "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt.c", @@ -394,6 +391,13 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/yloop/src/yloop.c", ] + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "BFLB_COREDUMP_BINARY_ID=${invoker.coredump_binary_id}" ] + sources += + [ "${bl_iot_sdk_root}/components/stage/coredump/bl_coredump.c" ] + } + cflags_c = [ "-Wno-sign-compare" ] configs += [ ":${sdk_target_name}_config", @@ -402,10 +406,12 @@ template("bl_iot_sdk") { ":${sdk_target_name}_config_fs", ":${sdk_target_name}_config_sys", ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_hosal", ] if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && invoker.bouffalo_sdk_component_easyflash_enabled) { + defines += [ "EF_ENV_CACHE_TABLE_SIZE=64" ] sources += [ "${bl_iot_sdk_root}/components/stage/easyflash4/src/easyflash.c", "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_env.c", @@ -423,7 +429,6 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/littlefs/littlefs/lfs_util.c", "${bl_iot_sdk_root}/components/stage/littlefs/port/lfs_xip_flash.c", ] - configs += [ ":${sdk_target_name}_config_hosal" ] } public_configs = [ ":${sdk_target_name}_config_stage" ] diff --git a/third_party/bouffalolab/bl702/bl_iot_sdk.gni b/third_party/bouffalolab/bl702/bl_iot_sdk.gni index d90262483f24a2..76d35da758e883 100644 --- a/third_party/bouffalolab/bl702/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl702/bl_iot_sdk.gni @@ -21,8 +21,8 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" - enable_debug_frame_ptr = true - debug_output_file = "" + enable_debug_coredump = false + coredump_binary_id = 0 } assert(bl_iot_sdk_root != "", "bl_iot_sdk_root must be specified") @@ -63,11 +63,6 @@ template("bl_iot_sdk") { "-include", rebase_path("${invoker.freertos_config}", root_build_dir), ] - - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - cflags += [ "-fno-omit-frame-pointer" ] - } } config("${sdk_target_name}_config_soc") { @@ -97,6 +92,7 @@ template("bl_iot_sdk") { config("${sdk_target_name}_config_BSP_Driver") { include_dirs = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver", "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/inc", "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/regs", "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/startup", @@ -171,13 +167,6 @@ template("bl_iot_sdk") { source_set("${sdk_target_name}_bl702_freertos") { defines = [ "portasmHANDLE_INTERRUPT=interrupt_entry" ] - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - defines += [ - "CONF_ENABLE_FRAME_PTR=1", - "CONF_ENABLE_FUNC_BACKTRACE_ELF=${invoker.debug_output_file}", - ] - } include_dirs = [ "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single" ] @@ -202,14 +191,6 @@ template("bl_iot_sdk") { "-Wno-old-style-declaration", ] - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - cflags_c += [ - "-Wno-incompatible-pointer-types", - "-Wno-int-conversion", - ] - } - public_configs = [ ":${sdk_target_name}_config", ":${sdk_target_name}_config_freertos", @@ -267,6 +248,11 @@ template("bl_iot_sdk") { defines += [ "CFG_BLE_ENABLE" ] } + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "SYS_ENABLE_COREDUMP" ] + } + sources = [ "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_adc.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_boot2.c", @@ -281,6 +267,7 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_irq.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_pds.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_psram.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_psram_sp.S", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_pwm.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_rtc.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_sec.c", @@ -413,6 +400,11 @@ template("bl_iot_sdk") { include_dirs += [ "${bl_iot_sdk_root}/components/stage/littlefs/port" ] } + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + include_dirs += [ "${bl_iot_sdk_root}/components/stage/coredump/inc" ] + } + if (defined(invoker.enable_cdc_module) && invoker.enable_cdc_module) { cflags_cc = [ "-Wno-shadow" ] } @@ -441,6 +433,13 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/yloop/src/yloop.c", ] + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "BFLB_COREDUMP_BINARY_ID=${invoker.coredump_binary_id}" ] + sources += + [ "${bl_iot_sdk_root}/components/stage/coredump/bl_coredump.c" ] + } + cflags_c = [ "-Wno-sign-compare" ] configs += [ ":${sdk_target_name}_config", @@ -449,10 +448,12 @@ template("bl_iot_sdk") { ":${sdk_target_name}_config_fs", ":${sdk_target_name}_config_sys", ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_hosal", ] if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && invoker.bouffalo_sdk_component_easyflash_enabled) { + defines += [ "EF_ENV_CACHE_TABLE_SIZE=64" ] sources += [ "${bl_iot_sdk_root}/components/stage/easyflash4/src/easyflash.c", "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_env.c", @@ -470,7 +471,6 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/littlefs/littlefs/lfs_util.c", "${bl_iot_sdk_root}/components/stage/littlefs/port/lfs_xip_flash.c", ] - configs += [ ":${sdk_target_name}_config_hosal" ] } public_configs = [ ":${sdk_target_name}_config_stage" ] @@ -742,7 +742,10 @@ template("bl_iot_sdk") { } config("${sdk_target_name}_config_openthread_port") { - defines = [ "OT_FREERTOS_ENABLE=1" ] + defines = [ + "OT_FREERTOS_ENABLE=1", + "CONFIG_LMAC154_LOG=0", + ] include_dirs = [ "${openthread_root}/src/core", @@ -779,6 +782,7 @@ template("bl_iot_sdk") { invoker.bouffalo_sdk_component_easyflash_enabled) { sources += [ "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_settings_easyflash.c" ] } else { + defines += [ "BL_LITTLEFS_PARTITION_NAME" ] sources += [ "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_settings_littlefs.c" ] } diff --git a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni index cdbf9228ca0e58..ac608a72098cd6 100644 --- a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni @@ -21,8 +21,9 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" - enable_debug_frame_ptr = true - debug_output_file = "" + enable_pds = false + enable_debug_coredump = false + coredump_binary_id = 0 } assert(bl_iot_sdk_root != "", "bl_iot_sdk_root must be specified") @@ -63,11 +64,6 @@ template("bl_iot_sdk") { "-include", rebase_path("${invoker.freertos_config}", root_build_dir), ] - - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - cflags += [ "-fno-omit-frame-pointer" ] - } } config("${sdk_target_name}_config_soc") { @@ -83,12 +79,7 @@ template("bl_iot_sdk") { "SYS_APP_TASK_PRIORITY=15", ] - include_dirs = [ - "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_rf/include", - ] - sources = [ - # "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l/bfl_main.c", "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l/evb/src/boot/gcc/start.S", "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l/evb/src/debug.c", "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l/evb/src/strntoumax.c", @@ -111,6 +102,7 @@ template("bl_iot_sdk") { ":${sdk_target_name}_config_utils", ":${sdk_target_name}_config_freertos", ] + public_configs = [ ":${sdk_target_name}_config_soc" ] } config("${sdk_target_name}_config_BSP_Driver") { @@ -158,20 +150,13 @@ template("bl_iot_sdk") { config("${sdk_target_name}_config_freertos") { include_dirs = [ "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_freertos/config", - "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_freertos/portable/GCC/RISC-V", "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_freertos/panic", + "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_freertos/portable/GCC/RISC-V", ] } source_set("${sdk_target_name}_bl702l_freertos") { defines = [ "portasmHANDLE_INTERRUPT=interrupt_entry" ] - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - defines += [ - "CONF_ENABLE_FRAME_PTR=1", - "CONF_ENABLE_FUNC_BACKTRACE_ELF=${invoker.debug_output_file}", - ] - } include_dirs = [ "${bl_iot_sdk_root}/components/platform/soc/bl702l/bl702l_freertos/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single" ] @@ -196,14 +181,6 @@ template("bl_iot_sdk") { "-Wno-old-style-declaration", ] - if (defined(invoker.enable_debug_frame_ptr) && - invoker.enable_debug_frame_ptr) { - cflags_c += [ - "-Wno-incompatible-pointer-types", - "-Wno-int-conversion", - ] - } - public_configs = [ ":${sdk_target_name}_config", ":${sdk_target_name}_config_freertos", @@ -229,6 +206,11 @@ template("bl_iot_sdk") { defines += [ "CFG_BLE_ENABLE" ] } + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "SYS_ENABLE_COREDUMP" ] + } + sources = [ "${bl_iot_sdk_root}/components/platform/hosal/bl702l_hal/bl_adc.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702l_hal/bl_boot2.c", @@ -277,10 +259,12 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_pka.c", "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_sha.c", ] + sources += [ "${bl_iot_sdk_root}/components/platform/hosal/bl702l_hal/bl_pds.c", "${bl_iot_sdk_root}/components/platform/hosal/bl702l_hal/hal_pds.c", ] + cflags_c = [ "-Wno-unused-variable", "-Wno-sign-compare", @@ -375,6 +359,11 @@ template("bl_iot_sdk") { [ "${bl_iot_sdk_root}/components/stage/littlefs/littlefs" ] include_dirs += [ "${bl_iot_sdk_root}/components/stage/littlefs/port" ] } + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + include_dirs += [ "${bl_iot_sdk_root}/components/stage/coredump/inc" ] + } } source_set("${sdk_target_name}_stage") { @@ -400,6 +389,13 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/yloop/src/yloop.c", ] + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "BFLB_COREDUMP_BINARY_ID=${invoker.coredump_binary_id}" ] + sources += + [ "${bl_iot_sdk_root}/components/stage/coredump/bl_coredump.c" ] + } + cflags_c = [ "-Wno-sign-compare" ] configs += [ ":${sdk_target_name}_config", @@ -408,6 +404,7 @@ template("bl_iot_sdk") { ":${sdk_target_name}_config_sys", ":${sdk_target_name}_config_utils", ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_hosal", ] if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && @@ -429,7 +426,6 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/stage/littlefs/littlefs/lfs_util.c", "${bl_iot_sdk_root}/components/stage/littlefs/port/lfs_xip_flash.c", ] - configs += [ ":${sdk_target_name}_config_hosal" ] } public_configs = [ ":${sdk_target_name}_config_stage" ] @@ -605,32 +601,41 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/network/ble/blestack/src/port/include", "${bl_iot_sdk_root}/components/network/ble/blestack/src", "${bl_iot_sdk_root}/components/network/ble/blestack/src/host", + "${bl_iot_sdk_root}/components/network/ble/btble_pds/include", ] defines = [ + "BUILD_ROM_CODE", + "CFG_BLE_ENABLE", "BFLB_BLE", - "CONFIG_SET_TX_PWR", - "CFG_CON=1", "CFG_BLE", - "CFG_SLEEP", - "CONFIG_BT_PERIPHERAL=1", + "CFG_IOT_SDK", + "CFG_CON=1", "CFG_BLE_TX_BUFF_DATA=2", - "CONFIG_BT_GATT_DYNAMIC_DB", - "CONFIG_BT_GATT_SERVICE_CHANGED", - "CONFIG_BT_SETTINGS_CCC_LAZY_LOADING", - "CONFIG_BT_KEYS_OVERWRITE_OLDEST", - "CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS", - "CONFIG_BT_BONDABLE", + "CONFIG_BT_PERIPHERAL", + "CONFIG_BT_BROADCASTER", + "CFG_EM_HEAP_DISABLE", + "CONFIG_BT_CONN", + "CONFIG_BT_HCI_VS_EVT_USER", "CONFIG_BT_ASSERT", - "CFG_BLE_STACK_DBG_PRINT", - "CONFIG_CHIP_NAME = BL702L", + "CONFIG_BT_GATT_CLIENT", ] + if (defined(invoker.enable_pds) && invoker.enable_pds) { + defines += [ + "CFG_BLE_PDS", + "CONFIG_HW_SEC_ENG_DISABLE", + ] + } + cflags_cc = [ "-Wno-conversion" ] } source_set("${sdk_target_name}_ble") { libs = [ "${bl_iot_sdk_root}/components/network/ble/btblecontroller_702l_m0s1p/lib/libbtblecontroller_702l_m0s1p.a" ] + if (defined(invoker.enable_pds) && invoker.enable_pds) { + libs += [ "${bl_iot_sdk_root}/components/network/ble/btble_pds/lib/libbtble_pds.a" ] + } include_dirs = [ "${bl_iot_sdk_root}/components/network/ble/blestack/src/common", @@ -688,9 +693,13 @@ template("bl_iot_sdk") { } config("${sdk_target_name}_config_openthread_port") { - defines = [ "OT_FREERTOS_ENABLE=1" ] + defines = [ + "OT_FREERTOS_ENABLE=1", + "CONFIG_LMAC154_LOG=0", + ] include_dirs = [ + "${bl_iot_sdk_root}/components/network/lmac154/lmac154/include", "${openthread_root}/src/core", "${openthread_root}/examples/platforms", "${bl_iot_sdk_root}/components/network/thread/openthread_port/include", @@ -708,7 +717,6 @@ template("bl_iot_sdk") { } include_dirs = [ - "${bl_iot_sdk_root}/components/network/lmac154/lmac154/include", "${bl_iot_sdk_root}/components/network/thread/openthread_port", "${openthread_root}/examples/platforms/utils/", "${openthread_root}/examples", @@ -725,6 +733,7 @@ template("bl_iot_sdk") { invoker.bouffalo_sdk_component_easyflash_enabled) { sources += [ "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_settings_easyflash.c" ] } else { + defines += [ "BL_LITTLEFS_PARTITION_NAME" ] sources += [ "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_settings_littlefs.c" ] } diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index 51a4f451b67a33..75df6e87ffa10b 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit 51a4f451b67a33d07f11cc55e4dbd8ff5d374eb0 +Subproject commit 75df6e87ffa10b905c9dbb0efc5fd35f96955c55 From a3380db4b31e4164a6f4a03b7e4267f253cdb988 Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Thu, 16 Jan 2025 02:29:36 +0800 Subject: [PATCH 5/7] [bouffalo lab] Update Bouffalo Lab platform documents (#37067) * [bouffalo lab] Update bouffalo lab documents for contact sensor and new platform bl616 * Restyled by prettier-markdown * fix document references * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io --- docs/guides/bouffalolab/getting_started.md | 286 ++++++++++++++++++ docs/guides/bouffalolab/ota_upgrade.md | 108 +++++++ docs/guides/bouffalolab/platform_overview.md | 75 +++++ docs/guides/bouffalolab/rpc_console.md | 38 +++ docs/platforms/bouffalolab/index.md | 15 + .../contact-sensor-app/bouffalolab/README.md | 68 +++++ .../bouffalolab/bl702l/with_pw_rpc.gni | 1 - 7 files changed, 590 insertions(+), 1 deletion(-) create mode 100644 docs/guides/bouffalolab/getting_started.md create mode 100644 docs/guides/bouffalolab/ota_upgrade.md create mode 100644 docs/guides/bouffalolab/platform_overview.md create mode 100644 docs/guides/bouffalolab/rpc_console.md create mode 100644 docs/platforms/bouffalolab/index.md create mode 100644 examples/contact-sensor-app/bouffalolab/README.md diff --git a/docs/guides/bouffalolab/getting_started.md b/docs/guides/bouffalolab/getting_started.md new file mode 100644 index 00000000000000..eb96bc8da04728 --- /dev/null +++ b/docs/guides/bouffalolab/getting_started.md @@ -0,0 +1,286 @@ +# Checking out the Matter code + +## Checking out all Platforms + +To check out the Matter repository with all platforms, run the following +command: + +``` +git clone --recurse-submodules https://github.com/project-chip/connectedhomeip.git +``` + +## Checking out `Bouffalo Lab` Platform + +- Checking out matter top level repo with command below: + + ``` + git clone --depth=1 https://github.com/project-chip/connectedhomeip.git + ``` + +- check out `Bouffalo Lab` platform support repos as follows: + + ``` + scripts/checkout_submodules.py --shallow --recursive --platform bouffalolab + ``` + + If you want to checkout Matter Linux example and development tools, please + try as follows: + + ``` + scripts/checkout_submodules.py --shallow --recursive --platform linux bouffalolab + ``` + + Or if you want to checkout Matter Darwin example and development tools, + please try as follows: + + ``` + scripts/checkout_submodules.py --shallow --recursive --platform darwin bouffalolab + ``` + +# Setup build environment + +Please refer to section `Prerequisites` in +[BUILDING.md](../../guides/BUILDING.md) to install build software. + +## Install toolchains for `Bouffalo Lab` SoC + +- Enter to cloned Matter project in terminal and run the following script + + ``` + ./integrations/docker/images/stage-2/chip-build-bouffalolab/setup.sh + ``` + + Script `setup.sh` requires to select install path, and please execute + following command to export `BOUFFALOLAB_SDK_ROOT` before building. + + ``` + export BOUFFALOLAB_SDK_ROOT="Your install path" + ``` + +## Setup Matter build environment + +- Enter to cloned Matter project in terminal and run the following script + + ``` + source scripts/activate.sh -p bouffalolab + ``` + + > Please refer to `scripts/bootstrap.sh` and `scripts/activate.sh` for more + > detail. + +# Build examples + +## Build options for `Bouffalo Lab` SoC + +With `source scripts/activate.sh -p bouffalolab` under terminal, please try the +following command to list supports options. + +``` +./scripts/build/build_examples.py targets +``` + +The output with `bouffalolab` started likes below: + +``` +bouffalolab-{bl602dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-{light,contact-sensor}-{ethernet,wifi,thread,thread-ftd,thread-mtd}-{easyflash,littlefs}[-shell][-mfd][-rotating_device_id][-rpc][-cdc] +``` + +- supported board options, select one of the following options to build + + - `-bl602dk` + - `-bl616dk` + - `-bl704ldk` + - `-bl706dk` + + - `-bl602-night-light` + - `-bl706-night-light` + - `-bl602-iot-matter-v1` + - `-xt-zb6-devkit` + +- supported example options, select one of the following options to build + + - `-light` + - `-contact-sensor`, currently, only BL704L with Thread MTD and low power + supported + +- connectivity options, select one of the following options to build + + - `-wifi`, specifies to use Wi-Fi for Matter application. + + - `-ethernet`, specifies to use Ethernet for Matter application. + + - `-thread`, specifies to use Thread FTD for Matter application. + + - `-thread-ftd`, specifies to use Thread FTD for Matter application. + + - `-thread-mtd`, specifies to use Thread MTD for Matter application. + +- storage options, select one of the following options to build + + - `-littlefs`, specifies to use `littlefs` for flash access. + + - `-easyflash`, specifies to use `easyflash` for flash access. + + > `littlefs` has different format with `easyflash`, please uses + > `-easyflash` for your in-field production + +- `-rotating_device_id`, enable rotating device id + +- `-mfd`, enable Matter factory data feature, which load factory data from + `MFD` partition + + - Please refer to + [Bouffalo Lab Matter factory data guide](./matter_factory_data.md) or + contact to `Bouffalo Lab` for support. + +- `-shell`, enable command line + +- `-rpc`, enable Pigweed RPC feature, which will use `baudrate` 115200 for PRC + +- `-cdc`, enable USB CDC feature, only support for BL706, and can't work with + Ethernet Board + +> `Bouffalo Lab` Matter project uses UART `baudrate` 2000000 for logging output +> by default. If you want other `baudrate` for your test station, please change +> variable `baudrate` in `BUILD.gn` under example project. + +## Build an example + +Taking lighting app with `littlefs` supported as example : + +- BL602DK with Wi-Fi + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl602dk-light-wifi-littlefs build + ``` + +- BL616DK with Wi-Fi + + ```shell + ./scripts/build/build_examples.py --target bouffalolab-bl616dk-light-wifi-littlefs build + ``` + +- BL616 with Thread + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl616dk-light-thread-littlefs build + ``` + +- BL704L with Thread + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl704ldk-light-thread-littlefs build + ``` + +- BL706 with Thread + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl706dk-light-thread-littlefs build + ``` + +- BL706 with Ethernet + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl706dk-light-ethernet-littlefs build + ``` + +- BL706 with Wi-Fi + + ``` + ./scripts/build/build_examples.py --target bouffalolab-bl706dk-light-ethernet-littlefs build + ``` + + > This BL706 + BL602 Wi-Fi solution: BL602 runs WLAN part and BL706 runs + > TCP/IP stack which uses SPI for communication between these two parts. + +# Download image + +Take build target `bouffalolab-bl602dk-light-wifi-littlefs` as example to +introduce image downloading steps. + +After example compiled, a python script `chip-bl602-lighting-example.flash.py` +will be generated out under `./out/bouffalolab-bl602dk-light-wifi-littlefs/` and +is used to download image to `Bouffalo Lab` SoC. + +And download image as following steps: + +- Connect the board to your build machine with USB cable + +- Put the SoC to the download mode: + + - Press and hold the **BOOT** button. + - Click the **RESET** or **EN** button. + - Release the **BOOT** button. + +- Type following command for image download. Please set serial port + accordingly, here we use /dev/ttyACM0 as a serial port example. + + ```shell + ./out/bouffalolab-bl602dk-light-wifi-littlefs/chip-bl602-lighting-example.flash.py --port /dev/ttyACM0 + ``` + + If needs to download image with the whole flash erased, please append + `--erase` option. + + ```shell + ./out/bouffalolab-bl602dk-light-wifi-littlefs/chip-bl602-lighting-example.flash.py --port /dev/ttyACM0 --erase + ``` + + > Note, better to append --erase option to download image for BL602 develop + > board at first time. + +- Then, open serial console `/dev/ttyACM0` with `baudrate` 2000000. The log + will output if the **RESET** or **EN** button clicked. + +# Test Commission and Control with chip-tool + +Please follow +[chip_tool_guide](../../development_controllers/chip-tool/chip_tool_guide.md) to +build and [guide](../../../examples/chip-tool/README.md) use chip-tool for test. + +## Prerequisite for Thread Protocol + +Thread wireless protocol could runs on BL704L/BL706/BL616, which needs a Thread +border router to connect Thread network to Wi-Fi/Ethernet network. Please follow +this [guide](../openthread/openthread_border_router_pi.md) to setup a raspberry +Pi border router. + +After Thread border router setup, please type following command on Thread border +router to get Thread network credential. + +```shell +sudo ot-ctl dataset active -x +``` + +## Commissioning over BLE + +- Reset the board or factory reset the board + +- Enter build out folder of chip-tool and running the following command to do + BLE commission + + - Wi-Fi + + ```shell + ./out/linux-x64-chip-tool/chip-tool pairing ble-wifi 20202021 3840 + ``` + + - Thread + + ```shell + ./out/linux-x64-chip-tool/chip-tool pairing ble-thread hex: 20202021 3840 + ``` + + - Ethernet + `./out/linux-x64-chip-tool/chip-tool pairing onnetwork 20202021` + > ``, which is node ID assigned to device with + > chip-tool;
``, Wi-Fi network SSID;
``, + > Wi-FI network password;
``, Thread + > network credential which running `sudo ot-ctl dataset active -x` + > command on border router to get. + +## Read a cluster attribute + +``` +./out/linux-x64-chip-tool/chip-tool basicinformation read vendor-name 0 +``` diff --git a/docs/guides/bouffalolab/ota_upgrade.md b/docs/guides/bouffalolab/ota_upgrade.md new file mode 100644 index 00000000000000..2a50f073e8d02d --- /dev/null +++ b/docs/guides/bouffalolab/ota_upgrade.md @@ -0,0 +1,108 @@ +# Build OTA image + +Take build target `bouffalolab-bl602dk-light-wifi-littlefs` as example to +introduce OTA image building. + +After example compiled, a python script `chip-bl602-lighting-example.flash.py` +will be generated out under `./out/bouffalolab-bl602dk-light-wifi-littlefs/` and +is used to download image to `Bouffalo Lab` SoC. + +Type following command to generated OTA images: + +```shell +./out/bouffalolab-bl602dk-light-wifi-littlefs/chip-bl602-lighting-example.flash.py --build-ota --vendor-id --product-id --version --version-str --digest-algorithm +``` + +Please find `./src/app/ota_image_tool.py` for information on `vendor id`, +`product id`, `version number`, `version number string` and `digest algorithm`. + +Here is an example command to generate an OTA image, + +> Please change `CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION` and +> `CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING`in CHIPProjectConfig.h +> under example folder before to build a test OTA image. + +```shell +./out/bouffalolab-bl602dk-light-wifi-littlefs/chip-bl602-lighting-example.flash.py --build-ota --vendor-id 0xFFF1 --product-id 0x8005 --version 10 --version-str "1.0" --digest-algorithm sha256 +``` + +OTA images will generated under +`out/bouffalolab-bl602dk-light-wifi-littlefs/ota_images`: + +> BL702 and BL702L have same OTA image format with BL602 + +- `chip-bl602dk-lighting-example.bin.hash.matter`, OTA image packed with raw + firmware image. +- `chip-bl602dk-lighting-example.bin.xz.hash.matter`, OTA image packed with + compressed firmware image. + +BL616 SoC platform uses different OTA image format. Take BL616D lighting app +with Wi-Fi and `littlefs` supported as example: + +- `chip-bl616-lighting-example.bin.ota.matter`, OTA image packed with raw + firmware image. +- `chip-bl616-lighting-example.xz.ota.matter`, OTA image packed with + compressed firmware image. + +> Please contact `Bouffalo Lab` for more security requirements on firmware and +> OTA images. + +## Test OTA software upgrade with chip-tool and ota-provider-app + +Please follow +[chip_tool_guide](../../development_controllers/chip-tool/chip_tool_guide.md) +and [chip-tool guide](../../../examples/chip-tool/README.md) for chip-tool build +and usage and follow +[ota-provider-app guide](../../../examples/ota-provider-app/linux/README.md) for +ota-provider-app build and usage. + +### Start ota-provider-app + +- Start ota-provider-app with OTA compressed image. + + ```shell + $ rm -r /tmp/chip_* + $ out/linux-x64-ota-provider/chip-ota-provider-app -f out/bouffalolab-bl602dk-light-wifi-littlefs/ota_images/chip-bl602-lighting-example.bin.xz.hash.matter + ``` + +- Provision ota-provider-app with node id assigned + ```shell + $ ./out/linux-x64-chip-tool/chip-tool pairing onnetwork 20202021 + $ ./out/linux-x64-chip-tool/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}]' 0 + ``` + +### Start ota software upgrade + +- BLE commission with node id assigned + + - Wi-Fi + + ```shell + ./out/linux-x64-chip-tool/chip-tool pairing ble-wifi 20202021 3840 + ``` + + - Thread + + ```shell + ./out/linux-x64-chip-tool/chip-tool pairing ble-thread hex: 20202021 3840 + ``` + + - Ethernet + ``` + ./out/linux-x64-chip-tool/chip-tool pairing onnetwork 20202021 + ``` + +- Start OTA software upgrade process + + ```shell + ./out/linux-x64-chip-tool/chip-tool otasoftwareupdaterequestor announce-otaprovider 0 0 0 0 + ``` + +- After the OTA software upgrade completes, the device will reboot + automatically. Once rebooted, execute the following commands to verify if + the new firmware is applied: + + ``` + ./out/linux-x64-chip-tool/chip-tool basicinformation read software-version 0 + ./out/linux-x64-chip-tool/chip-tool basicinformation read software-version-string 0 + ``` diff --git a/docs/guides/bouffalolab/platform_overview.md b/docs/guides/bouffalolab/platform_overview.md new file mode 100644 index 00000000000000..d6a0fe96181101 --- /dev/null +++ b/docs/guides/bouffalolab/platform_overview.md @@ -0,0 +1,75 @@ +# `Bouffalo Lab` SoCs + +- BL602 + + BL602/BL604 is combo chip-set for Wi-Fi 4 and BLE 5.0. + +- BL61X + + BL61X is combo chip-set for Wi-Fi 6, Classic Bluetooth, Bluetooth low energy + 5.3 and IEEE 802.15.4/ZigBee/Thread. + + BL61X has fully certified with all Thread 1.3 features, included Thread + `SSED` and Thread Border Router. + +- BL70X + + BL70X is combo chip-set for BLE and IEEE 802.15.4/ZigBee/Thread. + + BL70X has fully certified with all Thread 1.3 features, included Thread + `SSED` and Thread Border Router. + + - BL702/BL706 has 14dbm tx power and is recommended for routing devices. + SDK uses BL702 as a general name. + - BL702L/BL704L is designed for low power application. SDK uses BL702L as + a general name. + +# Solutions introduction + +`Bouffalo Lab` has full connectivity supports for Matter Applications. + +- Wi-Fi 4/6 application, we have + - BL602, Wi-Fi 4 application. + - BL706 + BL602, Wi-Fi 4 application. + - BL616, Wi-Fi 6 application +- Thread application, we have + - BL70X/BL616 + - BL704L, Thread low power application. +- Ethernet application, we have + - BL706/BL618 +- Openthread Border Router application based on FreeRTOS + - BL706 + BL602, Wi-Fi 4 as infrastructure network + - BL616, Wi-Fi 6 as infrastructure network + - BL706/BL616, Ethernet as as infrastructure network +- Matter ZigBee Bridge application based on FreeRTOS - BL706 + BL602, Wi-Fi 4 + as infrastructure network - BL616, Wi-Fi 6 as infrastructure network - + BL706/BL616, Ethernet as as infrastructure network + > Please contact `Bouffalo Lab` for supports on OTBR and Matter ZigBee + > Bridge application + +# Current supported + +- Current supported boards: + + - `BL602DK` + + - `BL616DK` + + > Please contact `Bouffalo Lab` for BL616 SDK. + + - `BL704LDK` + + - `BL706DK` + +- Legacy supported boards: + + - `BL602-IoT-Matter-V1` + - `BL602-NIGHT-LIGHT` + - `XT-ZB6-DevKit` + - `BL706-NIGHT-LIGHT` + +- Supported examples: + + - [Lighting app](../../../examples/lighting-app/bouffalolab/README.md) + + - [Contact sensor app](../../../examples/contact-sensor-app/bouffalolab/README.md) diff --git a/docs/guides/bouffalolab/rpc_console.md b/docs/guides/bouffalolab/rpc_console.md new file mode 100644 index 00000000000000..6a506d69d325e3 --- /dev/null +++ b/docs/guides/bouffalolab/rpc_console.md @@ -0,0 +1,38 @@ +# `Bouffalo Lab` with RPC console + +## Build image + +- `BL602DK` + + ```shell + ./scripts/build/build_examples.py --target bouffalolab-bl602dk-light-wifi-littlefs-rpc build + ``` + +- `BL704LDK` + + ```shell + ./scripts/build/build_examples.py --target bouffalolab-bl704ldk-light-thread-littlefs-rpc build + ``` + +- `BL706DK` + + ```shell + ./scripts/build/build_examples.py --target bouffalolab-bl706dk-light-thread-littlefs-rpc build + ``` + +## Run RPC Console + +- Build chip-console following this + [guide](../../../examples/common/pigweed/rpc_console/README.md) + +- Start the console + + ``` + $ chip-console -d /dev/ttyACM0 -b 115200 + ``` + +- Get or Set the light state + + `rpcs.chip.rpc.Lighting.Get()` + + `rpcs.chip.rpc.Lighting.Set(on=True, level=128)` diff --git a/docs/platforms/bouffalolab/index.md b/docs/platforms/bouffalolab/index.md new file mode 100644 index 00000000000000..c3cc8f3db84702 --- /dev/null +++ b/docs/platforms/bouffalolab/index.md @@ -0,0 +1,15 @@ +# Bouffalolab + +```{toctree} +:glob: +:maxdepth: 1 +:hidden: + +* +``` + +[Bouffalo Lab - Platform overview](./platform_overview.md) +[Bouffalo Lab - Getting Started](./getting_started.md) +[Bouffalo Lab - OTA upgrade](./ota_upgrade.md) +[Bouffalo Lab - Matter factory data generation](./matter_factory_data.md) +[Bouffalo Lab - RPC console](./rpc_console.md) diff --git a/examples/contact-sensor-app/bouffalolab/README.md b/examples/contact-sensor-app/bouffalolab/README.md new file mode 100644 index 00000000000000..1b954452985e5f --- /dev/null +++ b/examples/contact-sensor-app/bouffalolab/README.md @@ -0,0 +1,68 @@ +# Matter `Bouffalo Lab` Contact Sensor Example + +This example functions as a contact sensor uses a test Vendor ID (VID) and a +Product ID (PID) of **0x8005**. + +Supported board: + +- `bl704ldk` + +Please refer to the following documents for more information + +- [Bouffalo Lab - Platform overview](../../../docs/platforms/bouffalolab/platform_overview.md) +- [Bouffalo Lab - Getting Started](../../../docs/platforms/bouffalolab/getting_started.md) +- [Bouffalo Lab - OTA upgrade](../../../docs/platforms/bouffalolab/ota_upgrade.md) +- [Bouffalo Lab - Matter factory data generation](../../../docs/platforms/bouffalolab/matter_factory_data.md) + +## Build CHIP Contact Sensor example + +```shell +./scripts/build/build_examples.py --target bouffalolab-bl704ldk-contact-sensor-thread-mtd-littlefs build +``` + +## Test with chip-tool + +### Commissioning over BLE + +- Reset the board or factory reset the board + +- Enter build out folder of chip-tool and running the following command to do + BLE commission + + - Thread + + ```shell + ./out/linux-x64-chip-tool/chip-tool pairing ble-thread hex: 20202021 3840 + ``` + + > ``, which is node ID assigned to device within + > chip-tool ``, Thread network credential + > which running `sudo ot-ctl dataset active -x` command on border router + > to get. + +### Subscribe booleanstate of contact sensor + +- Start chip-tool with interactive mode + + ```shell + ./chip-tool interactive start + ``` + +- Subscribe booleanstate under chip-tool interactive mode + + ```shell + booleanstate subscribe state-value 1 + ``` + + - ``, min interval to report to boolean state of contact + sensor + - ``, max interval to report to boolean state of contact + sensor + - ``, node id of contact sensor + +- Press down `INT` button, boolean state True will report to chip-tool + + > GPIO 20 connects to `INT` button. + +- After press down `INT` button over `min-interva>` seconds, and release `INT` + button, boolean state False will report to chip-tool diff --git a/examples/lighting-app/bouffalolab/bl702l/with_pw_rpc.gni b/examples/lighting-app/bouffalolab/bl702l/with_pw_rpc.gni index 5d7ce27c99df3d..91ad078fb6adf6 100644 --- a/examples/lighting-app/bouffalolab/bl702l/with_pw_rpc.gni +++ b/examples/lighting-app/bouffalolab/bl702l/with_pw_rpc.gni @@ -21,5 +21,4 @@ import("${chip_root}/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni") import("${chip_root}/examples/platform/bouffalolab/bl702l/args.gni") chip_enable_pw_rpc = true -chip_build_pw_trace_lib = false #pw_trace_BACKEND = "$dir_pw_trace_tokenized" From 422e391ce1d3b48e1ee62480253d8a4fc45be18b Mon Sep 17 00:00:00 2001 From: wyhong Date: Thu, 16 Jan 2025 13:59:48 +0800 Subject: [PATCH 6/7] change contact sensor zap to version 103 --- .github/workflows/examples-bouffalolab.yaml | 51 +++++-------------- .../data_model/contact-sensor-app.matter | 11 ++-- .../data_model/contact-sensor-app.zap | 16 +++--- scripts/setup/requirements.bouffalolab.txt | 3 +- 4 files changed, 26 insertions(+), 55 deletions(-) diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 5af3b4cc90d9ab..776c744fe868a6 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -58,25 +58,15 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl602dk-light-easyflash \ - --target bouffalolab-bl602dk-light-mfd-littlefs \ - --target bouffalolab-bl602dk-light-rpc-115200-littlefs \ + --target bouffalolab-bl602dk-light-wifi-littlefs-mfd-rpc \ build \ --copy-artifacts-to out/artifacts \ " - name: Prepare some bloat report from the previous builds run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl602 bl602 lighting-app \ - out/artifacts/bouffalolab-bl602dk-light-easyflash/chip-bl602-lighting-example.out \ - /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl602 bl602+mfd lighting-app \ - out/artifacts/bouffalolab-bl602dk-light-mfd-littlefs/chip-bl602-lighting-example.out \ - /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl602 bl602+rpc lighting-app \ - out/artifacts/bouffalolab-bl602dk-light-rpc-115200-littlefs/chip-bl602-lighting-example.out \ + bl602 bl602+mfd+littlefs+rpc lighting-app \ + out/artifacts/bouffalolab-bl602dk-light-wifi-littlefs-mfd-rpc/chip-bl602-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out @@ -85,35 +75,25 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl706dk-light-easyflash \ - --target bouffalolab-bl706dk-light-mfd-littlefs \ - --target bouffalolab-bl706dk-light-ethernet-littlefs \ + --target bouffalolab-bl706dk-light-ethernet-easyflash \ --target bouffalolab-bl706dk-light-wifi-littlefs \ - --target bouffalolab-bl706dk-light-rpc-115200-littlefs \ + --target bouffalolab-bl706dk-light-thread-littlefs-mfd-rpc \ build \ --copy-artifacts-to out/artifacts \ " - name: Prepare some bloat report from the previous builds run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702 bl702 lighting-app \ - out/artifacts/bouffalolab-bl706dk-light-easyflash/chip-bl702-lighting-example.out \ - /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702 bl702+mfd lighting-app \ - out/artifacts/bouffalolab-bl706dk-light-mfd-littlefs/chip-bl702-lighting-example.out \ - /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702 bl706-eth lighting-app \ - out/artifacts/bouffalolab-bl706dk-light-ethernet-littlefs/chip-bl702-lighting-example.out \ + bl702 bl702+eth lighting-app \ + out/artifacts/bouffalolab-bl706dk-light-ethernet-easyflash/chip-bl702-lighting-example.out \ /tmp/bloat_reports/ .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702 bl706-wifi lighting-app \ + bl702 bl702+wifi lighting-app \ out/artifacts/bouffalolab-bl706dk-light-wifi-littlefs/chip-bl702-lighting-example.out \ /tmp/bloat_reports/ .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702 bl702+rpc lighting-app \ - out/artifacts/bouffalolab-bl706dk-light-rpc-115200-littlefs/chip-bl702-lighting-example.out \ + bl702 bl706+mfd+rpc+littlefs lighting-app \ + out/artifacts/bouffalolab-bl706dk-light-thread-littlefs-mfd-rpc/chip-bl702-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out @@ -123,20 +103,15 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl704ldk-light-easyflash \ - --target bouffalolab-bl704ldk-light-mfd-littlefs \ + --target bouffalolab-bl704ldk-light-thread-littlefs-mfd \ build \ --copy-artifacts-to out/artifacts \ " - name: Prepare some bloat report from the previous builds run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702l bl702l lighting-app \ - out/artifacts/bouffalolab-bl704ldk-light-easyflash/chip-bl702l-lighting-example.out \ - /tmp/bloat_reports/ - .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - bl702l bl702l+mfd lighting-app \ - out/artifacts/bouffalolab-bl704ldk-light-mfd-littlefs/chip-bl702l-lighting-example.out \ + bl702l bl702l+mfd+littlefs lighting-app \ + out/artifacts/bouffalolab-bl704ldk-light-thread-littlefs-mfd/chip-bl702l-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out diff --git a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter index f12c88c86598a1..38f62673b4e5b7 100644 --- a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter +++ b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.matter @@ -833,7 +833,6 @@ cluster GeneralCommissioning = 48 { provisional readonly attribute access(read: administer) optional int16u TCMinRequiredVersion = 6; provisional readonly attribute access(read: administer) optional bitmap16 TCAcknowledgements = 7; provisional readonly attribute access(read: administer) optional boolean TCAcknowledgementsRequired = 8; - provisional readonly attribute access(read: administer) optional int32u TCUpdateDeadline = 9; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; readonly attribute event_id eventList[] = 65530; @@ -1241,7 +1240,7 @@ cluster GeneralDiagnostics = 51 { /** Take a snapshot of system time and epoch time. */ command TimeSnapshot(): TimeSnapshotResponse = 1; /** Request a variable length payload response. */ - command access(invoke: manage) PayloadTestRequest(PayloadTestRequestRequest): PayloadTestResponse = 3; + command PayloadTestRequest(PayloadTestRequestRequest): PayloadTestResponse = 3; } /** The Software Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ @@ -1809,10 +1808,10 @@ cluster IcdManagement = 70 { readonly attribute access(read: administer) optional MonitoringRegistrationStruct registeredClients[] = 3; readonly attribute access(read: administer) optional int32u ICDCounter = 4; readonly attribute optional int16u clientsSupportedPerFabric = 5; - readonly attribute optional UserActiveModeTriggerBitmap userActiveModeTriggerHint = 6; - readonly attribute optional char_string<128> userActiveModeTriggerInstruction = 7; - readonly attribute optional OperatingModeEnum operatingMode = 8; - readonly attribute optional int32u maximumCheckInBackOff = 9; + provisional readonly attribute optional UserActiveModeTriggerBitmap userActiveModeTriggerHint = 6; + provisional readonly attribute optional char_string<128> userActiveModeTriggerInstruction = 7; + provisional readonly attribute optional OperatingModeEnum operatingMode = 8; + provisional readonly attribute optional int32u maximumCheckInBackOff = 9; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; readonly attribute event_id eventList[] = 65530; diff --git a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap index bce092c500a726..64b82d1d73bb0d 100644 --- a/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap +++ b/examples/contact-sensor-app/bouffalolab/data_model/contact-sensor-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 104, + "featureLevel": 103, "creator": "zap", "keyValuePairs": [ { @@ -41,16 +41,14 @@ "code": 22, "profileId": 259, "label": "MA-rootdevice", - "name": "MA-rootdevice", - "deviceTypeOrder": 0 + "name": "MA-rootdevice" }, "deviceTypes": [ { "code": 22, "profileId": 259, "label": "MA-rootdevice", - "name": "MA-rootdevice", - "deviceTypeOrder": 0 + "name": "MA-rootdevice" } ], "deviceVersions": [ @@ -3973,16 +3971,14 @@ "code": 21, "profileId": 259, "label": "MA-contactsensor", - "name": "MA-contactsensor", - "deviceTypeOrder": 0 + "name": "MA-contactsensor" }, "deviceTypes": [ { "code": 21, "profileId": 259, "label": "MA-contactsensor", - "name": "MA-contactsensor", - "deviceTypeOrder": 0 + "name": "MA-contactsensor" } ], "deviceVersions": [ @@ -4515,4 +4511,4 @@ "parentEndpointIdentifier": null } ] -} \ No newline at end of file +} diff --git a/scripts/setup/requirements.bouffalolab.txt b/scripts/setup/requirements.bouffalolab.txt index 933330c0a4ad82..2abdd5f27c873a 100644 --- a/scripts/setup/requirements.bouffalolab.txt +++ b/scripts/setup/requirements.bouffalolab.txt @@ -4,4 +4,5 @@ ecdsa>=0.18.0 qrcode==7.4.2 bitarray==2.6.0 python_stdnum==1.18 -pycryptodome>=3.20.0 \ No newline at end of file +pycryptodome>=3.20.0 +construct>=2.10.70 \ No newline at end of file From 404f7e86cc4f8e3f8d4bef07d2174e3978265a73 Mon Sep 17 00:00:00 2001 From: wyhong Date: Wed, 22 Jan 2025 11:20:09 +0800 Subject: [PATCH 7/7] add pbuf ram support on matter --- .gitmodules | 5 + docs/guides/bouffalolab/getting_started.md | 15 +- .../guides/bouffalolab/matter_factory_data.md | 155 ++- .../lighting-app/bouffalolab/bl602/BUILD.gn | 11 +- .../lighting-app/bouffalolab/bl616/BUILD.gn | 6 + .../lighting-app/bouffalolab/bl616/args.gni | 11 +- .../lighting-app/bouffalolab/bl702/BUILD.gn | 2 +- .../lighting-app/bouffalolab/bl702l/BUILD.gn | 2 +- .../bouffalolab/bl602/ldscripts/flash_rom.ld | 7 +- .../bouffalolab/bl602/lwipopts/lwipopts.h | 30 +- .../platform/bouffalolab/bl616/lwipopts.h | 21 +- .../common/bouffalo_sdk/platform_port.cpp | 5 +- .../common/iot_sdk/platform_port.cpp | 3 +- .../bouffalolab/common/plat/platform.cpp | 3 +- scripts/build/build/targets.py | 1 + scripts/build/builders/bouffalolab.py | 14 +- scripts/checkout_submodules.py | 2 +- .../flashing/bouffalolab_firmware_utils.py | 123 +- .../bouffalolab/generate_factory_data.py | 54 +- .../BL602/NetworkCommissioningDriver.cpp | 2 +- .../common/CHIPDevicePlatformConfig.h | 2 + .../common/DiagnosticDataProviderImpl.cpp | 8 +- .../common/DiagnosticDataProviderImpl.h | 1 + .../bouffalolab/common/SystemPlatformConfig.h | 1 - src/system/SystemPacketBuffer.h | 2 + third_party/bouffalolab/bl602/bl_iot_sdk.gni | 20 +- .../bouffalolab/bl616/bouffalo_sdk.gni | 24 +- third_party/bouffalolab/bl702/bl_iot_sdk.gni | 1 + third_party/bouffalolab/bl702l/bl_iot_sdk.gni | 1 + third_party/bouffalolab/bouffalo_sdk | 1 + .../bouffalolab/patches/lwip/lwippools.h | 0 third_party/bouffalolab/patches/lwip/mem.c | 1041 +++++++++++++++++ third_party/bouffalolab/repo | 2 +- 33 files changed, 1458 insertions(+), 118 deletions(-) create mode 160000 third_party/bouffalolab/bouffalo_sdk create mode 100644 third_party/bouffalolab/patches/lwip/lwippools.h create mode 100644 third_party/bouffalolab/patches/lwip/mem.c diff --git a/.gitmodules b/.gitmodules index c2b9a95a5e0345..3fe46e9e125d34 100644 --- a/.gitmodules +++ b/.gitmodules @@ -345,3 +345,8 @@ path = third_party/re2/src url = https://github.com/google/re2.git platforms = linux,darwin +[submodule "third_party/bouffalolab/bouffalo_sdk"] + path = third_party/bouffalolab/bouffalo_sdk + url = git@github.com:bouffalolab/bouffalo_sdk_private.git + branch = master + platforms = bouffalo_sdk diff --git a/docs/guides/bouffalolab/getting_started.md b/docs/guides/bouffalolab/getting_started.md index eb96bc8da04728..844e1dcf2ce7c9 100644 --- a/docs/guides/bouffalolab/getting_started.md +++ b/docs/guides/bouffalolab/getting_started.md @@ -17,24 +17,31 @@ git clone --recurse-submodules https://github.com/project-chip/connectedhomeip.g git clone --depth=1 https://github.com/project-chip/connectedhomeip.git ``` -- check out `Bouffalo Lab` platform support repos as follows: +- Check out necessary submodules + Checkout `BL_IOT_SDK` for `BL602`, `BL702` and `BL702L` platform: ``` - scripts/checkout_submodules.py --shallow --recursive --platform bouffalolab + ./scripts/checkout_submodules.py --shallow --recursive --platform bouffalolab ``` + Checkout `bouffalo_sdk` for `BL616` platform: + ``` + ./scripts/checkout_submodules.py --shallow --recursive --platform bouffalo_sdk + ``` + > Please contact `Bouffalo Lab` for `BL616` SDK access. + If you want to checkout Matter Linux example and development tools, please try as follows: ``` - scripts/checkout_submodules.py --shallow --recursive --platform linux bouffalolab + ./scripts/checkout_submodules.py --shallow --recursive --platform linux bouffalolab ``` Or if you want to checkout Matter Darwin example and development tools, please try as follows: ``` - scripts/checkout_submodules.py --shallow --recursive --platform darwin bouffalolab + ./scripts/checkout_submodules.py --shallow --recursive --platform darwin bouffalolab ``` # Setup build environment diff --git a/docs/guides/bouffalolab/matter_factory_data.md b/docs/guides/bouffalolab/matter_factory_data.md index 9021cd80f61815..c6018a7d56e686 100644 --- a/docs/guides/bouffalolab/matter_factory_data.md +++ b/docs/guides/bouffalolab/matter_factory_data.md @@ -71,7 +71,7 @@ Script tool call `chip-cert` to generate test certificates and verify certificates. Please run below command to compile `chip-cert` tool under `connnectedhomeip` -repo. +repo for Linux platform. ```shell ./scripts/build/build_examples.py --target linux-x64-chip-cert build @@ -111,24 +111,45 @@ repo. Please reference to `--help` for more detail. -## Generate with default test certificates +## Generate with default configuration -- Run following command to generate all plain text factory data +- Default setting uses the following parameters - Please create output folder first. Here takes `out/test-cert` as example. + - PAI certification: [test PAI certification](../../../credentials/test/attestation/Chip-Test-PAI-FFF1-8000-Key.pem) + + - Vendor ID for DAC: 0xFFF1; Vendor ID for CD: 0x130d + + - Product ID for DAC: 0x8000, Product ID for CD: 0x1001 + + +- Run following command to generate all plain text factory data + + Please create output folder first. Here takes `out/test-cert` as example. + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert + ``` + + - Check DAC certificate. Here takes `out_130d_1001_106_dac_cert.pem` as generated test certificate. ```shell - ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert + openssl x509 -noout -text -in out/test-cert/out_130d_1001_106_dac_cert.pem ``` -- Run following command to generate factory data which encrypt private of - device attestation data + - Check Certification Declare. Here takes `out_130d_1001_cd.der` as generated test certificate. ```shell - ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --key + ./out/linux-x64-chip-cert/chip-cert print-cd out/test-cert/out_130d_1001_cd.der ``` - > An example of hex string of 16 bytes: 12345678123456781234567812345678 +- Run following command to generate factory data which encrypt private of + device attestation data + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --key + ``` + + > An example of hex string of 16 bytes: 12345678123456781234567812345678. After command executes successfully, the output folder will has files as below: @@ -148,48 +169,122 @@ After command executes successfully, the output folder will has files as below: - On board information which file name ends with `onboard.txt` - Matter factory data which file name ends with `mfd.bin`. +## Generate with VID/PID input + + + ## Generate with self-defined PAA/PAI certificates Self-defined PAA/PAI certificates may use in development and test scenario. But, user should know it has limit to work with real ecosystem. -- Export environment variables in terminal for easy operations +- Export environment variables in terminal for certificates generation - ``` - export TEST_CERT_VENDOR_ID=130D # Vendor ID hex string - export TEST_CERT_CN=BFLB # Common Name - ``` + ``` + export TEST_CERT_VENDOR_ID=130D # Vendor ID hex string + export TEST_CERT_PRODUCT_ID=1001 # Product ID hex string + export TEST_CERT_CN=BFLB # Common Name + ``` -- Generate PAA certificate and key to `out/cert` folder. +- Generate PAA certificate and key to `out/cert` folder. + + ```shell + ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type a --subject-cn "${TEST_CERT_CN} PAA 01" --valid-from "2020-10-15 14:23:43" --lifetime 7305 --out-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --subject-vid ${TEST_CERT_VENDOR_ID} + ``` + + - Check PAA certificate ```shell - mkdir out/test-cert - ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type a --subject-cn "${TEST_CERT_CN} PAA 01" --valid-from "2020-10-15 14:23:43" --lifetime 7305 --out-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --subject-vid ${TEST_CERT_VENDOR_ID} + openssl x509 -noout -text -in out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem ``` -- Convert PAA PEM format file to PAA DER format file +- Convert PAA PEM format file to PAA DER format file + + ```shell + ./out/linux-x64-chip-cert/chip-cert convert-cert -d out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.der + ``` + + > Please save this PAA DER format file which will be used by `chip-tool` + > during commissioning. + +- Generate PAI certificate and key: + + ```shell + ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type i --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --valid-from "2020-10-15 14:23:43" --lifetime 7305 --ca-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem + ``` + + - Check PAI certificate + + ```shell + openssl x509 -noout -text -in out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem + ``` + +- Generate `MFD` in plain text data with same VID/PID in DAC and CD + + - Use same environment variables `TEST_CERT_VENDOR_ID` and `TEST_CERT_PRODUCT_ID` for CD. + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --paa_cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --paa_key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --pai_cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --pai_key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --dac_pid 0x${TEST_CERT_PRODUCT_ID} --vendor_id 0x${TEST_CERT_VENDOR_ID} --product_id 0x${TEST_CERT_PRODUCT_ID} + ``` + + > Appending `--key ` option to enable encrypt + > private key of attestation device data. + + - Check DAC certificate. Here takes `out_130d_1001_1349_dac_cert.pem` as generated test certification. ```shell - ./out/linux-x64-chip-cert/chip-cert convert-cert -d out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.der + openssl x509 -noout -text -in out/test-cert/out_130d_1001_1349_dac_cert.pem ``` - > Please save this PAA DER format file which will be used by `chip-tool` - > during commissioning. + - Check PAA/PAI/DAC certificate chain. -- Generate PAI certificate and key: + ```shell + ./out/linux-x64-chip-cert/chip-cert validate-att-cert --dac out/test-cert/out_130d_1001_1349_dac_cert.pem --pai out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --paa out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem + ``` + + - Check Certification Declare. Here takes `out_130d_1001_cd.der` as generated test certification. ```shell - ./out/linux-x64-chip-cert/chip-cert gen-att-cert --type i --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --valid-from "2020-10-15 14:23:43" --lifetime 7305 --ca-key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --out out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem + ./out/linux-x64-chip-cert/chip-cert print-cd out/test-cert/out_130d_1001_cd.der ``` -- Generate `MFD` in plain text data +- Generate `MFD` in plain text data with different VID/PID in DAC and CD + - Export vendor ID and product ID for CD + ```shell - ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --paa_cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --paa_key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --pai_cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --pai_key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem + export TEST_CD_VENDOR_ID=730D # Vendor ID hex string + export TEST_CD_PRODUCT_ID=7001 # Product ID hex string + ``` + + - Run script to generate DAC/CD and MFD. + + ```shell + ./scripts/tools/bouffalolab/generate_factory_data.py --output out/test-cert --paa_cert out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem --paa_key out/test-cert/Chip-PAA-Key-${TEST_CERT_VENDOR_ID}.pem --pai_cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --pai_key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --dac_pid 0x${TEST_CERT_PRODUCT_ID} --vendor_id 0x${TEST_CD_VENDOR_ID} --product_id 0x${TEST_CD_PRODUCT_ID} + ``` + + > Appending `--key ` option to enable encrypt + > private key of attestation device data. + > + > Please use --`vendor_name` and `--product_name` to change vendor name and product name. + + - Check DAC certificate. Here takes `out_130d_1001_1349_dac_cert.pem` as generated test certification. + + ```shell + openssl x509 -noout -text -in out/test-cert/out_130d_1001_1349_dac_cert.pem + ``` + + - Check PAA/PAI/DAC certificate chain. + + ```shell + ./out/linux-x64-chip-cert/chip-cert validate-att-cert --dac out/test-cert/out_130d_1001_1349_dac_cert.pem --pai out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --paa out/test-cert/Chip-PAA-Cert-${TEST_CERT_VENDOR_ID}.pem + ``` + + - Check Certification Declare. Here takes `out_730D_7001_cd.der` as generated test certification. + + ```shell + ./out/linux-x64-chip-cert/chip-cert print-cd out/test-cert/out_130d_1001_cd.der ``` - - > Appending `--key ` option to enable encrypt - > private key of attestation device data. ## Generate with self-defined DAC certificate and key @@ -200,14 +295,14 @@ user should know it has limit to work with real ecosystem. ``` export TEST_CERT_VENDOR_ID=130D # Vendor ID hex string - export TEST_CERT_PRODUCT_ID=1001 # Vendor ID hex string + export TEST_CERT_PRODUCT_ID=1001 # Product ID hex string export TEST_CERT_CN=BFLB # Common Name ``` - Generate DAC certificate and key ```shell - out/linux-x64-chip-cert/chip-cert gen-att-cert --type d --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --subject-pid ${TEST_CERT_VENDOR_ID} --valid-from "2020-10-16 14:23:43" --lifetime 5946 --ca-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-DAC-Key-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem --out out/test-cert/Chip-DAC-Cert-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem + out/linux-x64-chip-cert/chip-cert gen-att-cert --type d --subject-cn "${TEST_CERT_CN} PAI 01" --subject-vid ${TEST_CERT_VENDOR_ID} --subject-pid ${TEST_CERT_PRODUCT_ID} --valid-from "2020-10-16 14:23:43" --lifetime 5946 --ca-key out/test-cert/Chip-PAI-Key-${TEST_CERT_VENDOR_ID}.pem --ca-cert out/test-cert/Chip-PAI-Cert-${TEST_CERT_VENDOR_ID}.pem --out-key out/test-cert/Chip-DAC-Key-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem --out out/test-cert/Chip-DAC-Cert-${TEST_CERT_VENDOR_ID}-${TEST_CERT_PRODUCT_ID}.pem ``` > **Note**, `--valid-from` and `--lifetime` should be in `--valid-from` and diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index c45251824fefbb..39dc4c3a6e911e 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -97,7 +97,7 @@ bouffalolab_executable("lighting_app") { output_name = "chip-bl602-lighting-example.out" defines = [ - "APP_TASK_STACK_SIZE=2044", + "APP_TASK_STACK_SIZE=4096", "CHIP_UART_BAUDRATE=${baudrate}", "START_ENTRY=bfl_main", "SYS_AOS_LOOP_ENABLE", @@ -110,6 +110,10 @@ bouffalolab_executable("lighting_app") { defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] + if (enable_lwip_pbuf_ram) { + defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ] + } + bl_plat_name = "bl602" sources = [ "${examples_plat_dir}/common/route_hook/bl_route_hook.c", @@ -228,6 +232,11 @@ bouffalolab_executable("lighting_app") { inputs = [ ldscript ] if (chip_print_memory_usage) { + + if (enable_lwip_pbuf_ram) { + ldflags += [ "-Wl,--defsym=__RAM_PBUF_POOL=0" ] + } + ldflags += [ "-Wl,--print-memory-usage", "-fstack-usage", diff --git a/examples/lighting-app/bouffalolab/bl616/BUILD.gn b/examples/lighting-app/bouffalolab/bl616/BUILD.gn index 6671db3f9f7a6d..19848ba5792fdf 100644 --- a/examples/lighting-app/bouffalolab/bl616/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl616/BUILD.gn @@ -72,6 +72,7 @@ bouffalo_sdk("sdk") { "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_seconds}", "OTA_AUTO_REBOOT_DELAY=${ota_auto_reboot_delay_seconds}", "CHIP_UART_BAUDRATE=${baudrate}", + "CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE=388", ] defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] @@ -108,6 +109,7 @@ bouffalolab_executable("lighting_app") { "CHIP_UART_BAUDRATE=${baudrate}", "BL616_ENABLE", "START_ENTRY=main", + "CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE=388", ] defines += @@ -121,6 +123,10 @@ bouffalolab_executable("lighting_app") { defines += [ "BOOT_PIN_RESET=2" ] } + if (enable_lwip_pbuf_ram) { + defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ] + } + defines += [ "BL616DK" ] sources = [ diff --git a/examples/lighting-app/bouffalolab/bl616/args.gni b/examples/lighting-app/bouffalolab/bl616/args.gni index d031a4b769ec88..aa60a4234e0c07 100644 --- a/examples/lighting-app/bouffalolab/bl616/args.gni +++ b/examples/lighting-app/bouffalolab/bl616/args.gni @@ -19,16 +19,7 @@ import("${chip_root}/src/platform/bouffalolab/BL616/args.gni") bouffalo_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/pw_backends/log" -pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" -pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" - -chip_detail_logging = true +chip_detail_logging = false # use -Os instead of -Og is_debug = false - -pw_build_LINK_DEPS = [ - "$dir_pw_assert:impl", - "$dir_pw_log:impl", -] diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index 9cec7d240e0ff7..5ac21970289e20 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -129,7 +129,7 @@ bouffalolab_executable("lighting_app") { bl_plat_name = "bl702" defines = [ - "APP_TASK_STACK_SIZE=2048", + "APP_TASK_STACK_SIZE=4096", "CHIP_UART_BAUDRATE=${baudrate}", "START_ENTRY=bl702_main", ] diff --git a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn index c004af4134dfc2..de9210b4b1b714 100644 --- a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn @@ -106,7 +106,7 @@ bouffalolab_executable("lighting_app") { bl_plat_name = "bl702l" defines = [ - "APP_TASK_STACK_SIZE=2048", + "APP_TASK_STACK_SIZE=4096", "CHIP_UART_BAUDRATE=${baudrate}", "START_ENTRY=bl702_main", ] diff --git a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld index 206f89bd077fd3..6393c9d2d75663 100644 --- a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld +++ b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld @@ -11,7 +11,9 @@ __RFTLV_HEAD1_L = (0x41524150); /* PAPA */ __RAM_START = 0x4200C000; __RAM_END = 0x4200C000 + 256K - __EM_SIZE; /* leave 8K left for BLE */ -__RAM_TCM_LEN = (16K + 16K + 48K + 64K + 64K - 16K - 16K); +__RAM_PBUF_POOL = DEFINED(__RAM_PBUF_POOL) ? __RAM_PBUF_POOL : 30K; + +__RAM_TCM_LEN = (16K + 16K + 48K + 64K + 64K - 16K - 16K + 30K - 12K - __RAM_PBUF_POOL); __RAM_WIFI_LEN = (__RAM_END - __RAM_START - __RAM_TCM_LEN); MEMORY @@ -173,6 +175,9 @@ SECTIONS *libwifi_drv.a:bl_utils.o(.bss*) *(.wifi_ram*) . = ALIGN(16); + + KEEP(*libCHIP.a:*(.bss.*PlatformManagerImp*)) + . = ALIGN(16); } > ram_wifi PROVIDE( _heap_wifi_start = . ); diff --git a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h index 93c14da58cfbbb..8fa1bb48722710 100644 --- a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h +++ b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h @@ -78,10 +78,6 @@ a lot of data that needs to be copied, this should be set high. */ #define MEMP_NUM_NETCONN (MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB + MEMP_NUM_TCP_PCB_LISTEN) -/* ---------- Pbuf options ---------- */ -/* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ -#define PBUF_POOL_SIZE 20 - /* ---------- TCP options ---------- */ #define LWIP_TCP 1 #define IP_DEFAULT_TTL 64 @@ -269,17 +265,37 @@ a lot of data that needs to be copied, this should be set high. */ #define LWIP_NETIF_EXT_STATUS_CALLBACK 1 -/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS + 40 + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN) -#define LWIP_PBUF_FROM_CUSTOM_POOLS (0) - /* --------------------------------- ---------- MISC. options ---------- --------------------------------- */ +#if defined(CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM) && CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM +#define PBUF_POOL_SIZE 0 +#define MEM_LIBC_MALLOC 0 +#define MEM_USE_POOLS 0 +#define MEMP_USE_CUSTOM_POOLS 0 + +#include +#include +#define LWIP_PBUF_CUSTOM_DATA mem_size_t pool; + +#if defined(__cplusplus) +extern "C" const mem_size_t * memp_sizes; +extern "C" struct pbuf *pbuf_rightsize(struct pbuf *p, s16_t offset); +#else +extern const mem_size_t * memp_sizes; +extern struct pbuf *pbuf_rightsize(struct pbuf *p, s16_t offset); +#endif +#else + +#define PBUF_POOL_SIZE 20 +#define LWIP_PBUF_FROM_CUSTOM_POOLS (0) +#endif + #if defined(__cplusplus) extern "C" int bl_rand(void); extern "C" int * __errno(void); diff --git a/examples/platform/bouffalolab/bl616/lwipopts.h b/examples/platform/bouffalolab/bl616/lwipopts.h index 91d779fb9356e5..8e20897d1d3fd0 100644 --- a/examples/platform/bouffalolab/bl616/lwipopts.h +++ b/examples/platform/bouffalolab/bl616/lwipopts.h @@ -120,10 +120,9 @@ extern const int fhost_tcpip_priority; #define MEMP_NUM_UDP_PCB 16 #define MEMP_NUM_REASSDATA LWIP_MIN((IP_REASS_MAX_PBUFS), 5) -#define PBUF_POOL_SIZE 0 #define MEM_ALIGNMENT 4 #define MEM_SIZE 30720 -#define PBUF_POOL_BUFSIZE (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + 1280) +#define PBUF_POOL_BUFSIZE (1280 + 462 + 26) #define MEMP_MEM_MALLOC 1 // #define LWIP_HOOK_FILENAME "lwiphooks.h" @@ -177,4 +176,22 @@ extern const int fhost_tcpip_priority; #define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) \ u8_t variable_name[size] __attribute__((aligned(4))) __attribute__((section("SHAREDRAM"))) +#if defined(CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM) && CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM +#define PBUF_POOL_SIZE 0 + +#include +#include +#define LWIP_PBUF_CUSTOM_DATA mem_size_t pool; + +#if defined(__cplusplus) +extern "C" const mem_size_t * memp_sizes; +extern "C" struct pbuf *pbuf_rightsize(struct pbuf *p, s16_t offset); +#else +extern const mem_size_t * memp_sizes; +extern struct pbuf *pbuf_rightsize(struct pbuf *p, s16_t offset); +#endif +#else +#define PBUF_POOL_SIZE 20 +#endif + #endif /* LWIP_HDR_LWIPOPTS_H__ */ diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp index f92b527b410d3a..7e4693a5e4d764 100644 --- a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp @@ -56,8 +56,9 @@ extern "C" void vAssertCalled(void) printf("vAssertCalled, ra = %p in task %s\r\n", (void *) ra, pcTaskGetName(NULL)); } - while (true) - ; + abort(); + + while (true) ; } extern "C" void bflb_assert(void) __attribute__((weak, alias("vAssertCalled"))); diff --git a/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp index 64f8965ff8528e..4b91b2d868b3fd 100644 --- a/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp +++ b/examples/platform/bouffalolab/common/iot_sdk/platform_port.cpp @@ -178,8 +178,7 @@ extern "C" void vAssertCalled(void) portABORT(); - while (true) - ; + while (true) ; } extern "C" void user_vAssertCalled(void) __attribute__((weak, alias("vAssertCalled"))); diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index ef6a2452cdbb04..6455c45add2e94 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -234,7 +234,8 @@ CHIP_ERROR PlatformManagerImpl::PlatformInit(void) } else { - ChipLogError(NotSpecified, "sFactoryDataProvider.Init() failed"); + ChipLogError(NotSpecified, "factory data provider is failed to initialize, use example DAC provider."); + SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); } #else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 4af73192b578d4..2b5e7c6a03d037 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -731,6 +731,7 @@ def BuildBouffalolabTarget(): target.AppendModifier('mot', use_matter_openthread=True).OnlyIfRe('-(thread)') target.AppendModifier('memmonitor', enable_heap_monitoring=True) target.AppendModifier('coredump', enable_debug_coredump=True) + target.AppendModifier('pbuf-pool', enable_lwip_pbuf_ram=False).OnlyIfRe('-(bl602dk)') return target diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index d575259aafab7a..e1daaf8d9ca661 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -104,6 +104,7 @@ def __init__(self, enable_littlefs: bool = False, enable_pds: bool = False, enable_debug_coredump: bool = False, + enable_lwip_pbuf_ram: bool = True ): if 'BL602' == module_type: @@ -250,6 +251,9 @@ def __init__(self, self.argsOpt.append(f"chip_generate_link_map_file=true") + if enable_lwip_pbuf_ram: + self.argsOpt.append(f"enable_lwip_pbuf_ram=true") + try: self.argsOpt.append('bouffalolab_sdk_root="%s"' % os.environ['BOUFFALOLAB_SDK_ROOT']) except KeyError as err: @@ -285,16 +289,14 @@ def PreBuildCommand(self): def PostBuildCommand(self): - bouffalo_sdk_chips = ["bl616"] - abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") - - if self.chip_name not in bouffalo_sdk_chips: - abs_path_fw_raw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw") + if self.chip_name in ["bl616"]: + abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw") + else: + abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") if os.path.isfile(abs_path_fw): target_dir = self.output_dir.replace(self.chip_dir, "").strip("/") - abs_path_fw_bin = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") path_fw = os.path.join(target_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") path_flash_script = os.path.join(target_dir, self.app.AppNamePrefix(self.chip_name) + ".flash.py") diff --git a/scripts/checkout_submodules.py b/scripts/checkout_submodules.py index 0290182b5b4bff..f212b2832fe18e 100755 --- a/scripts/checkout_submodules.py +++ b/scripts/checkout_submodules.py @@ -28,7 +28,6 @@ 'ameba', 'android', 'asr', - 'bl602', 'bouffalolab', 'cc13xx_26xx', 'cc32xx', @@ -51,6 +50,7 @@ 'genio', 'openiotsdk', 'silabs_docker', + 'bouffalo_sdk' ]) Module = namedtuple('Module', 'name path platforms recursive') diff --git a/scripts/flashing/bouffalolab_firmware_utils.py b/scripts/flashing/bouffalolab_firmware_utils.py index e6ca898609102f..752ce228a02a8a 100755 --- a/scripts/flashing/bouffalolab_firmware_utils.py +++ b/scripts/flashing/bouffalolab_firmware_utils.py @@ -23,6 +23,7 @@ import shutil import subprocess import sys +import toml import coloredlogs import firmware_utils @@ -446,7 +447,69 @@ def exe_gen_ota_image_cmd(flashtool_exe): new_name = os.path.join(self.work_dir, "ota_images", fw_name + ota_img_name[len("FW_OTA"):]) os.system("mv {} {}".format(img, new_name)) - def exe_prog_cmd(flashtool_exe, mfd_addr): + + def construct_prog_confg(): + + iot_cfg = { + "param": { + "interface_type": "uart", + "comport_uart": self.args["port"], + "speed_uart": self.args["baudrate"], + "speed_jlink": "1000", + "chip_xtal": self.args["xtal"], + "ota": "", + "version": "", + "aes_key": "", + "aes_iv": "", + "addr": "0x0", + "publickey": "", + "privatekey": "" + }, + "check_box": { + "fw_download": True, + "mfg_download": False, + "media_download": False, + "romfs_download": False, + "psm_download": False, + "key_download": False, + "data_download": False, + "factory_download": True if self.args["dts"] else False, + "mfd_download": True if self.args["mfd"] else False, + "boot2_download": True if self.args["boot2"] else False, + "ckb_erase_all": "True" if self.args["erase"] else "False", + "partition_download": True if self.args["pt"] else False, + "encrypt": False, + "sign": False, + "single_download": False, + "auto_efuse_verify": False + }, + "input_path": { + "fw_bin_input": self.args['firmware'], + "mfg_bin_input": "", + "media_bin_input": "", + "romfs_dir_input": "", + "psm_bin_input": "", + "key_bin_input": "", + "data_bin_input": "", + "factory_bin_input": self.args["dts"], + "mfd_bin_input": self.args["mfd"], + "boot2_bin_input": self.args["boot2"], + "img_bin_input": "", + "pt_table_bin_input": self.args["pt"], + "publickey": "", + "privatekey": "" + } + } + + conf_toml = os.path.splitext(self.args['firmware'])[0] + "_config.toml" + + with open(conf_toml, "w", encoding="utf-8") as f: + toml.dump(iot_cfg, f) + + return conf_toml + + + def exe_prog_cmd(flashtool_exe, mfd_addr, flashtool_path): if not self.args["port"]: return @@ -454,33 +517,43 @@ def exe_prog_cmd(flashtool_exe, mfd_addr): if self.args["mfd"] and not mfd_addr: raise Exception("No MFD partition found in partition table.") - prog_cmd = [ - flashtool_exe, - "--port", self.args["port"], - "--baudrate", self.args["baudrate"], - "--chipname", self.args["chipname"], - "--firmware", self.args["firmware"], - "--dts", self.args["dts"], - "--pt", self.args["pt"], - ] + if self.args["mfd"] and not self.args["key"]: + conf_toml = construct_prog_confg() - if self.args["boot2"]: - prog_cmd += ["--boot2", self.args["boot2"]] + prog_cmd = [ + flashtool_exe, + "--chipname", self.args["chipname"], + "--config", conf_toml, + ] - if self.args["sk"]: - prog_cmd += ["--sk", self.args["sk"]] + else: + prog_cmd = [ + flashtool_exe, + "--port", self.args["port"], + "--baudrate", self.args["baudrate"], + "--chipname", self.args["chipname"], + "--firmware", self.args["firmware"], + "--dts", self.args["dts"], + "--pt", self.args["pt"], + ] - if mfd_addr and self.args["mfd_str"]: - if self.args["key"] and not self.args["iv"]: - logging.warning("mfd file has no iv, do NOT program mfd key.") - else: - prog_cmd += ["--dac_key", self.args["key"]] - prog_cmd += ["--dac_iv", self.args["iv"]] - prog_cmd += ["--dac_addr", hex(mfd_addr)] - prog_cmd += ["--dac_value", self.args["mfd_str"]] + if self.args["boot2"]: + prog_cmd += ["--boot2", self.args["boot2"]] + + if self.args["sk"]: + prog_cmd += ["--sk", self.args["sk"]] + + if mfd_addr and self.args["mfd_str"]: + if self.args["key"] and not self.args["iv"]: + logging.warning("mfd file has no iv, do NOT program mfd key.") + else: + prog_cmd += ["--dac_key", self.args["key"]] + prog_cmd += ["--dac_iv", self.args["iv"]] + prog_cmd += ["--dac_addr", hex(mfd_addr)] + prog_cmd += ["--dac_value", self.args["mfd_str"]] - if self.option.erase: - prog_cmd += ["--erase"] + if self.option.erase: + prog_cmd += ["--erase"] logging.info("firmware programming: {}".format(" ".join(prog_cmd))) process = subprocess.Popen(prog_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -500,7 +573,7 @@ def exe_prog_cmd(flashtool_exe, mfd_addr): os.chdir(self.work_dir) exe_gen_ota_image_cmd(flashtool_exe) - exe_prog_cmd(flashtool_exe, mfd_addr) + exe_prog_cmd(flashtool_exe, mfd_addr, flashtool_path) def bouffalo_sdk_prog(self): diff --git a/scripts/tools/bouffalolab/generate_factory_data.py b/scripts/tools/bouffalolab/generate_factory_data.py index 28f362ba2d3b21..d94c09e70f3fb9 100755 --- a/scripts/tools/bouffalolab/generate_factory_data.py +++ b/scripts/tools/bouffalolab/generate_factory_data.py @@ -132,7 +132,9 @@ def gen_test_certs(chip_cert: str, pai_cert: str = None, pai_key: str = None, dac_cert: str = None, - dac_key: str = None): + dac_key: str = None, + dac_product_id: int = None, + discriminator: int = None): def parse_cert_file(cert): @@ -188,7 +190,7 @@ def verify_certificates(chip_cert, paa_cert, pai_cert, dac_cert): log.info("Verify Certificate Chain: {}".format(" ".join(cmd))) subprocess.run(cmd) - def gen_dac_certificate(chip_cert, device_name, vendor_id, product_id, pai_cert, pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date): + def gen_dac_certificate(chip_cert, device_name, dac_vid, dac_pid, pai_cert, pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date, discriminator): def gen_valid_times(issue_date, expire_date): now = datetime.now() - timedelta(days=1) @@ -205,8 +207,8 @@ def gen_valid_times(issue_date, expire_date): cmd = [chip_cert, "gen-att-cert", "--type", "d", # device attestation certificate "--subject-cn", device_name + " Test DAC 0", - "--subject-vid", hex(vendor_id), - "--subject-pid", hex(product_id), + "--subject-vid", hex(dac_vid), + "--subject-pid", hex(dac_pid), "--ca-cert", pai_cert, "--ca-key", pai_key, "--out", dac_cert, @@ -229,7 +231,7 @@ def convert_pem_to_der(chip_cert, action, pem): return der - def gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd): + def gen_cd(chip_cert, paa_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd): if os.path.isfile(cd): return @@ -254,15 +256,29 @@ def gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_c "--dac-origin-product-id", hex(dac_product_id), ] + if paa_cert: + cmd += [ "--authorized-paa-cert", paa_cert ] + log.info("Generate CD: {}".format(" ".join(cmd))) subprocess.run(cmd) pai_vendor_id, pai_product_id, pai_issue_date, pai_expire_date = parse_cert_file(pai_cert) - dac_vendor_id = pai_vendor_id if pai_vendor_id else vendor_id - dac_product_id = pai_product_id if pai_product_id else product_id + dac_vendor_id = pai_vendor_id + + if dac_product_id is not None and pai_product_id is not None and dac_product_id != pai_product_id: + raise Exception("Specified product id for DAC certificate is not same as product id in PAI certificate.") + + if pai_product_id is not None: + dac_product_id = pai_product_id + + if dac_cert is None: + dac_disc_vp = "{}_{}_{}".format(hex(dac_vendor_id).split("x")[-1], hex(dac_product_id).split("x")[-1], discriminator) + dac_cert = os.path.join(output, "out_{}_dac_cert.pem".format(dac_disc_vp)) + dac_key = os.path.join(output, "out_{}_dac_key.pem".format(dac_disc_vp)) + gen_dac_certificate(chip_cert, device_name, dac_vendor_id, dac_product_id, pai_cert, - pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date) + pai_key, dac_cert, dac_key, pai_issue_date, pai_expire_date, discriminator) dac_cert_der = convert_pem_to_der(chip_cert, "convert-cert", dac_cert) dac_key_der = convert_pem_to_der(chip_cert, "convert-key", dac_key) @@ -273,7 +289,7 @@ def gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_c verify_certificates(chip_cert, paa_cert, pai_cert, dac_cert) - gen_cd(chip_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd) + gen_cd(chip_cert, paa_cert, dac_vendor_id, dac_product_id, vendor_id, product_id, cd_cert, cd_key, cd) return cd, pai_cert_der, dac_cert_der, dac_key_der @@ -446,10 +462,14 @@ def to_bytes(input): else: return None + def hex_to_int(hex_string): + return int(hex_string, 16) + parser = argparse.ArgumentParser(description="Bouffalo Lab Factory Data generator tool") parser.add_argument("--dac_cert", type=str, help="DAC certificate file.") parser.add_argument("--dac_key", type=str, help="DAC certificate privat key.") + parser.add_argument("--dac_pid", type=hex_to_int, help="Product Identification, hex string, used in DAC certificate. ") parser.add_argument("--passcode", type=int, help="Setup pincode, optional.") parser.add_argument("--pai_cert", type=str, default=TEST_PAI_CERT, help="PAI certificate file.") parser.add_argument("--cd", type=str, help="Certificate Declaration file.") @@ -459,9 +479,9 @@ def to_bytes(input): parser.add_argument("--spake2p_it", type=int, default=None, help="Spake2+ iteration count, optional.") parser.add_argument("--spake2p_salt", type=base64.b64decode, help="Spake2+ salt in hex string, optional.") - parser.add_argument("--vendor_id", type=int, default=0x130D, help="Vendor Identification, mandatory.") + parser.add_argument("--vendor_id", type=hex_to_int, default=0x130D, help="Vendor Identification, hex string, mandatory.") parser.add_argument("--vendor_name", type=str, default="Bouffalo Lab", help="Vendor Name string, optional.") - parser.add_argument("--product_id", type=int, default=0x1001, help="Product Identification, mandatory.") + parser.add_argument("--product_id", type=hex_to_int, default=0x1001, help="Product Identification, hex string, mandatory.") parser.add_argument("--product_name", type=str, default="Test Product", help="Product Name string, optional.") parser.add_argument("--product_part_no", type=str, help="Product Part number, optional.") @@ -486,6 +506,7 @@ def to_bytes(input): log.basicConfig(format='[%(levelname)s] %(message)s', level=log.INFO) + print (args.dac_pid) check_arg(args) passcode = gen_test_passcode(args.passcode) @@ -493,11 +514,8 @@ def to_bytes(input): unique_id = gen_test_unique_id(args.unique_id) spake2p_it, spake2p_salt, spake2p_verifier = gen_test_spake2(passcode, args.spake2p_it, args.spake2p_salt) - vp_info = "{}_{}".format(hex(args.vendor_id), hex(args.product_id)) - vp_disc_info = "{}_{}_{}".format(hex(args.vendor_id), hex(args.product_id), discriminator) - if args.dac_cert is None: - args.dac_cert = os.path.join(args.output, "out_{}_dac_cert.pem".format(vp_disc_info)) - args.dac_key = os.path.join(args.output, "out_{}_dac_key.pem".format(vp_disc_info)) + vp_info = "{}_{}".format(hex(args.vendor_id).split('x')[-1], hex(args.product_id).split('x')[-1]) + vp_disc_info = "{}_{}".format(vp_info, discriminator) if args.cd is None: args.cd = os.path.join(args.output, "out_{}_cd.der".format(vp_info)) @@ -515,7 +533,9 @@ def to_bytes(input): args.pai_cert, args.pai_key, args.dac_cert, - args.dac_key) + args.dac_key, + args.dac_pid, + discriminator) mfd_output = os.path.join(args.output, "out_{}_mfd.bin".format(vp_disc_info)) args.dac_cert = dac_cert_der diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index 87136268afd0d2..3da54f09457664 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -268,7 +268,7 @@ void BLWiFiDriver::OnScanWiFiNetworkDone() } wifi_mgmr_ap_item_t * ScanResult = (wifi_mgmr_ap_item_t *) pvPortMalloc(ap_num * sizeof(wifi_mgmr_ap_item_t)); - wifi_mgmr_get_scan_result(ScanResult, &ap_num, 0, mScanSSID); + wifi_mgmr_get_scan_result(ScanResult, &ap_num, mScanType, mScanSSID); if (ScanResult) { diff --git a/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h index bc34d9124b6d92..7f1bbf360fdd7f 100644 --- a/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h +++ b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h @@ -58,4 +58,6 @@ #define CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE 1 #elif CHIP_DEVICE_LAYER_TARGET_BL702 #define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1 +#elif CHIP_DEVICE_LAYER_TARGET_BL702L +#define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1 #endif diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp index a5d70240ba5a04..12a58f995d7d26 100644 --- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp @@ -78,7 +78,10 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeap CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { #if CHIP_DEVICE_LAYER_TARGET_BL616 - return CHIP_ERROR_NOT_IMPLEMENTED; + struct meminfo info; + bflb_mem_usage(KMEM_HEAP, &info); + currentHeapHighWatermark = info.total_size - info.max_free_size; + #else #ifdef CFG_USE_PSRAM currentHeapHighWatermark = @@ -86,8 +89,9 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & cu #else currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize(); #endif - return CHIP_NO_ERROR; #endif + + return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h index 8001afb0544cb3..6ff0d07ad30d1e 100644 --- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h @@ -32,6 +32,7 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider static DiagnosticDataProviderImpl & GetDefaultInstance(); // ===== Methods that implement the PlatformManager abstract interface. + bool SupportsWatermarks() override { return true; } CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override; CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override; diff --git a/src/platform/bouffalolab/common/SystemPlatformConfig.h b/src/platform/bouffalolab/common/SystemPlatformConfig.h index 89a0a5a8f9a966..f82da0bfb5872d 100644 --- a/src/platform/bouffalolab/common/SystemPlatformConfig.h +++ b/src/platform/bouffalolab/common/SystemPlatformConfig.h @@ -38,7 +38,6 @@ struct ChipDeviceEvent; // #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(mbedtls_sha256_context) in hw_acc/sha256_alt.h #define CHIP_CONFIG_SHA256_CONTEXT_SIZE (32 + 64 + 64 + 19 * 32) #define CHIP_CONFIG_SHA256_CONTEXT_ALIGN 32 -#define CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE (388) #else // #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) diff --git a/src/system/SystemPacketBuffer.h b/src/system/SystemPacketBuffer.h index 5068822c7f22a4..9290b788d93e7e 100644 --- a/src/system/SystemPacketBuffer.h +++ b/src/system/SystemPacketBuffer.h @@ -172,6 +172,8 @@ class DLL_EXPORT PacketBuffer : private pbuf return kMaxSizeWithoutReserve; #elif CHIP_SYSTEM_PACKETBUFFER_FROM_CHIP_HEAP return this->alloc_size; +#elif CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM + return LWIP_MEM_ALIGN_SIZE(memp_sizes[this->pool]) - kStructureSize; #elif CHIP_SYSTEM_PACKETBUFFER_FROM_LWIP_CUSTOM_POOL // Temporary workaround for custom pbufs by assuming size to be PBUF_POOL_BUFSIZE if (this->flags & PBUF_FLAG_IS_CUSTOM) diff --git a/third_party/bouffalolab/bl602/bl_iot_sdk.gni b/third_party/bouffalolab/bl602/bl_iot_sdk.gni index ba564db1469bec..d634247c598ac2 100644 --- a/third_party/bouffalolab/bl602/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl602/bl_iot_sdk.gni @@ -20,6 +20,7 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" + enable_lwip_pbuf_ram = false enable_debug_coredump = false coredump_binary_id = 0 } @@ -63,6 +64,11 @@ template("bl_iot_sdk") { "-include", rebase_path("${invoker.freertos_config}", root_build_dir), ] + + if (defined(invoker.enable_lwip_pbuf_ram) && + invoker.enable_lwip_pbuf_ram) { + defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ] + } } source_set("${sdk_target_name}_soc") { @@ -906,6 +912,11 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/network/lwip_dhcpd", ] + if (defined(invoker.enable_lwip_pbuf_ram) && + invoker.enable_lwip_pbuf_ram) { + include_dirs += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip" ] + } + defines = [ "LWIP_IPV6=1" ] } @@ -927,7 +938,6 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/network/lwip/src/core/inet_chksum.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/init.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/ip.c", - "${bl_iot_sdk_root}/components/network/lwip/src/core/mem.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/memp.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/netif.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/pbuf.c", @@ -941,6 +951,14 @@ template("bl_iot_sdk") { "${bl_iot_sdk_root}/components/network/lwip/src/core/udp.c", ] + if (defined(invoker.enable_lwip_pbuf_ram) && + invoker.enable_lwip_pbuf_ram) { + sources += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip/mem.c" ] + } + else { + sources += [ "${bl_iot_sdk_root}/components/network/lwip/src/core/mem.c" ] + } + sources += [ "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/autoip.c", "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/dhcp.c", diff --git a/third_party/bouffalolab/bl616/bouffalo_sdk.gni b/third_party/bouffalolab/bl616/bouffalo_sdk.gni index 174b04b8160ae2..5a8652f4ad93a9 100644 --- a/third_party/bouffalolab/bl616/bouffalo_sdk.gni +++ b/third_party/bouffalolab/bl616/bouffalo_sdk.gni @@ -21,6 +21,7 @@ declare_args() { # Location of the bl616 SDK. bouffalo_sdk_root = "${chip_root}/third_party/bouffalolab/bouffalo_sdk" + enable_lwip_pbuf_ram = false enable_debug_coredump = false coredump_binary_id = 0 bouffalo_sdk_coredump_version = 1 @@ -72,6 +73,11 @@ template("bouffalo_sdk") { if (defined(invoker.defines)) { defines += invoker.defines } + + if (defined(invoker.enable_lwip_pbuf_ram) && + invoker.enable_lwip_pbuf_ram) { + defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ] + } } config("${sdk_target_name}_config_startup") { @@ -457,6 +463,7 @@ template("bouffalo_sdk") { "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtok.c", "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtokr.c", "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_vikmemcpy.c", + "${bouffalo_sdk_root}/components/libc/assert.c", "${bouffalo_sdk_root}/components/libc/printf.c", "${bouffalo_sdk_root}/components/libc/snprintf.c", "${bouffalo_sdk_root}/components/libc/sprintf.c", @@ -895,6 +902,11 @@ template("bouffalo_sdk") { include_dirs += [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd" ] + if (defined(invoker.enable_lwip_pbuf_ram) && + invoker.enable_lwip_pbuf_ram) { + include_dirs += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip" ] + } + defines = [ "CONFIG_LWIP", "CONFIG_MAC_TXQ_DEPTH=8", @@ -937,7 +949,6 @@ template("bouffalo_sdk") { "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_frag.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/mld6.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/nd6.c", - "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/memp.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/netif.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/pbuf.c", @@ -952,6 +963,17 @@ template("bouffalo_sdk") { "${bouffalo_sdk_root}/components/net/lwip/lwip/src/netif/ethernet.c", ] + if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) { + sources += [ + "${bouffalolab_iot_sdk_build_root}/patches/lwip/mem.c", + ] + } + else { + sources += [ + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c", + ] + } + sources += [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd/dhcp_server_raw.c", "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/lwiperf/lwiperf.c", diff --git a/third_party/bouffalolab/bl702/bl_iot_sdk.gni b/third_party/bouffalolab/bl702/bl_iot_sdk.gni index 76d35da758e883..45122f43c34021 100644 --- a/third_party/bouffalolab/bl702/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl702/bl_iot_sdk.gni @@ -21,6 +21,7 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" + enable_lwip_pbuf_ram = false enable_debug_coredump = false coredump_binary_id = 0 } diff --git a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni index ac608a72098cd6..514d25d2172427 100644 --- a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni +++ b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni @@ -21,6 +21,7 @@ import("${chip_root}/src/lib/lib.gni") declare_args() { bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" + enable_lwip_pbuf_ram = false enable_pds = false enable_debug_coredump = false coredump_binary_id = 0 diff --git a/third_party/bouffalolab/bouffalo_sdk b/third_party/bouffalolab/bouffalo_sdk new file mode 160000 index 00000000000000..42f58bf8eb9bfd --- /dev/null +++ b/third_party/bouffalolab/bouffalo_sdk @@ -0,0 +1 @@ +Subproject commit 42f58bf8eb9bfde342b1164ca3962096e0838411 diff --git a/third_party/bouffalolab/patches/lwip/lwippools.h b/third_party/bouffalolab/patches/lwip/lwippools.h new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/third_party/bouffalolab/patches/lwip/mem.c b/third_party/bouffalolab/patches/lwip/mem.c new file mode 100644 index 00000000000000..7d4cb9b9bb8a34 --- /dev/null +++ b/third_party/bouffalolab/patches/lwip/mem.c @@ -0,0 +1,1041 @@ +/** + * @file + * Dynamic memory manager + * + * This is a lightweight replacement for the standard C library malloc(). + * + * If you want to use the standard C library malloc() instead, define + * MEM_LIBC_MALLOC to 1 in your lwipopts.h + * + * To let mem_malloc() use pools (prevents fragmentation and is much faster than + * a heap but might waste some memory), define MEM_USE_POOLS to 1, define + * MEMP_USE_CUSTOM_POOLS to 1 and create a file "lwippools.h" that includes a list + * of pools like this (more pools can be added between _START and _END): + * + * Define three pools with sizes 256, 512, and 1512 bytes + * LWIP_MALLOC_MEMPOOL_START + * LWIP_MALLOC_MEMPOOL(20, 256) + * LWIP_MALLOC_MEMPOOL(10, 512) + * LWIP_MALLOC_MEMPOOL(5, 1512) + * LWIP_MALLOC_MEMPOOL_END + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ + +#include "lwip/opt.h" +#include "lwip/mem.h" +#include "lwip/def.h" +#include "lwip/sys.h" +#include "lwip/stats.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#include + +#if MEM_LIBC_MALLOC +#include /* for malloc()/free() */ +#endif + +/* This is overridable for tests only... */ +#ifndef LWIP_MEM_ILLEGAL_FREE +#define LWIP_MEM_ILLEGAL_FREE(msg) LWIP_ASSERT(msg, 0) +#endif + +#define MEM_STATS_INC_LOCKED(x) SYS_ARCH_LOCKED(MEM_STATS_INC(x)) +#define MEM_STATS_INC_USED_LOCKED(x, y) SYS_ARCH_LOCKED(MEM_STATS_INC_USED(x, y)) +#define MEM_STATS_DEC_USED_LOCKED(x, y) SYS_ARCH_LOCKED(MEM_STATS_DEC_USED(x, y)) + +#if MEM_OVERFLOW_CHECK +#define MEM_SANITY_OFFSET MEM_SANITY_REGION_BEFORE_ALIGNED +#define MEM_SANITY_OVERHEAD (MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED) +#else +#define MEM_SANITY_OFFSET 0 +#define MEM_SANITY_OVERHEAD 0 +#endif + +#if MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK +/** + * Check if a mep element was victim of an overflow or underflow + * (e.g. the restricted area after/before it has been altered) + * + * @param p the mem element to check + * @param size allocated size of the element + * @param descr1 description of the element source shown on error + * @param descr2 description of the element source shown on error + */ +void +mem_overflow_check_raw(void *p, size_t size, const char *descr1, const char *descr2) +{ +#if MEM_SANITY_REGION_AFTER_ALIGNED || MEM_SANITY_REGION_BEFORE_ALIGNED + u16_t k; + u8_t *m; + +#if MEM_SANITY_REGION_AFTER_ALIGNED > 0 + m = (u8_t *)p + size; + for (k = 0; k < MEM_SANITY_REGION_AFTER_ALIGNED; k++) { + if (m[k] != 0xcd) { + char errstr[128]; + snprintf(errstr, sizeof(errstr), "detected mem overflow in %s%s", descr1, descr2); + LWIP_ASSERT(errstr, 0); + } + } +#endif /* MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ + +#if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 + m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED; + for (k = 0; k < MEM_SANITY_REGION_BEFORE_ALIGNED; k++) { + if (m[k] != 0xcd) { + char errstr[128]; + snprintf(errstr, sizeof(errstr), "detected mem underflow in %s%s", descr1, descr2); + LWIP_ASSERT(errstr, 0); + } + } +#endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 */ +#else + LWIP_UNUSED_ARG(p); + LWIP_UNUSED_ARG(desc); + LWIP_UNUSED_ARG(descr); +#endif +} + +/** + * Initialize the restricted area of a mem element. + */ +void +mem_overflow_init_raw(void *p, size_t size) +{ +#if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 + u8_t *m; +#if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 + m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED; + memset(m, 0xcd, MEM_SANITY_REGION_BEFORE_ALIGNED); +#endif +#if MEM_SANITY_REGION_AFTER_ALIGNED > 0 + m = (u8_t *)p + size; + memset(m, 0xcd, MEM_SANITY_REGION_AFTER_ALIGNED); +#endif +#else /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ + LWIP_UNUSED_ARG(p); + LWIP_UNUSED_ARG(desc); +#endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */ +} +#endif /* MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK */ + +#if MEM_LIBC_MALLOC || MEM_USE_POOLS + +/** mem_init is not used when using pools instead of a heap or using + * C library malloc(). + */ +void +mem_init(void) +{ +} + +/** mem_trim is not used when using pools instead of a heap or using + * C library malloc(): we can't free part of a pool element and the stack + * support mem_trim() to return a different pointer + */ +void * +mem_trim(void *mem, mem_size_t size) +{ + LWIP_UNUSED_ARG(size); + return mem; +} +#endif /* MEM_LIBC_MALLOC || MEM_USE_POOLS */ + +#if MEM_LIBC_MALLOC +/* lwIP heap implemented using C library malloc() */ + +/* in case C library malloc() needs extra protection, + * allow these defines to be overridden. + */ +#ifndef mem_clib_free +#define mem_clib_free free +#endif +#ifndef mem_clib_malloc +#define mem_clib_malloc malloc +#endif +#ifndef mem_clib_calloc +#define mem_clib_calloc calloc +#endif + +#if LWIP_STATS && MEM_STATS +#define MEM_LIBC_STATSHELPER_SIZE LWIP_MEM_ALIGN_SIZE(sizeof(mem_size_t)) +#else +#define MEM_LIBC_STATSHELPER_SIZE 0 +#endif + +/** + * Allocate a block of memory with a minimum of 'size' bytes. + * + * @param size is the minimum size of the requested block in bytes. + * @return pointer to allocated memory or NULL if no free memory was found. + * + * Note that the returned value must always be aligned (as defined by MEM_ALIGNMENT). + */ +void * +mem_malloc(mem_size_t size) +{ + void *ret = mem_clib_malloc(size + MEM_LIBC_STATSHELPER_SIZE); + if (ret == NULL) { + MEM_STATS_INC_LOCKED(err); + } else { + LWIP_ASSERT("malloc() must return aligned memory", LWIP_MEM_ALIGN(ret) == ret); +#if LWIP_STATS && MEM_STATS + *(mem_size_t *)ret = size; + ret = (u8_t *)ret + MEM_LIBC_STATSHELPER_SIZE; + MEM_STATS_INC_USED_LOCKED(used, size); +#endif + } + return ret; +} + +/** Put memory back on the heap + * + * @param rmem is the pointer as returned by a previous call to mem_malloc() + */ +void +mem_free(void *rmem) +{ + LWIP_ASSERT("rmem != NULL", (rmem != NULL)); + LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem))); +#if LWIP_STATS && MEM_STATS + rmem = (u8_t *)rmem - MEM_LIBC_STATSHELPER_SIZE; + MEM_STATS_DEC_USED_LOCKED(used, *(mem_size_t *)rmem); +#endif + mem_clib_free(rmem); +} + +#elif MEM_USE_POOLS + +/* lwIP heap implemented with different sized pools */ + +/** + * Allocate memory: determine the smallest pool that is big enough + * to contain an element of 'size' and get an element from that pool. + * + * @param size the size in bytes of the memory needed + * @return a pointer to the allocated memory or NULL if the pool is empty + */ +void * +mem_malloc(mem_size_t size) +{ + void *ret; + struct memp_malloc_helper *element = NULL; + memp_t poolnr; + mem_size_t required_size = size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper)); + + for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr = (memp_t)(poolnr + 1)) { + /* is this pool big enough to hold an element of the required size + plus a struct memp_malloc_helper that saves the pool this element came from? */ + if (required_size <= memp_pools[poolnr]->size) { + element = (struct memp_malloc_helper *)memp_malloc(poolnr); + if (element == NULL) { + /* No need to DEBUGF or ASSERT: This error is already taken care of in memp.c */ +#if MEM_USE_POOLS_TRY_BIGGER_POOL + /** Try a bigger pool if this one is empty! */ + if (poolnr < MEMP_POOL_LAST) { + continue; + } +#endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */ + MEM_STATS_INC_LOCKED(err); + return NULL; + } + break; + } + } + if (poolnr > MEMP_POOL_LAST) { + LWIP_ASSERT("mem_malloc(): no pool is that big!", 0); + MEM_STATS_INC_LOCKED(err); + return NULL; + } + + /* save the pool number this element came from */ + element->poolnr = poolnr; + /* and return a pointer to the memory directly after the struct memp_malloc_helper */ + ret = (u8_t *)element + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper)); + +#if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) + /* truncating to u16_t is safe because struct memp_desc::size is u16_t */ + element->size = (u16_t)size; + MEM_STATS_INC_USED_LOCKED(used, element->size); +#endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */ +#if MEMP_OVERFLOW_CHECK + /* initialize unused memory (diff between requested size and selected pool's size) */ + memset((u8_t *)ret + size, 0xcd, memp_pools[poolnr]->size - size); +#endif /* MEMP_OVERFLOW_CHECK */ + return ret; +} + +/** + * Free memory previously allocated by mem_malloc. Loads the pool number + * and calls memp_free with that pool number to put the element back into + * its pool + * + * @param rmem the memory element to free + */ +void +mem_free(void *rmem) +{ + struct memp_malloc_helper *hmem; + + LWIP_ASSERT("rmem != NULL", (rmem != NULL)); + LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem))); + + /* get the original struct memp_malloc_helper */ + /* cast through void* to get rid of alignment warnings */ + hmem = (struct memp_malloc_helper *)(void *)((u8_t *)rmem - LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper))); + + LWIP_ASSERT("hmem != NULL", (hmem != NULL)); + LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem))); + LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX)); + + MEM_STATS_DEC_USED_LOCKED(used, hmem->size); +#if MEMP_OVERFLOW_CHECK + { + u16_t i; + LWIP_ASSERT("MEM_USE_POOLS: invalid chunk size", + hmem->size <= memp_pools[hmem->poolnr]->size); + /* check that unused memory remained untouched (diff between requested size and selected pool's size) */ + for (i = hmem->size; i < memp_pools[hmem->poolnr]->size; i++) { + u8_t data = *((u8_t *)rmem + i); + LWIP_ASSERT("MEM_USE_POOLS: mem overflow detected", data == 0xcd); + } + } +#endif /* MEMP_OVERFLOW_CHECK */ + + /* and put it in the pool we saved earlier */ + memp_free(hmem->poolnr, hmem); +} + +#else /* MEM_USE_POOLS */ +/* lwIP replacement for your libc malloc() */ + +/** + * The heap is made up as a list of structs of this type. + * This does not have to be aligned since for getting its size, + * we only use the macro SIZEOF_STRUCT_MEM, which automatically aligns. + */ +struct mem { + + /** Buffer size used for Matter application */ + mem_size_t mem_size; + + /** index (-> ram[next]) of the next struct */ + mem_size_t next; + /** index (-> ram[prev]) of the previous struct */ + mem_size_t prev; + /** 1: this area is used; 0: this area is unused */ + u8_t used; +#if MEM_OVERFLOW_CHECK + /** this keeps track of the user allocation size for guard checks */ + mem_size_t user_size; +#endif +}; + +/** All allocated blocks will be MIN_SIZE bytes big, at least! + * MIN_SIZE can be overridden to suit your needs. Smaller values save space, + * larger values could prevent too small blocks to fragment the RAM too much. */ +#ifndef MIN_SIZE +#define MIN_SIZE 12 +#endif /* MIN_SIZE */ +/* some alignment macros: we define them here for better source code layout */ +#define MIN_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MIN_SIZE) +#define SIZEOF_STRUCT_MEM LWIP_MEM_ALIGN_SIZE(sizeof(struct mem)) +#define MEM_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SIZE) + +/** If you want to relocate the heap to external memory, simply define + * LWIP_RAM_HEAP_POINTER as a void-pointer to that location. + * If so, make sure the memory at that location is big enough (see below on + * how that space is calculated). */ +#ifndef LWIP_RAM_HEAP_POINTER +/** the heap. we need one struct mem at the end and some room for alignment */ +LWIP_DECLARE_MEMORY_ALIGNED(ram_heap, MEM_SIZE_ALIGNED + (2U * SIZEOF_STRUCT_MEM)); +#define LWIP_RAM_HEAP_POINTER ram_heap +#endif /* LWIP_RAM_HEAP_POINTER */ + +/** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */ +static u8_t *ram; +/** the last entry, always unused! */ +static struct mem *ram_end; + +/** concurrent access protection */ +#if !NO_SYS +static sys_mutex_t mem_mutex; +#endif + +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + +static volatile u8_t mem_free_count; + +/* Allow mem_free from other (e.g. interrupt) context */ +#define LWIP_MEM_FREE_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_free) +#define LWIP_MEM_FREE_PROTECT() SYS_ARCH_PROTECT(lev_free) +#define LWIP_MEM_FREE_UNPROTECT() SYS_ARCH_UNPROTECT(lev_free) +#define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc) +#define LWIP_MEM_ALLOC_PROTECT() SYS_ARCH_PROTECT(lev_alloc) +#define LWIP_MEM_ALLOC_UNPROTECT() SYS_ARCH_UNPROTECT(lev_alloc) +#define LWIP_MEM_LFREE_VOLATILE volatile + +#else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + +/* Protect the heap only by using a mutex */ +#define LWIP_MEM_FREE_DECL_PROTECT() +#define LWIP_MEM_FREE_PROTECT() sys_mutex_lock(&mem_mutex) +#define LWIP_MEM_FREE_UNPROTECT() sys_mutex_unlock(&mem_mutex) +/* mem_malloc is protected using mutex AND LWIP_MEM_ALLOC_PROTECT */ +#define LWIP_MEM_ALLOC_DECL_PROTECT() +#define LWIP_MEM_ALLOC_PROTECT() +#define LWIP_MEM_ALLOC_UNPROTECT() +#define LWIP_MEM_LFREE_VOLATILE + +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + +/** pointer to the lowest free block, this is used for faster search */ +static struct mem * LWIP_MEM_LFREE_VOLATILE lfree; + +#if MEM_SANITY_CHECK +static void mem_sanity(void); +#define MEM_SANITY() mem_sanity() +#else +#define MEM_SANITY() +#endif + +#if MEM_OVERFLOW_CHECK +static void +mem_overflow_init_element(struct mem *mem, mem_size_t user_size) +{ + void *p = (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET; + mem->user_size = user_size; + mem_overflow_init_raw(p, user_size); +} + +static void +mem_overflow_check_element(struct mem *mem) +{ + void *p = (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET; + mem_overflow_check_raw(p, mem->user_size, "heap", ""); +} +#else /* MEM_OVERFLOW_CHECK */ +#define mem_overflow_init_element(mem, size) +#define mem_overflow_check_element(mem) +#endif /* MEM_OVERFLOW_CHECK */ + +static struct mem * +ptr_to_mem(mem_size_t ptr) +{ + return (struct mem *)(void *)&ram[ptr]; +} + +static mem_size_t +mem_to_ptr(void *mem) +{ + return (mem_size_t)((u8_t *)mem - ram); +} + +/** + * "Plug holes" by combining adjacent empty struct mems. + * After this function is through, there should not exist + * one empty struct mem pointing to another empty struct mem. + * + * @param mem this points to a struct mem which just has been freed + * @internal this function is only called by mem_free() and mem_trim() + * + * This assumes access to the heap is protected by the calling function + * already. + */ +static void +plug_holes(struct mem *mem) +{ + struct mem *nmem; + struct mem *pmem; + + LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram); + LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end); + LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0); + + /* plug hole forward */ + LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED); + + nmem = ptr_to_mem(mem->next); + if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) { + /* if mem->next is unused and not end of ram, combine mem and mem->next */ + if (lfree == nmem) { + lfree = mem; + } + mem->next = nmem->next; + if (nmem->next != MEM_SIZE_ALIGNED) { + ptr_to_mem(nmem->next)->prev = mem_to_ptr(mem); + } + } + + /* plug hole backward */ + pmem = ptr_to_mem(mem->prev); + if (pmem != mem && pmem->used == 0) { + /* if mem->prev is unused, combine mem and mem->prev */ + if (lfree == mem) { + lfree = pmem; + } + pmem->next = mem->next; + if (mem->next != MEM_SIZE_ALIGNED) { + ptr_to_mem(mem->next)->prev = mem_to_ptr(pmem); + } + } +} + +/** + * Zero the heap and initialize start, end and lowest-free + */ +void +mem_init(void) +{ + struct mem *mem; + + LWIP_ASSERT("Sanity check alignment", + (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT - 1)) == 0); + + /* align the heap */ + ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER); + /* initialize the start of the heap */ + mem = (struct mem *)(void *)ram; + mem->next = MEM_SIZE_ALIGNED; + mem->prev = 0; + mem->used = 0; + /* initialize the end of the heap */ + ram_end = ptr_to_mem(MEM_SIZE_ALIGNED); + ram_end->used = 1; + ram_end->next = MEM_SIZE_ALIGNED; + ram_end->prev = MEM_SIZE_ALIGNED; + MEM_SANITY(); + + /* initialize the lowest-free pointer to the start of the heap */ + lfree = (struct mem *)(void *)ram; + + MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED); + + if (sys_mutex_new(&mem_mutex) != ERR_OK) { + LWIP_ASSERT("failed to create mem_mutex", 0); + } +} + +/* Check if a struct mem is correctly linked. + * If not, double-free is a possible reason. + */ +static int +mem_link_valid(struct mem *mem) +{ + struct mem *nmem, *pmem; + mem_size_t rmem_idx; + rmem_idx = mem_to_ptr(mem); + nmem = ptr_to_mem(mem->next); + pmem = ptr_to_mem(mem->prev); + if ((mem->next > MEM_SIZE_ALIGNED) || (mem->prev > MEM_SIZE_ALIGNED) || + ((mem->prev != rmem_idx) && (pmem->next != rmem_idx)) || + ((nmem != ram_end) && (nmem->prev != rmem_idx))) { + return 0; + } + return 1; +} + +#if MEM_SANITY_CHECK +static void +mem_sanity(void) +{ + struct mem *mem; + u8_t last_used; + + /* begin with first element here */ + mem = (struct mem *)ram; + LWIP_ASSERT("heap element used valid", (mem->used == 0) || (mem->used == 1)); + last_used = mem->used; + LWIP_ASSERT("heap element prev ptr valid", mem->prev == 0); + LWIP_ASSERT("heap element next ptr valid", mem->next <= MEM_SIZE_ALIGNED); + LWIP_ASSERT("heap element next ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->next) == ptr_to_mem(mem->next))); + + /* check all elements before the end of the heap */ + for (mem = ptr_to_mem(mem->next); + ((u8_t *)mem > ram) && (mem < ram_end); + mem = ptr_to_mem(mem->next)) { + LWIP_ASSERT("heap element aligned", LWIP_MEM_ALIGN(mem) == mem); + LWIP_ASSERT("heap element prev ptr valid", mem->prev <= MEM_SIZE_ALIGNED); + LWIP_ASSERT("heap element next ptr valid", mem->next <= MEM_SIZE_ALIGNED); + LWIP_ASSERT("heap element prev ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->prev) == ptr_to_mem(mem->prev))); + LWIP_ASSERT("heap element next ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->next) == ptr_to_mem(mem->next))); + + if (last_used == 0) { + /* 2 unused elements in a row? */ + LWIP_ASSERT("heap element unused?", mem->used == 1); + } else { + LWIP_ASSERT("heap element unused member", (mem->used == 0) || (mem->used == 1)); + } + + LWIP_ASSERT("heap element link valid", mem_link_valid(mem)); + + /* used/unused altering */ + last_used = mem->used; + } + LWIP_ASSERT("heap end ptr sanity", mem == ptr_to_mem(MEM_SIZE_ALIGNED)); + LWIP_ASSERT("heap element used valid", mem->used == 1); + LWIP_ASSERT("heap element prev ptr valid", mem->prev == MEM_SIZE_ALIGNED); + LWIP_ASSERT("heap element next ptr valid", mem->next == MEM_SIZE_ALIGNED); +} +#endif /* MEM_SANITY_CHECK */ + +/** + * Put a struct mem back on the heap + * + * @param rmem is the data portion of a struct mem as returned by a previous + * call to mem_malloc() + */ +void +mem_free(void *rmem) +{ + struct mem *mem; + LWIP_MEM_FREE_DECL_PROTECT(); + + if (rmem == NULL) { + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n")); + return; + } + if ((((mem_ptr_t)rmem) & (MEM_ALIGNMENT - 1)) != 0) { + LWIP_MEM_ILLEGAL_FREE("mem_free: sanity check alignment"); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: sanity check alignment\n")); + /* protect mem stats from concurrent access */ + MEM_STATS_INC_LOCKED(illegal); + return; + } + + /* Get the corresponding struct mem: */ + /* cast through void* to get rid of alignment warnings */ + mem = (struct mem *)(void *)((u8_t *)rmem - (SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET)); + + if ((u8_t *)mem < ram || (u8_t *)rmem + MIN_SIZE_ALIGNED > (u8_t *)ram_end) { + LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory"); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n")); + /* protect mem stats from concurrent access */ + MEM_STATS_INC_LOCKED(illegal); + return; + } +#if MEM_OVERFLOW_CHECK + mem_overflow_check_element(mem); +#endif + /* protect the heap from concurrent access */ + LWIP_MEM_FREE_PROTECT(); + /* mem has to be in a used state */ + if (!mem->used) { + LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory: double free"); + LWIP_MEM_FREE_UNPROTECT(); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory: double free?\n")); + /* protect mem stats from concurrent access */ + MEM_STATS_INC_LOCKED(illegal); + return; + } + + if (!mem_link_valid(mem)) { + LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory: non-linked: double free"); + LWIP_MEM_FREE_UNPROTECT(); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory: non-linked: double free?\n")); + /* protect mem stats from concurrent access */ + MEM_STATS_INC_LOCKED(illegal); + return; + } + + /* mem is now unused. */ + mem->used = 0; + + if (mem < lfree) { + /* the newly freed struct is now the lowest */ + lfree = mem; + } + + MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram))); + + /* finally, see if prev or next are free also */ + plug_holes(mem); + MEM_SANITY(); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 1; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_FREE_UNPROTECT(); +} + +/** + * Shrink memory returned by mem_malloc(). + * + * @param rmem pointer to memory allocated by mem_malloc the is to be shrinked + * @param new_size required size after shrinking (needs to be smaller than or + * equal to the previous size) + * @return for compatibility reasons: is always == rmem, at the moment + * or NULL if newsize is > old size, in which case rmem is NOT touched + * or freed! + */ +void * +mem_trim(void *rmem, mem_size_t new_size) +{ + mem_size_t size, newsize; + mem_size_t ptr, ptr2; + struct mem *mem, *mem2; + /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */ + LWIP_MEM_FREE_DECL_PROTECT(); + + /* Expand the size of the allocated memory region so that we can + adjust for alignment. */ + newsize = (mem_size_t)LWIP_MEM_ALIGN_SIZE(new_size); + if (newsize < MIN_SIZE_ALIGNED) { + /* every data block must be at least MIN_SIZE_ALIGNED long */ + newsize = MIN_SIZE_ALIGNED; + } +#if MEM_OVERFLOW_CHECK + newsize += MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED; +#endif + if ((newsize > MEM_SIZE_ALIGNED) || (newsize < new_size)) { + return NULL; + } + + LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram && + (u8_t *)rmem < (u8_t *)ram_end); + + if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) { + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n")); + /* protect mem stats from concurrent access */ + MEM_STATS_INC_LOCKED(illegal); + return rmem; + } + /* Get the corresponding struct mem ... */ + /* cast through void* to get rid of alignment warnings */ + mem = (struct mem *)(void *)((u8_t *)rmem - (SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET)); +#if MEM_OVERFLOW_CHECK + mem_overflow_check_element(mem); +#endif + /* ... and its offset pointer */ + ptr = mem_to_ptr(mem); + + size = (mem_size_t)((mem_size_t)(mem->next - ptr) - (SIZEOF_STRUCT_MEM + MEM_SANITY_OVERHEAD)); + LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size); + if (newsize > size) { + /* not supported */ + return NULL; + } + if (newsize == size) { + /* No change in size, simply return */ + return rmem; + } + + /* protect the heap from concurrent access */ + LWIP_MEM_FREE_PROTECT(); + + mem2 = ptr_to_mem(mem->next); + if (mem2->used == 0) { + /* The next struct is unused, we can simply move it at little */ + mem_size_t next; + LWIP_ASSERT("invalid next ptr", mem->next != MEM_SIZE_ALIGNED); + /* remember the old next pointer */ + next = mem2->next; + /* create new struct mem which is moved directly after the shrinked mem */ + ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + newsize); + if (lfree == mem2) { + lfree = ptr_to_mem(ptr2); + } + mem2 = ptr_to_mem(ptr2); + mem2->used = 0; + /* restore the next pointer */ + mem2->next = next; + /* link it back to mem */ + mem2->prev = ptr; + /* link mem to it */ + mem->next = ptr2; + /* last thing to restore linked list: as we have moved mem2, + * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not + * the end of the heap */ + if (mem2->next != MEM_SIZE_ALIGNED) { + ptr_to_mem(mem2->next)->prev = ptr2; + } + MEM_STATS_DEC_USED(used, (size - newsize)); + /* no need to plug holes, we've already done that */ + } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) { + /* Next struct is used but there's room for another struct mem with + * at least MIN_SIZE_ALIGNED of data. + * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem + * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED'). + * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty + * region that couldn't hold data, but when mem->next gets freed, + * the 2 regions would be combined, resulting in more free memory */ + ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + newsize); + LWIP_ASSERT("invalid next ptr", mem->next != MEM_SIZE_ALIGNED); + mem2 = ptr_to_mem(ptr2); + if (mem2 < lfree) { + lfree = mem2; + } + mem2->used = 0; + mem2->next = mem->next; + mem2->prev = ptr; + mem->next = ptr2; + if (mem2->next != MEM_SIZE_ALIGNED) { + ptr_to_mem(mem2->next)->prev = ptr2; + } + MEM_STATS_DEC_USED(used, (size - newsize)); + /* the original mem->next is used, so no need to plug holes! */ + } + /* else { + next struct mem is used but size between mem and mem2 is not big enough + to create another struct mem + -> don't do anyhting. + -> the remaining space stays unused since it is too small + } */ +#if MEM_OVERFLOW_CHECK + mem_overflow_init_element(mem, new_size); +#endif + MEM_SANITY(); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 1; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_FREE_UNPROTECT(); + return rmem; +} + +/** + * Allocate a block of memory with a minimum of 'size' bytes. + * + * @param size_in is the minimum size of the requested block in bytes. + * @return pointer to allocated memory or NULL if no free memory was found. + * + * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT). + */ +void * +mem_malloc(mem_size_t size_in) +{ + mem_size_t ptr, ptr2, size; + struct mem *mem, *mem2; +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + u8_t local_mem_free_count = 0; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + LWIP_MEM_ALLOC_DECL_PROTECT(); + + if (size_in == 0) { + return NULL; + } + + /* Expand the size of the allocated memory region so that we can + adjust for alignment. */ + size = (mem_size_t)LWIP_MEM_ALIGN_SIZE(size_in); + if (size < MIN_SIZE_ALIGNED) { + /* every data block must be at least MIN_SIZE_ALIGNED long */ + size = MIN_SIZE_ALIGNED; + } +#if MEM_OVERFLOW_CHECK + size += MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED; +#endif + if ((size > MEM_SIZE_ALIGNED) || (size < size_in)) { + return NULL; + } + + /* protect the heap from concurrent access */ + sys_mutex_lock(&mem_mutex); + LWIP_MEM_ALLOC_PROTECT(); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + /* run as long as a mem_free disturbed mem_malloc or mem_trim */ + do { + local_mem_free_count = 0; +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + + /* Scan through the heap searching for a free block that is big enough, + * beginning with the lowest free block. + */ + for (ptr = mem_to_ptr(lfree); ptr < MEM_SIZE_ALIGNED - size; + ptr = ptr_to_mem(ptr)->next) { + mem = ptr_to_mem(ptr); +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 0; + LWIP_MEM_ALLOC_UNPROTECT(); + /* allow mem_free or mem_trim to run */ + LWIP_MEM_ALLOC_PROTECT(); + if (mem_free_count != 0) { + /* If mem_free or mem_trim have run, we have to restart since they + could have altered our current struct mem. */ + local_mem_free_count = 1; + break; + } +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + + if ((!mem->used) && + (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) { + /* mem is not used and at least perfect fit is possible: + * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */ + + if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) { + /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing + * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem') + * -> split large block, create empty remainder, + * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if + * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size, + * struct mem would fit in but no data between mem2 and mem2->next + * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty + * region that couldn't hold data, but when mem->next gets freed, + * the 2 regions would be combined, resulting in more free memory + */ + ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + size); + LWIP_ASSERT("invalid next ptr",ptr2 != MEM_SIZE_ALIGNED); + /* create mem2 struct */ + mem2 = ptr_to_mem(ptr2); + mem2->used = 0; + mem2->next = mem->next; + mem2->prev = ptr; + /* and insert it between mem and mem->next */ + mem->next = ptr2; + mem->used = 1; + + if (mem2->next != MEM_SIZE_ALIGNED) { + ptr_to_mem(mem2->next)->prev = ptr2; + } + MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM)); + } else { + /* (a mem2 struct does no fit into the user data space of mem and mem->next will always + * be used at this point: if not we have 2 unused structs in a row, plug_holes should have + * take care of this). + * -> near fit or exact fit: do not split, no mem2 creation + * also can't move mem->next directly behind mem, since mem->next + * will always be used at this point! + */ + mem->used = 1; + MEM_STATS_INC_USED(used, mem->next - mem_to_ptr(mem)); + } +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT +mem_malloc_adjust_lfree: +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + if (mem == lfree) { + struct mem *cur = lfree; + /* Find next free block after mem and update lowest free pointer */ + while (cur->used && cur != ram_end) { +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + mem_free_count = 0; + LWIP_MEM_ALLOC_UNPROTECT(); + /* prevent high interrupt latency... */ + LWIP_MEM_ALLOC_PROTECT(); + if (mem_free_count != 0) { + /* If mem_free or mem_trim have run, we have to restart since they + could have altered our current struct mem or lfree. */ + goto mem_malloc_adjust_lfree; + } +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + cur = ptr_to_mem(cur->next); + } + lfree = cur; + LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used))); + } + LWIP_MEM_ALLOC_UNPROTECT(); + sys_mutex_unlock(&mem_mutex); + LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.", + (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end); + LWIP_ASSERT("mem_malloc: allocated memory properly aligned.", + ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0); + LWIP_ASSERT("mem_malloc: sanity check alignment", + (((mem_ptr_t)mem) & (MEM_ALIGNMENT - 1)) == 0); + +#if MEM_OVERFLOW_CHECK + mem_overflow_init_element(mem, size_in); +#endif + MEM_SANITY(); + + mem->mem_size = size_in; + if (size_in >= sizeof(struct pbuf)) { + struct pbuf *p_mem = (struct pbuf *)((u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET); + p_mem->pool = (mem_size_t*)mem - (mem_size_t*)memp_sizes; + } + + lfree->used = 0; + + return (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET; + } + } +#if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT + /* if we got interrupted by a mem_free, try again */ + } while (local_mem_free_count != 0); +#endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */ + MEM_STATS_INC(err); + LWIP_MEM_ALLOC_UNPROTECT(); + sys_mutex_unlock(&mem_mutex); + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size)); + return NULL; +} + +#endif /* MEM_USE_POOLS */ + +#if MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS) +void * +mem_calloc(mem_size_t count, mem_size_t size) +{ + return mem_clib_calloc(count, size); +} + +#else /* MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS) */ +/** + * Contiguously allocates enough space for count objects that are size bytes + * of memory each and returns a pointer to the allocated memory. + * + * The allocated memory is filled with bytes of value zero. + * + * @param count number of objects to allocate + * @param size size of the objects to allocate + * @return pointer to allocated memory / NULL pointer if there is an error + */ +void * +mem_calloc(mem_size_t count, mem_size_t size) +{ + void *p; + size_t alloc_size = (size_t)count * (size_t)size; + + if ((size_t)(mem_size_t)alloc_size != alloc_size) { + LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_calloc: could not allocate %"SZT_F" bytes\n", alloc_size)); + return NULL; + } + + /* allocate 'count' objects of size 'size' */ + p = mem_malloc((mem_size_t)alloc_size); + if (p) { + /* zero the memory */ + memset(p, 0, alloc_size); + } + return p; +} + +#endif /* MEM_LIBC_MALLOC && (!LWIP_STATS || !MEM_STATS) */ + +const mem_size_t * memp_sizes = (mem_size_t *)LWIP_RAM_HEAP_POINTER; + +struct pbuf * +pbuf_rightsize(struct pbuf *p, s16_t offset) +{ + LWIP_ASSERT("pbuf_rightsize NOT implemented", 0); + return NULL; +} diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index 75df6e87ffa10b..fd642ce8739972 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit 75df6e87ffa10b905c9dbb0efc5fd35f96955c55 +Subproject commit fd642ce8739972ae389dd3174e266284d1299b35