From 45986a32316adb93816085e2860d2b4fc6e251b7 Mon Sep 17 00:00:00 2001 From: ZIYANG LIU <46555470+pigletz2@users.noreply.github.com> Date: Wed, 4 Jan 2023 23:01:10 +0800 Subject: [PATCH 01/31] board name changed (#24249) if do not update here, build in vscode + docker fails --- .vscode/tasks.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.vscode/tasks.json b/.vscode/tasks.json index fd815494affee7..2dfa9587570c4d 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -621,12 +621,12 @@ "mbed-CY8CPROTO_062_4343W-shell-debug", "mbed-CY8CPROTO_062_4343W-shell-develop", "mbed-CY8CPROTO_062_4343W-shell-release", - "nrf-nrf52840-light", - "nrf-nrf52840-light-rpc", - "nrf-nrf52840-lock", - "nrf-nrf52840-pump", - "nrf-nrf52840-pump-controller", - "nrf-nrf52840-shell", + "nrf-nrf52840dk-light", + "nrf-nrf52840dk-light-rpc", + "nrf-nrf52840dk-lock", + "nrf-nrf52840dk-pump", + "nrf-nrf52840dk-pump-controller", + "nrf-nrf52840dk-shell", "nrf-nrf5340-light", "nrf-nrf5340-light-rpc", "nrf-nrf5340-lock", From 34f9130609314ea76c6ac06f93feb314eee438b3 Mon Sep 17 00:00:00 2001 From: Kamil Kasperczyk <66371704+kkasperczyk-no@users.noreply.github.com> Date: Wed, 4 Jan 2023 16:16:33 +0100 Subject: [PATCH 02/31] [nrfconnect] Removed types from Kconfig overrides (#24250) Types should not be used in case of overriding existing kconfig definitions to make sure that compilation will fail due to creating a config without a type in case of name change in the origin kconfig option. --- .../nrfconnect/chip-module/Kconfig.defaults | 97 ------------------- .../nrfconnect/chip-module/Kconfig.features | 11 --- .../chip-module/Kconfig.hci_rpmsg.defaults | 20 ---- .../chip-module/Kconfig.mcuboot.defaults | 34 ------- .../Kconfig.multiprotocol_rpmsg.defaults | 21 ---- 5 files changed, 183 deletions(-) diff --git a/config/nrfconnect/chip-module/Kconfig.defaults b/config/nrfconnect/chip-module/Kconfig.defaults index fedfc8cab28f57..67d4b1f23cf88a 100644 --- a/config/nrfconnect/chip-module/Kconfig.defaults +++ b/config/nrfconnect/chip-module/Kconfig.defaults @@ -21,7 +21,6 @@ if CHIP config LOG - bool default y if LOG @@ -35,33 +34,26 @@ choice MATTER_LOG_LEVEL_CHOICE endchoice config LOG_DEFAULT_LEVEL - int default 2 config CHIP_LOG_SIZE_OPTIMIZATION - bool default y endif config PRINTK_SYNC - bool default y config ASSERT - bool default y config HW_STACK_PROTECTION - bool default y config FPU - bool default y config SHELL - bool default y config PTHREAD_IPC @@ -70,117 +62,91 @@ config PTHREAD_IPC # Generic networking options config NET_SOCKETS_POSIX_NAMES - bool default n # Application stack size config MAIN_STACK_SIZE - int default 8192 config INIT_STACKS - bool default y # Disable certain parts of Zephyr IPv6 stack config NET_IPV6_NBR_CACHE - bool default n config NET_IPV6_MLD - bool default y config NET_IF_MCAST_IPV6_ADDR_COUNT - int default 14 # Network buffers config NET_PKT_RX_COUNT - int default 16 config NET_PKT_TX_COUNT - int default 16 config NET_BUF_RX_COUNT - int default 80 config NET_BUF_TX_COUNT - int default 80 # Bluetooth Low Energy configs config BT - bool default y config BT_PERIPHERAL - bool default y config BT_PERIPHERAL_PREF_MIN_INT - int default 36 config BT_PERIPHERAL_PREF_MAX_INT - int default 36 config BT_GAP_AUTO_UPDATE_CONN_PARAMS - bool default y config BT_GATT_DYNAMIC_DB - bool default y config BT_DEVICE_NAME_DYNAMIC - bool default y config BT_DEVICE_NAME_MAX - int default 15 config BT_MAX_CONN - int default 1 config BT_L2CAP_TX_MTU - int default 247 config BT_BUF_ACL_RX_SIZE - int default 251 config BT_BUF_ACL_TX_SIZE - int default 251 config BT_RX_STACK_SIZE - int default 1200 # Enable NFC support config CHIP_NFC_COMMISSIONING - bool default y config CHIP_OTA_REQUESTOR - bool default y # All boards besides nRF7002DK use QSPI NOR external flash if BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 config CHIP_QSPI_NOR - bool default y endif # BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 @@ -190,35 +156,29 @@ endif # BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 if BOARD_NRF7002DK_NRF5340_CPUAPP config CHIP_SPI_NOR - bool default y endif # BOARD_NRF7002DK_NRF5340_CPUAPP # Enable extended discovery config CHIP_EXTENDED_DISCOVERY - bool default y config NVS_LOOKUP_CACHE - bool default y config NVS_LOOKUP_CACHE_SIZE - int default 512 # Enable OpenThread config NET_L2_OPENTHREAD - bool default y if !WIFI_NRF700X if NET_L2_OPENTHREAD # Increase the default RX stack size config IEEE802154_NRF5_RX_STACK_SIZE - int default 1024 endif @@ -226,50 +186,39 @@ endif if CHIP_WIFI config NRF_WIFI_LOW_POWER - bool default n config MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG - bool default n config SYSTEM_WORKQUEUE_STACK_SIZE - int default 1120 # align these numbers to match the OpenThread config config NET_IF_UNICAST_IPV6_ADDR_COUNT - int default 6 config NET_IF_MCAST_IPV6_ADDR_COUNT - int default 8 config NET_SOCKETS_POSIX_NAMES - bool default n config MBEDTLS_SSL_OUT_CONTENT_LEN - int default 900 # options managed by IP4/IP6 simultaneous support # aligned here to match OpenThread config config NET_MAX_ROUTERS - int default 1 config NET_MAX_CONN - int default 4 config SHELL_STACK_SIZE - int default 2616 config HEAP_MEM_POOL_SIZE - int default 200000 endif @@ -282,183 +231,139 @@ choice OPENTHREAD_SECURITY endchoice config PSA_CRYPTO_DRIVER_CC3XX - bool default n config OBERON_BACKEND - bool default y config MBEDTLS_ENABLE_HEAP - bool default y config MBEDTLS_HEAP_SIZE - int default 15360 config MBEDTLS_TLS_LIBRARY - bool default y config NRF_SECURITY_ADVANCED - bool default y config MBEDTLS_AES_C - bool default y config MBEDTLS_ECP_C - bool default y config MBEDTLS_ECP_DP_SECP256R1_ENABLED - bool default y config MBEDTLS_CTR_DRBG_C - bool default y config MBEDTLS_CIPHER_MODE_CTR - bool default y config MBEDTLS_ECJPAKE_C - bool default y config MBEDTLS_SHA256_C - bool default y config MBEDTLS_PK_C - bool default y config MBEDTLS_PK_WRITE_C - bool default y config MBEDTLS_X509_CREATE_C - bool default y if !CHIP_CRYPTO_PSA config MBEDTLS_X509_CSR_WRITE_C - bool default y if !CHIP_CRYPTO_PSA # Disable unneeded crypto operations config MBEDTLS_SHA384_C - bool default n config MBEDTLS_SHA512_C - bool default n config MBEDTLS_CIPHER_MODE_XTS - bool default n config MBEDTLS_CHACHA20_C - bool default n config MBEDTLS_POLY1305_C - bool default n config MBEDTLS_CHACHAPOLY_C - bool default n config MBEDTLS_GCM_C - bool default n config MBEDTLS_RSA_C - bool default n config PSA_WANT_KEY_TYPE_ARIA - bool default n config PSA_WANT_KEY_TYPE_CHACHA20 - bool default n config PSA_WANT_ALG_GCM - bool default n config PSA_WANT_ALG_CHACHA20_POLY1305 - bool default n config PSA_WANT_ALG_SHA_1 - bool default n config PSA_WANT_ALG_SHA_224 - bool default n config PSA_WANT_ALG_SHA_384 - bool default n config PSA_WANT_ALG_SHA_512 - bool default n config PSA_WANT_ALG_RIPEMD160 - bool default n config PSA_WANT_ALG_MD5 - bool default n config PSA_WANT_ALG_CFB - bool default n config PSA_WANT_ALG_OFB - bool default n # Disable not used shell modules config SENSOR_SHELL - bool default n config DEVICE_SHELL - bool default n config DATE_SHELL - bool default n config DEVMEM_SHELL - bool default n config MCUBOOT_SHELL - bool default n config CLOCK_CONTROL_NRF_SHELL - bool default n config FLASH_SHELL - bool default n # SoC series related configuration @@ -467,7 +372,6 @@ if SOC_SERIES_NRF52X # Increase maximum data length of PDU supported in the Controller config BT_CTLR_DATA_LENGTH_MAX - int default 251 endif # SOC_SERIES_NRF52X @@ -475,7 +379,6 @@ endif # SOC_SERIES_NRF52X if SOC_SERIES_NRF53X config UPDATEABLE_IMAGE_NUMBER - int default 2 # Generate random numbers using Xoroshiro algorithm instead of direct calls diff --git a/config/nrfconnect/chip-module/Kconfig.features b/config/nrfconnect/chip-module/Kconfig.features index 918a82685cad02..662d7074ebe0b3 100644 --- a/config/nrfconnect/chip-module/Kconfig.features +++ b/config/nrfconnect/chip-module/Kconfig.features @@ -49,11 +49,9 @@ config CHIP_QSPI_NOR if CHIP_QSPI_NOR config NORDIC_QSPI_NOR - bool default y config NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE - int default 16 endif # CHIP_QSPI_NOR @@ -71,7 +69,6 @@ config CHIP_SPI_NOR if CHIP_SPI_NOR config SPI_NOR_FLASH_LAYOUT_PAGE_SIZE - int default 4096 endif # CHIP_SPI_NOR @@ -96,41 +93,33 @@ if CHIP_DFU_OVER_BT_SMP # MCU Manager and SMP configuration config MCUMGR_SMP_BT_AUTHEN - bool default n config MCUMGR_BUF_COUNT - int default 6 # Increase BT MTU and RX buffer for big size DFU messages config BT_L2CAP_TX_MTU - int default 498 config BT_BUF_ACL_RX_SIZE - int default 502 # Increase MCUMGR_BUF_SIZE, as it must be big enough to fit MAX MTU + overhead and for single-image DFU default is 384 B config MCUMGR_BUF_SIZE - int default 1024 # Increase system workqueue size, as SMP is processed within it config SYSTEM_WORKQUEUE_STACK_SIZE - int default 2800 if SOC_SERIES_NRF53X # Enable custom SMP request to erase settings partition. config MCUMGR_GRP_ZEPHYR_BASIC - bool default y config MCUMGR_GRP_BASIC_CMD_STORAGE_ERASE - bool default y endif # SOC_SERIES_NRF53X diff --git a/config/nrfconnect/chip-module/Kconfig.hci_rpmsg.defaults b/config/nrfconnect/chip-module/Kconfig.hci_rpmsg.defaults index 8069d710047338..83290b2b492f28 100644 --- a/config/nrfconnect/chip-module/Kconfig.hci_rpmsg.defaults +++ b/config/nrfconnect/chip-module/Kconfig.hci_rpmsg.defaults @@ -17,83 +17,63 @@ # The purpose of this file is to define new default values of settings used when building hci_rpmsg child image for Matter samples. config LOG - bool default n config HEAP_MEM_POOL_SIZE - int default 8192 config MAIN_STACK_SIZE - int default 2048 config SYSTEM_WORKQUEUE_STACK_SIZE - int default 2048 config BT - bool default y config BT_HCI_RAW - bool default y config BT_MAX_CONN - int default 1 config BT_PERIPHERAL - bool default y config BT_CENTRAL - bool default n config BT_BUF_ACL_RX_SIZE - int default 502 config BT_BUF_ACL_TX_SIZE - int default 251 config BT_CTLR_DATA_LENGTH_MAX - int default 251 config BT_CTLR_ASSERT_HANDLER - bool default y config BT_HCI_RAW_RESERVE - int default 1 # Workaround: Unable to allocate command buffer when using K_NO_WAIT since # Host number of completed commands does not follow normal flow control. config BT_BUF_CMD_TX_COUNT - int default 10 config ASSERT - bool default y config DEBUG_INFO - bool default y config EXCEPTION_STACK_TRACE - bool default y config IPC_SERVICE - bool default y config MBOX - bool default y diff --git a/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults b/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults index b9c6dce1982fb7..72169ca50afd8e 100644 --- a/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults +++ b/config/nrfconnect/chip-module/Kconfig.mcuboot.defaults @@ -17,50 +17,39 @@ # The purpose of this file is to define new default values of settings used when building mcuboot child image for Matter samples. config MAIN_STACK_SIZE - int default 10240 config BOOT_SWAP_SAVE_ENCTLV - bool default n config BOOT_ENCRYPT_RSA - bool default n config BOOT_ENCRYPT_EC256 - bool default n config BOOT_ENCRYPT_X25519 - bool default n config BOOT_BOOTSTRAP - bool default n config PM - bool default n config FLASH - bool default y config FPROTECT - bool default y # nRF7002DK uses SPI NOR external flash if BOARD_NRF7002DK_NRF5340_CPUAPP config SPI - bool default y config SPI_NOR - bool default y choice SPI_NOR_SFDP @@ -68,15 +57,12 @@ choice SPI_NOR_SFDP endchoice config SPI_NOR_FLASH_LAYOUT_PAGE_SIZE - int default 4096 config MULTITHREADING - bool default y config PM_OVERRIDE_EXTERNAL_DRIVER_CHECK - bool default y endif @@ -85,68 +71,53 @@ endif if BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF52840DK_NRF52840 config NORDIC_QSPI_NOR - bool default y config NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE - int default 4096 config NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE - int default 16 endif config BOOT_MAX_IMG_SECTORS - int default 256 config LOG - bool default n config CONSOLE_HANDLER - bool default n config BOOT_BANNER - bool default n config TIMESLICING - bool default n config RESET_ON_FATAL_ERROR - bool default n config MULTITHREADING - bool default n config TICKLESS_KERNEL - bool default n config TIMEOUT_64BIT - bool default n config NRF_ENABLE_ICACHE - bool default n if SOC_SERIES_NRF53X # The following configurations are required to support simultaneous multi image update config PCD_APP - bool default y config UPDATEABLE_IMAGE_NUMBER - int default 2 # Multi-image updates do not support image swapping yet. @@ -157,24 +128,19 @@ endchoice # The network core cannot access external flash directly. The flash simulator must be used to # provide a memory region that is used to forward the new firmware to the network core. config FLASH_SIMULATOR - bool default y config FLASH_SIMULATOR_DOUBLE_WRITES - bool default y config FLASH_SIMULATOR_STATS - bool default n # Enable custom command to erase settings partition. config ENABLE_MGMT_PERUSER - bool default y config BOOT_MGMT_CUSTOM_STORAGE_ERASE - bool default y endif # SOC_SERIES_NRF53X diff --git a/config/nrfconnect/chip-module/Kconfig.multiprotocol_rpmsg.defaults b/config/nrfconnect/chip-module/Kconfig.multiprotocol_rpmsg.defaults index 18d3e7889ae1a2..9fee38cb5f38fc 100644 --- a/config/nrfconnect/chip-module/Kconfig.multiprotocol_rpmsg.defaults +++ b/config/nrfconnect/chip-module/Kconfig.multiprotocol_rpmsg.defaults @@ -17,87 +17,66 @@ # The purpose of this file is to define new default values of settings used when building multiprotocol_rpmsg child image for Matter samples. config LOG - bool default n config HEAP_MEM_POOL_SIZE - int default 8192 config MAIN_STACK_SIZE - int default 2048 config SYSTEM_WORKQUEUE_STACK_SIZE - int default 2048 config BT - bool default y config BT_HCI_RAW - bool default y config BT_MAX_CONN - int default 1 config BT_PERIPHERAL - bool default y config BT_CENTRAL - bool default n config BT_BUF_ACL_RX_SIZE - int default 502 config BT_BUF_ACL_TX_SIZE - int default 251 config BT_CTLR_DATA_LENGTH_MAX - int default 251 config BT_CTLR_ASSERT_HANDLER - bool default y config BT_HCI_RAW_RESERVE - int default 1 # Workaround: Unable to allocate command buffer when using K_NO_WAIT since # Host number of completed commands does not follow normal flow control. config BT_BUF_CMD_TX_COUNT - int default 10 config ASSERT - bool default y config DEBUG_INFO - bool default y config EXCEPTION_STACK_TRACE - bool default y config NRF_802154_SER_RADIO - bool default y config NRF_RTC_TIMER_USER_CHAN_COUNT - int default 2 config NRF_802154_ENCRYPTION - bool default y From 99a8de7056b0fa06c161f9fdbea5d2c3cd650f71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Kr=C3=B3lik?= <66667989+Damian-Nordic@users.noreply.github.com> Date: Wed, 4 Jan 2023 17:16:11 +0100 Subject: [PATCH 03/31] [nrfconnect] Disable selected BLE features and RTT (#24227) Disable encryption and EC in BLE controller, and JLink RTT in all nRF Connect examples. BLE changes save over 5.5kB of flash and almost 2kB of RAM. Disabling RTT saves over 1kB of RAM, additionally. Signed-off-by: Damian Krolik Signed-off-by: Damian Krolik --- config/nrfconnect/chip-module/Kconfig.defaults | 12 ++++++++++++ examples/all-clusters-app/nrfconnect/prj.conf | 3 +++ examples/all-clusters-app/nrfconnect/prj_dfu.conf | 3 ++- .../all-clusters-app/nrfconnect/prj_release.conf | 1 + .../all-clusters-minimal-app/nrfconnect/prj.conf | 3 +++ .../all-clusters-minimal-app/nrfconnect/prj_dfu.conf | 3 ++- .../nrfconnect/prj_release.conf | 1 + examples/light-switch-app/nrfconnect/prj.conf | 3 +++ examples/light-switch-app/nrfconnect/prj_no_dfu.conf | 3 +++ .../light-switch-app/nrfconnect/prj_release.conf | 1 + examples/lighting-app/nrfconnect/prj.conf | 3 +++ examples/lighting-app/nrfconnect/prj_no_dfu.conf | 3 +++ examples/lighting-app/nrfconnect/prj_release.conf | 1 + examples/lock-app/nrfconnect/prj.conf | 3 +++ examples/lock-app/nrfconnect/prj_no_dfu.conf | 3 +++ examples/lock-app/nrfconnect/prj_release.conf | 1 + examples/pump-app/nrfconnect/prj.conf | 6 +++--- examples/pump-app/nrfconnect/prj_no_dfu.conf | 3 +++ examples/pump-app/nrfconnect/prj_release.conf | 1 + examples/pump-controller-app/nrfconnect/prj.conf | 3 +++ .../pump-controller-app/nrfconnect/prj_no_dfu.conf | 3 +++ .../pump-controller-app/nrfconnect/prj_release.conf | 1 + examples/window-app/nrfconnect/prj.conf | 3 +++ examples/window-app/nrfconnect/prj_no_dfu.conf | 3 +++ examples/window-app/nrfconnect/prj_release.conf | 1 + 25 files changed, 66 insertions(+), 5 deletions(-) diff --git a/config/nrfconnect/chip-module/Kconfig.defaults b/config/nrfconnect/chip-module/Kconfig.defaults index 67d4b1f23cf88a..88519293b67d77 100644 --- a/config/nrfconnect/chip-module/Kconfig.defaults +++ b/config/nrfconnect/chip-module/Kconfig.defaults @@ -135,6 +135,18 @@ config BT_BUF_ACL_TX_SIZE config BT_RX_STACK_SIZE default 1200 +config BT_CTLR_ECDH + bool + default n + +config BT_CTLR_LE_ENC + bool + default n + +config BT_DEVICE_NAME_GATT_WRITABLE + bool + default n + # Enable NFC support config CHIP_NFC_COMMISSIONING diff --git a/examples/all-clusters-app/nrfconnect/prj.conf b/examples/all-clusters-app/nrfconnect/prj.conf index ee2bee67b64ce4..51d5dd89c68a5f 100644 --- a/examples/all-clusters-app/nrfconnect/prj.conf +++ b/examples/all-clusters-app/nrfconnect/prj.conf @@ -36,6 +36,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable OTA requestor CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/all-clusters-app/nrfconnect/prj_dfu.conf b/examples/all-clusters-app/nrfconnect/prj_dfu.conf index b91bf3fa8298a6..c0d47e635ed406 100644 --- a/examples/all-clusters-app/nrfconnect/prj_dfu.conf +++ b/examples/all-clusters-app/nrfconnect/prj_dfu.conf @@ -35,7 +35,8 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n -# reduce application size by disabling including assertions in the output file. +# Reduce application size +CONFIG_USE_SEGGER_RTT=n CONFIG_ASSERT_VERBOSE=n CONFIG_ASSERT_NO_FILE_INFO=y CONFIG_ASSERT_NO_COND_INFO=y diff --git a/examples/all-clusters-app/nrfconnect/prj_release.conf b/examples/all-clusters-app/nrfconnect/prj_release.conf index 5816426f0fc09e..b229f68b308b9d 100644 --- a/examples/all-clusters-app/nrfconnect/prj_release.conf +++ b/examples/all-clusters-app/nrfconnect/prj_release.conf @@ -35,6 +35,7 @@ CONFIG_BT_DEVICE_NAME="AllClusters" CONFIG_RESET_ON_FATAL_ERROR=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/all-clusters-minimal-app/nrfconnect/prj.conf b/examples/all-clusters-minimal-app/nrfconnect/prj.conf index 2c2c8d2fc81c28..c33baaa8d79761 100644 --- a/examples/all-clusters-minimal-app/nrfconnect/prj.conf +++ b/examples/all-clusters-minimal-app/nrfconnect/prj.conf @@ -36,6 +36,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable OTA requestor CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/all-clusters-minimal-app/nrfconnect/prj_dfu.conf b/examples/all-clusters-minimal-app/nrfconnect/prj_dfu.conf index 292d7a086d4e89..6effabf6914a9b 100644 --- a/examples/all-clusters-minimal-app/nrfconnect/prj_dfu.conf +++ b/examples/all-clusters-minimal-app/nrfconnect/prj_dfu.conf @@ -36,7 +36,8 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n -# reduce application size by disabling including assertions in the output file. +# Reduce application size +CONFIG_USE_SEGGER_RTT=n CONFIG_ASSERT_VERBOSE=n CONFIG_ASSERT_NO_FILE_INFO=y CONFIG_ASSERT_NO_COND_INFO=y diff --git a/examples/all-clusters-minimal-app/nrfconnect/prj_release.conf b/examples/all-clusters-minimal-app/nrfconnect/prj_release.conf index 33cd3f38589653..8029f55a1e31f4 100644 --- a/examples/all-clusters-minimal-app/nrfconnect/prj_release.conf +++ b/examples/all-clusters-minimal-app/nrfconnect/prj_release.conf @@ -35,6 +35,7 @@ CONFIG_BT_DEVICE_NAME="AllClusters" CONFIG_RESET_ON_FATAL_ERROR=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/light-switch-app/nrfconnect/prj.conf b/examples/light-switch-app/nrfconnect/prj.conf index 19f3cb266a6abc..23fa257975fe64 100644 --- a/examples/light-switch-app/nrfconnect/prj.conf +++ b/examples/light-switch-app/nrfconnect/prj.conf @@ -38,3 +38,6 @@ CONFIG_BT_DEVICE_NAME="MatterSwitch" CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/light-switch-app/nrfconnect/prj_no_dfu.conf b/examples/light-switch-app/nrfconnect/prj_no_dfu.conf index 27475ce596444c..145cb9b50f835e 100644 --- a/examples/light-switch-app/nrfconnect/prj_no_dfu.conf +++ b/examples/light-switch-app/nrfconnect/prj_no_dfu.conf @@ -39,6 +39,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/light-switch-app/nrfconnect/prj_release.conf b/examples/light-switch-app/nrfconnect/prj_release.conf index a55449c991b17c..520a280b1e18ab 100644 --- a/examples/light-switch-app/nrfconnect/prj_release.conf +++ b/examples/light-switch-app/nrfconnect/prj_release.conf @@ -41,6 +41,7 @@ CONFIG_RESET_ON_FATAL_ERROR=y CONFIG_PM_DEVICE=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/lighting-app/nrfconnect/prj.conf b/examples/lighting-app/nrfconnect/prj.conf index 1a796988571cf5..ad67f13edf08e3 100644 --- a/examples/lighting-app/nrfconnect/prj.conf +++ b/examples/lighting-app/nrfconnect/prj.conf @@ -46,3 +46,6 @@ CONFIG_IEEE802154_NRF5_RX_STACK_SIZE=1024 CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/lighting-app/nrfconnect/prj_no_dfu.conf b/examples/lighting-app/nrfconnect/prj_no_dfu.conf index 7fc72e8fcbd704..a2d0392c98b5a9 100644 --- a/examples/lighting-app/nrfconnect/prj_no_dfu.conf +++ b/examples/lighting-app/nrfconnect/prj_no_dfu.conf @@ -43,6 +43,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Stack size settings CONFIG_IEEE802154_NRF5_RX_STACK_SIZE=1024 diff --git a/examples/lighting-app/nrfconnect/prj_release.conf b/examples/lighting-app/nrfconnect/prj_release.conf index 5ff25156b6861b..762b6d44f919c7 100644 --- a/examples/lighting-app/nrfconnect/prj_release.conf +++ b/examples/lighting-app/nrfconnect/prj_release.conf @@ -45,6 +45,7 @@ CONFIG_RESET_ON_FATAL_ERROR=y CONFIG_IEEE802154_NRF5_RX_STACK_SIZE=1024 # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/lock-app/nrfconnect/prj.conf b/examples/lock-app/nrfconnect/prj.conf index 676ae5a05f2599..6b4864a2a486b7 100644 --- a/examples/lock-app/nrfconnect/prj.conf +++ b/examples/lock-app/nrfconnect/prj.conf @@ -35,3 +35,6 @@ CONFIG_BT_DEVICE_NAME="MatterLock" CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/lock-app/nrfconnect/prj_no_dfu.conf b/examples/lock-app/nrfconnect/prj_no_dfu.conf index 839f839fc2e74f..a53431aa2dd9d7 100644 --- a/examples/lock-app/nrfconnect/prj_no_dfu.conf +++ b/examples/lock-app/nrfconnect/prj_no_dfu.conf @@ -36,6 +36,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/lock-app/nrfconnect/prj_release.conf b/examples/lock-app/nrfconnect/prj_release.conf index b41ed9ede98909..ba830806523ded 100644 --- a/examples/lock-app/nrfconnect/prj_release.conf +++ b/examples/lock-app/nrfconnect/prj_release.conf @@ -38,6 +38,7 @@ CONFIG_RESET_ON_FATAL_ERROR=y CONFIG_PM_DEVICE=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/pump-app/nrfconnect/prj.conf b/examples/pump-app/nrfconnect/prj.conf index 3195f884e65720..3013e7d7aec421 100644 --- a/examples/pump-app/nrfconnect/prj.conf +++ b/examples/pump-app/nrfconnect/prj.conf @@ -14,9 +14,6 @@ # limitations under the License. # -CONFIG_CHIP=y -CONFIG_STD_CPP14=y - # This sample uses Kconfig.defaults to set options common for all # samples. This file should contain only options specific for this sample # or overrides of default values. @@ -38,3 +35,6 @@ CONFIG_BT_DEVICE_NAME="MatterPump" CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/pump-app/nrfconnect/prj_no_dfu.conf b/examples/pump-app/nrfconnect/prj_no_dfu.conf index 67c31871ce797f..a0d3f8b1a879c2 100644 --- a/examples/pump-app/nrfconnect/prj_no_dfu.conf +++ b/examples/pump-app/nrfconnect/prj_no_dfu.conf @@ -36,6 +36,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/pump-app/nrfconnect/prj_release.conf b/examples/pump-app/nrfconnect/prj_release.conf index adb09f72ef3db2..540c77354fa82f 100644 --- a/examples/pump-app/nrfconnect/prj_release.conf +++ b/examples/pump-app/nrfconnect/prj_release.conf @@ -38,6 +38,7 @@ CONFIG_RESET_ON_FATAL_ERROR=y CONFIG_PM_DEVICE=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/pump-controller-app/nrfconnect/prj.conf b/examples/pump-controller-app/nrfconnect/prj.conf index 4a38ec1177c699..5b9c2baff8ee9e 100644 --- a/examples/pump-controller-app/nrfconnect/prj.conf +++ b/examples/pump-controller-app/nrfconnect/prj.conf @@ -35,3 +35,6 @@ CONFIG_BT_DEVICE_NAME="MatterPumpCtrl" CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/pump-controller-app/nrfconnect/prj_no_dfu.conf b/examples/pump-controller-app/nrfconnect/prj_no_dfu.conf index dba7042ad82864..d6632fe9172638 100644 --- a/examples/pump-controller-app/nrfconnect/prj_no_dfu.conf +++ b/examples/pump-controller-app/nrfconnect/prj_no_dfu.conf @@ -37,6 +37,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/pump-controller-app/nrfconnect/prj_release.conf b/examples/pump-controller-app/nrfconnect/prj_release.conf index 88ea95c777e1a1..fc3b092b655c8f 100644 --- a/examples/pump-controller-app/nrfconnect/prj_release.conf +++ b/examples/pump-controller-app/nrfconnect/prj_release.conf @@ -39,6 +39,7 @@ CONFIG_RESET_ON_FATAL_ERROR=y CONFIG_PM_DEVICE=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n diff --git a/examples/window-app/nrfconnect/prj.conf b/examples/window-app/nrfconnect/prj.conf index a284009a305d99..3dc711bce86098 100644 --- a/examples/window-app/nrfconnect/prj.conf +++ b/examples/window-app/nrfconnect/prj.conf @@ -46,3 +46,6 @@ CONFIG_IEEE802154_NRF5_RX_STACK_SIZE=1024 CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n + +# Reduce application size +CONFIG_USE_SEGGER_RTT=n diff --git a/examples/window-app/nrfconnect/prj_no_dfu.conf b/examples/window-app/nrfconnect/prj_no_dfu.conf index 3f55608bc1357e..d2da9b1a184eaa 100644 --- a/examples/window-app/nrfconnect/prj_no_dfu.conf +++ b/examples/window-app/nrfconnect/prj_no_dfu.conf @@ -52,6 +52,9 @@ CONFIG_THREAD_NAME=y CONFIG_MPU_STACK_GUARD=y CONFIG_RESET_ON_FATAL_ERROR=n +# Reduce application size +CONFIG_USE_SEGGER_RTT=n + # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n diff --git a/examples/window-app/nrfconnect/prj_release.conf b/examples/window-app/nrfconnect/prj_release.conf index c801e2f86bb9a7..336eb9ea95169f 100644 --- a/examples/window-app/nrfconnect/prj_release.conf +++ b/examples/window-app/nrfconnect/prj_release.conf @@ -54,6 +54,7 @@ CONFIG_IEEE802154_NRF5_RX_STACK_SIZE=1024 CONFIG_PM_DEVICE=y # Disable all debug features +CONFIG_USE_SEGGER_RTT=n CONFIG_SHELL=n CONFIG_OPENTHREAD_SHELL=n CONFIG_CONSOLE=n From cc94655a072e68644cd897435af73362eadad7d1 Mon Sep 17 00:00:00 2001 From: mkardous-silabs <84793247+mkardous-silabs@users.noreply.github.com> Date: Wed, 4 Jan 2023 11:35:11 -0500 Subject: [PATCH 04/31] [IC-Device] Initial implementation of Client Monitoring Registration table (#24096) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Client Monitoring table implementation * CM table tests * Add sub-struct to add a validation function Add unit test for invalid values * Address PR comments * Apply suggestions from code review Co-authored-by: Boris Zbarsky * Increase max unit test limit * Apply suggestions from code review Co-authored-by: Damian Królik <66667989+Damian-Nordic@users.noreply.github.com> * Move comments to headeR * update test assert * Add provisional comment * restyle Co-authored-by: Boris Zbarsky Co-authored-by: Damian Królik <66667989+Damian-Nordic@users.noreply.github.com> --- src/app/tests/BUILD.gn | 14 ++ .../TestClientMonitoringRegistrationTable.cpp | 141 ++++++++++++++++++ .../ClientMonitoringRegistrationTable.cpp | 62 ++++---- .../util/ClientMonitoringRegistrationTable.h | 55 +++++-- src/lib/core/DataModelTypes.h | 4 + src/lib/support/DefaultStorageKeyAllocator.h | 7 + src/lib/support/UnitTestRegistration.cpp | 2 +- 7 files changed, 237 insertions(+), 48 deletions(-) create mode 100644 src/app/tests/TestClientMonitoringRegistrationTable.cpp diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index d11f29a66c72c2..6afc8f8e2615fc 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -54,6 +54,18 @@ source_set("binding-test-srcs") { ] } +source_set("client-monitoring-test-srcs") { + sources = [ + "${chip_root}/src/app/util/ClientMonitoringRegistrationTable.cpp", + "${chip_root}/src/app/util/ClientMonitoringRegistrationTable.h", + ] + + public_deps = [ + "${chip_root}/src/app/common:cluster-objects", + "${chip_root}/src/lib/core", + ] +} + source_set("ota-requestor-test-srcs") { sources = [ "${chip_root}/src/app/clusters/ota-requestor/DefaultOTARequestorStorage.cpp", @@ -77,6 +89,7 @@ chip_test_suite("tests") { "TestAttributeValueEncoder.cpp", "TestBindingTable.cpp", "TestBuilderParser.cpp", + "TestClientMonitoringRegistrationTable.cpp", "TestClusterInfo.cpp", "TestCommandInteraction.cpp", "TestCommandPathParams.cpp", @@ -117,6 +130,7 @@ chip_test_suite("tests") { public_deps = [ ":binding-test-srcs", + ":client-monitoring-test-srcs", ":ota-requestor-test-srcs", "${chip_root}/src/app", "${chip_root}/src/app/common:cluster-objects", diff --git a/src/app/tests/TestClientMonitoringRegistrationTable.cpp b/src/app/tests/TestClientMonitoringRegistrationTable.cpp new file mode 100644 index 00000000000000..a05d9e6d490615 --- /dev/null +++ b/src/app/tests/TestClientMonitoringRegistrationTable.cpp @@ -0,0 +1,141 @@ +/* + * + * 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 +#include +#include + +using chip::ClientMonitoringRegistrationTable; +using chip::NullOptional; + +namespace { + +constexpr chip::FabricIndex kTestFabricIndex = 1; +constexpr uint64_t kTestICid = 10; +constexpr chip::NodeId kTestClientNodeId = 11; + +constexpr chip::FabricIndex kTestFabricIndex_2 = 2; +constexpr uint64_t kTestICid_2 = 20; +constexpr chip::NodeId kTestClientNodeId_2 = 21; + +void TestDefaultClientValues(nlTestSuite * aSuite, void * aContext) +{ + chip::TestPersistentStorageDelegate testStorage; + ClientMonitoringRegistrationTable registration(testStorage); + + NL_TEST_ASSERT(aSuite, !registration.GetClientRegistrationEntry().IsValid()); + NL_TEST_ASSERT(aSuite, registration.GetClientRegistrationEntry().clientNodeId == chip::kUndefinedFabricIndex); + NL_TEST_ASSERT(aSuite, registration.GetClientRegistrationEntry().ICid == chip::kUndefinedNodeId); + NL_TEST_ASSERT(aSuite, registration.GetClientRegistrationEntry().fabricIndex == chip::kInvalidIcId); +} + +void TestLoadFromStorageEmptyValue(nlTestSuite * aSuite, void * aContext) +{ + chip::TestPersistentStorageDelegate testStorage; + ClientMonitoringRegistrationTable registration(testStorage); + + CHIP_ERROR err = registration.LoadFromStorage(kTestFabricIndex); + NL_TEST_ASSERT(aSuite, err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); +} + +void TestSaveAndLoadRegistrationValue(nlTestSuite * aSuite, void * aContext) +{ + chip::TestPersistentStorageDelegate testStorage; + ClientMonitoringRegistrationTable savedRegistration(testStorage); + ClientMonitoringRegistrationTable loadedRegistration(testStorage); + + savedRegistration.GetClientRegistrationEntry().clientNodeId = kTestClientNodeId; + savedRegistration.GetClientRegistrationEntry().ICid = kTestICid; + savedRegistration.GetClientRegistrationEntry().fabricIndex = kTestFabricIndex; + + CHIP_ERROR err = savedRegistration.SaveToStorage(); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + err = loadedRegistration.LoadFromStorage(kTestFabricIndex); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().clientNodeId == kTestClientNodeId); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().ICid == kTestICid); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().fabricIndex == kTestFabricIndex); +} + +void TestSaveLoadRegistrationValueForMultipleFabrics(nlTestSuite * aSuite, void * aContexT) +{ + chip::TestPersistentStorageDelegate testStorage; + ClientMonitoringRegistrationTable savedRegistration(testStorage); + ClientMonitoringRegistrationTable loadedRegistration(testStorage); + + savedRegistration.GetClientRegistrationEntry().clientNodeId = kTestClientNodeId; + savedRegistration.GetClientRegistrationEntry().ICid = kTestICid; + savedRegistration.GetClientRegistrationEntry().fabricIndex = kTestFabricIndex; + + CHIP_ERROR err = savedRegistration.SaveToStorage(); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + savedRegistration.GetClientRegistrationEntry().clientNodeId = kTestClientNodeId_2; + savedRegistration.GetClientRegistrationEntry().ICid = kTestICid_2; + savedRegistration.GetClientRegistrationEntry().fabricIndex = kTestFabricIndex_2; + + err = savedRegistration.SaveToStorage(); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + err = loadedRegistration.LoadFromStorage(kTestFabricIndex); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().clientNodeId == kTestClientNodeId); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().ICid == kTestICid); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().fabricIndex == kTestFabricIndex); + + err = loadedRegistration.LoadFromStorage(kTestFabricIndex_2); + NL_TEST_ASSERT(aSuite, err == CHIP_NO_ERROR); + + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().clientNodeId == kTestClientNodeId_2); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().ICid == kTestICid_2); + NL_TEST_ASSERT(aSuite, loadedRegistration.GetClientRegistrationEntry().fabricIndex == kTestFabricIndex_2); +} + +void TestSaveAllInvalidRegistrationValues(nlTestSuite * aSuite, void * context) +{ + chip::TestPersistentStorageDelegate testStorage; + ClientMonitoringRegistrationTable registration(testStorage); + + CHIP_ERROR err = registration.SaveToStorage(); + NL_TEST_ASSERT(aSuite, err == CHIP_ERROR_INCORRECT_STATE); +} + +} // namespace + +int TestClientMonitoringRegistrationTable() +{ + static nlTest sTests[] = { NL_TEST_DEF("TestDefaultClientValues", TestDefaultClientValues), + NL_TEST_DEF("TestLoadFromStorageEmptyValue", TestLoadFromStorageEmptyValue), + NL_TEST_DEF("TestSaveAndLoadRegistrationValue", TestSaveAndLoadRegistrationValue), + NL_TEST_DEF("TestSaveAllInvalidRegistrationValues", TestSaveAllInvalidRegistrationValues), + NL_TEST_DEF("TestSaveLoadRegistrationValueForMultipleFabrics", + TestSaveLoadRegistrationValueForMultipleFabrics), + NL_TEST_SENTINEL() }; + + nlTestSuite cmSuite = { "TestClientMonitoringRegistrationTable", &sTests[0], nullptr, nullptr }; + + nlTestRunner(&cmSuite, nullptr); + return (nlTestRunnerStats(&cmSuite)); +} + +CHIP_REGISTER_TEST_SUITE(TestClientMonitoringRegistrationTable) diff --git a/src/app/util/ClientMonitoringRegistrationTable.cpp b/src/app/util/ClientMonitoringRegistrationTable.cpp index efdccf01467d1e..59ff417aefb363 100644 --- a/src/app/util/ClientMonitoringRegistrationTable.cpp +++ b/src/app/util/ClientMonitoringRegistrationTable.cpp @@ -17,59 +17,53 @@ #include "ClientMonitoringRegistrationTable.h" -namespace chip { +#include -/********************************************************** - * Attributes Definition - *********************************************************/ +namespace chip { /********************************************************** * ClientMonitoringRegistrationTable Implementation *********************************************************/ -ClientMonitoringRegistrationTable::ClientMonitoringRegistrationTable(FabricIndex fabricIndex) -{ - this->LoadFromStorage(fabricIndex); -} +ClientMonitoringRegistrationTable::ClientMonitoringRegistrationTable(PersistentStorageDelegate & storage) : mStorage(storage) {} -void ClientMonitoringRegistrationTable::LoadFromStorage(FabricIndex fabricIndex) +CHIP_ERROR ClientMonitoringRegistrationTable::LoadFromStorage(FabricIndex fabricIndex) { - // TODO: Implement load from NVM logic -} + uint8_t buffer[kRegStorageSize] = { 0 }; + uint16_t size = sizeof(buffer); -void ClientMonitoringRegistrationTable::SaveToStorage() -{ - // Store to NVM based of class attributes -} + ReturnErrorOnFailure( + mStorage.SyncGetKeyValue(DefaultStorageKeyAllocator::ClientMonitoringTableEntry(fabricIndex).KeyName(), buffer, size)); -NodeId ClientMonitoringRegistrationTable::getClientNodeId() -{ - return mRegisteredClient.clientNodeId; -} + TLV::TLVReader reader; + reader.Init(buffer, size); + ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag())); -uint64_t ClientMonitoringRegistrationTable::getICid() -{ - return mRegisteredClient.ICid; -} + ReturnErrorOnFailure(mRegisteredClient.Decode(reader)); -FabricIndex ClientMonitoringRegistrationTable::getFaricIndex() -{ - return mRegisteredClient.fabricIndex; -} + mRegisteredClient.fabricIndex = fabricIndex; -void ClientMonitoringRegistrationTable::setClientNodeId(NodeId clientNodeId) -{ - mRegisteredClient.clientNodeId = clientNodeId; + return CHIP_NO_ERROR; } -void ClientMonitoringRegistrationTable::setICid(uint64_t ICid) +CHIP_ERROR ClientMonitoringRegistrationTable::SaveToStorage() { - mRegisteredClient.ICid = ICid; + VerifyOrReturnError(mRegisteredClient.IsValid(), CHIP_ERROR_INCORRECT_STATE); + + uint8_t buffer[kRegStorageSize] = { 0 }; + TLV::TLVWriter writer; + + writer.Init(buffer); + ReturnErrorOnFailure(mRegisteredClient.EncodeForWrite(writer, TLV::AnonymousTag())); + ReturnErrorOnFailure(writer.Finalize()); + + return mStorage.SyncSetKeyValue(DefaultStorageKeyAllocator::ClientMonitoringTableEntry(mRegisteredClient.fabricIndex).KeyName(), + buffer, static_cast(writer.GetLengthWritten())); } -void ClientMonitoringRegistrationTable::setFabricIndex(FabricIndex fabric) +ClientMonitoringRegistrationTable::ClientRegistrationEntry & ClientMonitoringRegistrationTable::GetClientRegistrationEntry() { - mRegisteredClient.fabricIndex = fabric; + return mRegisteredClient; } } // namespace chip diff --git a/src/app/util/ClientMonitoringRegistrationTable.h b/src/app/util/ClientMonitoringRegistrationTable.h index a495f96ba0bc58..7579cdc016cee8 100644 --- a/src/app/util/ClientMonitoringRegistrationTable.h +++ b/src/app/util/ClientMonitoringRegistrationTable.h @@ -19,33 +19,62 @@ #include #include +#include +#include #include -#include namespace chip { + +/** + * @brief ClientMonitoringRegistrationTable exists to manage the persistence of entries in the ClientMonitoring Cluster. + * To access persisted data with the ClientMonitoringRegistrationTable class, instantiate an instance of this class + * and call the LoadFromStorage function. + * + * This class can only manage one fabric at a time. The flow is load a fabric, execute necessary operations, + * save it if there are any changes and load another fabric. + */ class ClientMonitoringRegistrationTable { public: using MonitoringRegistrationStruct = chip::app::Clusters::ClientMonitoring::Structs::MonitoringRegistration::Type; - ClientMonitoringRegistrationTable(FabricIndex fabricIndex); + struct ClientRegistrationEntry : MonitoringRegistrationStruct + { + bool IsValid() { return clientNodeId != kUndefinedNodeId && ICid != kInvalidIcId && fabricIndex != kUndefinedFabricIndex; } + }; + + ClientMonitoringRegistrationTable(PersistentStorageDelegate & storage); ~ClientMonitoringRegistrationTable(){}; - void SaveToStorage(); + /** + * @brief Function saves the mRegisteredClient attribute to persitant storage + * To correctly persit an entry, the values must be stored in the structures attributes + * + * @return CHIP_ERROR + */ + CHIP_ERROR SaveToStorage(); - // Getter - NodeId getClientNodeId(); - uint64_t getICid(); - FabricIndex getFaricIndex(); + /** + * @brief Function loads a client registration entry from persistent storage for a single fabric + * + * @param[in] fabricIndex fabric index to load from storage + * @return CHIP_ERROR + */ + CHIP_ERROR LoadFromStorage(FabricIndex fabricIndex); - // Setter - void setClientNodeId(NodeId clientNodeId); - void setICid(uint64_t ICid); - void setFabricIndex(FabricIndex fabric); + /** + * @brief Accessor function that returns the client registration entry that was loaded for a fabric from persistant storage. + * @see LoadFromStorage + * + * @return ClientMonitoringRegistrationTable::ClientRegistrationEntry& + */ + ClientRegistrationEntry & GetClientRegistrationEntry(); private: - void LoadFromStorage(FabricIndex fabricIndex); - MonitoringRegistrationStruct mRegisteredClient; + static constexpr uint8_t kRegStorageSize = TLV::EstimateStructOverhead(sizeof(NodeId), sizeof(uint64_t)); + + ClientRegistrationEntry mRegisteredClient; + PersistentStorageDelegate & mStorage; }; } // namespace chip diff --git a/src/lib/core/DataModelTypes.h b/src/lib/core/DataModelTypes.h index 4c955f3948a7d2..a25eb3e53ebd3b 100644 --- a/src/lib/core/DataModelTypes.h +++ b/src/lib/core/DataModelTypes.h @@ -58,6 +58,10 @@ constexpr EndpointId kRootEndpointId = 0; constexpr ListIndex kInvalidListIndex = 0xFFFF; // List index is a uint16 thus 0xFFFF is a invalid list index. constexpr KeysetId kInvalidKeysetId = 0xFFFF; +// Invalid IC identifier is provisional. Value will most likely change when identifying token is defined +// https://github.com/project-chip/connectedhomeip/issues/24251 +constexpr uint64_t kInvalidIcId = 0; + // These are MEIs, 0xFFFF is not a valid manufacturer code, // thus 0xFFFF'FFFF is not a valid MEI. static constexpr ClusterId kInvalidClusterId = 0xFFFF'FFFF; diff --git a/src/lib/support/DefaultStorageKeyAllocator.h b/src/lib/support/DefaultStorageKeyAllocator.h index 6a4b906c2426b8..d74a0e75bcbba5 100644 --- a/src/lib/support/DefaultStorageKeyAllocator.h +++ b/src/lib/support/DefaultStorageKeyAllocator.h @@ -175,6 +175,13 @@ class DefaultStorageKeyAllocator static StorageKeyName BindingTable() { return StorageKeyName::FromConst("g/bt"); } static StorageKeyName BindingTableEntry(uint8_t index) { return StorageKeyName::Formatted("g/bt/%x", index); } + // Client Monitoring + + static StorageKeyName ClientMonitoringTableEntry(chip::FabricIndex fabric) + { + return StorageKeyName::Formatted("f/%x/cm", fabric); + } + static StorageKeyName OTADefaultProviders() { return StorageKeyName::FromConst("g/o/dp"); } static StorageKeyName OTACurrentProvider() { return StorageKeyName::FromConst("g/o/cp"); } static StorageKeyName OTAUpdateToken() { return StorageKeyName::FromConst("g/o/ut"); } diff --git a/src/lib/support/UnitTestRegistration.cpp b/src/lib/support/UnitTestRegistration.cpp index a94fcb6f392e50..e706bbc891d6a5 100644 --- a/src/lib/support/UnitTestRegistration.cpp +++ b/src/lib/support/UnitTestRegistration.cpp @@ -22,7 +22,7 @@ namespace chip { -const size_t kTestSuitesMax = 128; +const size_t kTestSuitesMax = 256; typedef struct { From 757d67cade098f8278dd8f152c0f1e4b707cbff0 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Wed, 4 Jan 2023 17:36:46 +0100 Subject: [PATCH 05/31] Fix mutex use after destroy upon stack shutdown (#24191) * Fix mutex use after destroy upon stack shutdown Shutting down CHIP stack when the event loop is still running might lead to use after free for objects used in CHIP main event loop. This commit fixes this by not running pychip_DeviceController_StackShutdown() on the CHIP thread, but in the main thread of Python application. * Account for externally managed threads which are joined outside of the POSIX platform manager implementation class. * java: Stop IO thread before shutting down commissioner --- .../java/CHIPDeviceController-JNI.cpp | 34 +++++++++--- src/controller/python/chip/ChipStack.py | 5 +- .../GenericPlatformManagerImpl_POSIX.h | 19 +++---- .../GenericPlatformManagerImpl_POSIX.ipp | 52 ++++++++++++------- 4 files changed, 69 insertions(+), 41 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index bed3ffda5f0c42..85c88c48eacf38 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -74,6 +74,7 @@ using namespace chip::Credentials; #define CDC_JNI_CALLBACK_LOCAL_REF_COUNT 256 static void * IOThreadMain(void * arg); +static CHIP_ERROR StopIOThread(); static CHIP_ERROR N2J_PaseVerifierParams(JNIEnv * env, jlong setupPincode, jbyteArray pakeVerifier, jobject & outParams); static CHIP_ERROR N2J_NetworkLocation(JNIEnv * env, jstring ipAddress, jint port, jint interfaceIndex, jobject & outLocation); static CHIP_ERROR GetChipPathIdValue(jobject chipPathId, uint32_t wildcardValue, uint32_t & outValue); @@ -147,14 +148,10 @@ void JNI_OnUnload(JavaVM * jvm, void * reserved) chip::DeviceLayer::StackLock lock; ChipLogProgress(Controller, "JNI_OnUnload() called"); - // If the IO thread has been started, shut it down and wait for it to exit. - if (sIOThread != PTHREAD_NULL) - { - chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); - - chip::DeviceLayer::StackUnlock unlock; - pthread_join(sIOThread, NULL); - } + // If the IO thread has not been stopped yet, shut it down now. + // TODO(arkq): Maybe we should just assert here, as the IO thread + // should be stopped before the library is unloaded. + StopIOThread(); sJVM = NULL; @@ -1020,6 +1017,10 @@ JNI_METHOD(void, shutdownCommissioning) (JNIEnv * env, jobject self, jlong handle) { chip::DeviceLayer::StackLock lock; + + // Stop the IO thread, so that the controller can be safely shut down. + StopIOThread(); + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); wrapper->Controller()->Shutdown(); } @@ -1410,6 +1411,23 @@ void * IOThreadMain(void * arg) return NULL; } +// NOTE: This function SHALL be called with the stack lock held. +CHIP_ERROR StopIOThread() +{ + if (sIOThread != PTHREAD_NULL) + { + ChipLogProgress(Controller, "IO thread stopping"); + chip::DeviceLayer::StackUnlock unlock; + + chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); + + pthread_join(sIOThread, NULL); + sIOThread = PTHREAD_NULL; + } + + return CHIP_NO_ERROR; +} + CHIP_ERROR N2J_PaseVerifierParams(JNIEnv * env, jlong setupPincode, jbyteArray paseVerifier, jobject & outParams) { CHIP_ERROR err = CHIP_NO_ERROR; diff --git a/src/controller/python/chip/ChipStack.py b/src/controller/python/chip/ChipStack.py index 3ca313be08214d..fabf43e4110c5e 100644 --- a/src/controller/python/chip/ChipStack.py +++ b/src/controller/python/chip/ChipStack.py @@ -328,7 +328,10 @@ def setLogFunct(self, logFunct): self._ChipStackLib.pychip_Stack_SetLogFunct(logFunct) def Shutdown(self): - self.Call(lambda: self._ChipStackLib.pychip_DeviceController_StackShutdown()).raise_on_error() + # + # Terminate Matter thread and shutdown the stack. + # + self._ChipStackLib.pychip_DeviceController_StackShutdown() # # We only shutdown the persistent storage layer AFTER we've shut down the stack, diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.h b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.h index 7fd248fdf699d9..acdd2a4d3b762c 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.h +++ b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.h @@ -55,24 +55,19 @@ class GenericPlatformManagerImpl_POSIX : public GenericPlatformManagerImpl mState{ State::kStopped }; pthread_cond_t mEventQueueStoppedCond; pthread_mutex_t mStateLock; - // - // TODO: This variable is very similar to mMainLoopIsStarted, track the - // cleanup and consolidation in this issue: - // - bool mEventQueueHasStopped = false; - pthread_attr_t mChipTaskAttr; struct sched_param mChipTaskSchedParam; @@ -109,7 +104,7 @@ class GenericPlatformManagerImpl_POSIX : public GenericPlatformManagerImpl mShouldRunEventLoop; + std::atomic mShouldRunEventLoop{ true }; static void * EventLoopTaskMain(void * arg); }; diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp index 4a52152d91d64f..6050950bf4c261 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl_POSIX.ipp @@ -59,16 +59,12 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_InitChipStack() // Call up to the base class _InitChipStack() to perform the bulk of the initialization. ReturnErrorOnFailure(GenericPlatformManagerImpl::_InitChipStack()); - mShouldRunEventLoop.store(true, std::memory_order_relaxed); - int ret = pthread_cond_init(&mEventQueueStoppedCond, nullptr); VerifyOrReturnError(ret == 0, CHIP_ERROR_POSIX(ret)); ret = pthread_mutex_init(&mStateLock, nullptr); VerifyOrReturnError(ret == 0, CHIP_ERROR_POSIX(ret)); - mHasValidChipTask = false; - return CHIP_NO_ERROR; } @@ -117,7 +113,11 @@ void GenericPlatformManagerImpl_POSIX::_UnlockChipStack() template bool GenericPlatformManagerImpl_POSIX::_IsChipStackLockedByCurrentThread() const { - return !mHasValidChipTask || (mChipStackIsLocked && (pthread_equal(pthread_self(), mChipStackLockOwnerThread))); + // If no Matter thread is currently running we do not have to worry about + // locking. Hence, this function always returns true in that case. + if (mState.load(std::memory_order_relaxed) == State::kStopped) + return true; + return mChipStackIsLocked && (pthread_equal(pthread_self(), mChipStackLockOwnerThread)); } #endif @@ -153,18 +153,16 @@ void GenericPlatformManagerImpl_POSIX::_RunEventLoop() pthread_mutex_lock(&mStateLock); // - // If we haven't set mHasValidChipTask by now, it means that the application did not call StartEventLoopTask - // and consequently, are running the event loop from their own, externally managed task. - // Let's track his appropriately since we need this info later when stopping the event queues. + // If we haven't set mInternallyManagedChipTask by now, it means that the application did not call + // StartEventLoopTask and consequently, are running the event loop from their own, externally managed + // task. // - if (!mHasValidChipTask) + if (!mInternallyManagedChipTask) { - mHasValidChipTask = true; - mChipTask = pthread_self(); - mTaskType = kExternallyManagedTask; + mChipTask = pthread_self(); + mState.store(State::kRunning, std::memory_order_relaxed); } - mEventQueueHasStopped = false; pthread_mutex_unlock(&mStateLock); Impl()->LockChipStack(); @@ -187,7 +185,7 @@ void GenericPlatformManagerImpl_POSIX::_RunEventLoop() Impl()->UnlockChipStack(); pthread_mutex_lock(&mStateLock); - mEventQueueHasStopped = true; + mState.store(State::kStopping, std::memory_order_relaxed); pthread_mutex_unlock(&mStateLock); // @@ -195,6 +193,13 @@ void GenericPlatformManagerImpl_POSIX::_RunEventLoop() // StopEventLoopTask(). // pthread_cond_signal(&mEventQueueStoppedCond); + + // + // Mark event loop as truly stopped. After that line, we can not use any + // non-simple type member variables, because they can be destroyed by the + // Shutdown() method. + // + mState.store(State::kStopped, std::memory_order_relaxed); } template @@ -230,8 +235,8 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_StartEventLoopTask() err = pthread_create(&mChipTask, &mChipTaskAttr, EventLoopTaskMain, this); if (err == 0) { - mHasValidChipTask = true; - mTaskType = kInternallyManagedTask; + mInternallyManagedChipTask = true; + mState.store(State::kRunning, std::memory_order_relaxed); } pthread_mutex_unlock(&mStateLock); @@ -255,7 +260,8 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_StopEventLoopTask() // If we're calling this from a different thread than the one running chip, then // we need to wait till the event queue has completely stopped before proceeding. // - if (mHasValidChipTask && (pthread_equal(pthread_self(), mChipTask) == 0)) + auto isRunning = mState.load(std::memory_order_relaxed) == State::kRunning; + if (isRunning && (pthread_equal(pthread_self(), mChipTask) == 0)) { pthread_mutex_unlock(&mStateLock); @@ -269,7 +275,7 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_StopEventLoopTask() pthread_mutex_lock(&mStateLock); - while (!mEventQueueHasStopped) + while (mState.load(std::memory_order_relaxed) == State::kRunning) { err = pthread_cond_wait(&mEventQueueStoppedCond, &mStateLock); VerifyOrExit(err == 0, ); @@ -280,7 +286,7 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_StopEventLoopTask() // // Wait further for the thread to terminate if we had previously created it. // - if (mTaskType == kInternallyManagedTask) + if (mInternallyManagedChipTask) { err = pthread_join(mChipTask, nullptr); VerifyOrExit(err == 0, ); @@ -292,13 +298,19 @@ CHIP_ERROR GenericPlatformManagerImpl_POSIX::_StopEventLoopTask() } exit: - mHasValidChipTask = false; return CHIP_ERROR_POSIX(err); } template void GenericPlatformManagerImpl_POSIX::_Shutdown() { + // + // We cannot shutdown the stack while the event loop is still running. This can lead + // to use after free errors - here we are destroying mutex and condition variable that + // are still in use by the event loop! + // + VerifyOrDie(mState.load(std::memory_order_relaxed) == State::kStopped); + pthread_mutex_destroy(&mStateLock); pthread_cond_destroy(&mEventQueueStoppedCond); From 0f3039ffbbbc808af65c714c9e8f020eb6f64097 Mon Sep 17 00:00:00 2001 From: Hrishikesh Dhayagude Date: Wed, 4 Jan 2023 22:10:41 +0530 Subject: [PATCH 06/31] ESP32: Fix the initial call to esp_wifi_set_config() (#24168) --- src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp b/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp index 2eb2e1b3ad11e0..c068bba75cb492 100644 --- a/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp +++ b/src/platform/ESP32/ConnectivityManagerImpl_WiFi.cpp @@ -104,11 +104,6 @@ void ConnectivityManagerImpl::_ClearWiFiStationProvision(void) { if (mWiFiStationMode != kWiFiStationMode_ApplicationControlled) { - wifi_config_t stationConfig; - - memset(&stationConfig, 0, sizeof(stationConfig)); - esp_wifi_set_config(WIFI_IF_STA, &stationConfig); - DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL); #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP DeviceLayer::SystemLayer().ScheduleWork(DriveAPState, NULL); From b8d4c4ae92435f07dd26f70b36207c72492a1955 Mon Sep 17 00:00:00 2001 From: wyhong <30567533+wy-hh@users.noreply.github.com> Date: Thu, 5 Jan 2023 00:46:03 +0800 Subject: [PATCH 07/31] [Bouffalolab] Refactor Bouffalolab SDK gn scripts (#24132) * create bl_iot_sdk.gni * update bl_iot_sdk.gni * remove more 702 specific-name * update bl602 * update bl602 & bl702 * update toolchain path * fix issues for bl602 * fix parition table for bl702 * fix restyle --- build_overrides/bouffalolab_iot_sdk.gni | 6 +- .../bouffalolab/args.gni | 12 +- .../bouffalolab}/toolchain/BUILD.gn | 0 .../toolchain/riscv_toolchain.gni | 0 .../build_overrides/bouffalolab_iot_sdk.gni | 9 +- .../lighting-app/bouffalolab/bl602/BUILD.gn | 12 +- .../bouffalolab/bl602/CHIPProjectConfig.h | 2 + .../lighting-app/bouffalolab/bl602/args.gni | 2 +- .../lighting-app/bouffalolab/bl702/BUILD.gn | 9 +- .../lighting-app/bouffalolab/bl702/args.gni | 2 +- .../bouffalolab/common/AppTask.cpp | 3 +- examples/platform/bouffalolab/bl602/BUILD.gn | 2 +- .../bouffalolab/bl602/FreeRTOSConfig.h | 188 ++-- .../bl602/route_hook/bl_route_hook.c | 1 + examples/platform/bouffalolab/bl702/BUILD.gn | 2 +- .../platform/bouffalolab/common/plat/main.cpp | 3 +- scripts/build/builders/bouffalolab.py | 3 +- scripts/examples/gn_bouffalolab_example.sh | 2 +- src/lwip/BUILD.gn | 10 +- .../bouffalolab/BL602/BL602Config.cpp | 61 +- .../bouffalolab/BL602/CHIPMem-Platform.cpp | 2 +- .../BL602/ConfigurationManagerImpl.cpp | 4 +- .../BL602/ConfigurationManagerImpl.h | 1 - .../BL602/ConnectivityManagerImpl.cpp | 6 +- .../BL602/DiagnosticDataProviderImpl.cpp | 8 +- .../BL602/KeyValueStoreManagerImpl.cpp | 4 +- src/platform/bouffalolab/BL602/Logging.cpp | 10 +- .../BL602/NetworkCommissioningDriver.cpp | 11 +- .../BL602/NetworkCommissioningDriver.h | 2 +- .../BL602/NetworkCommissioningWiFiDriver.cpp | 2 +- .../bouffalolab/BL602/PlatformManagerImpl.cpp | 14 +- .../bouffalolab/BL602/PlatformManagerImpl.h | 10 +- src/platform/bouffalolab/BL602/args.gni | 4 +- .../bouffalolab/BL602/wifi_mgmr_portable.c | 14 +- src/platform/bouffalolab/BL702/BUILD.gn | 6 +- src/platform/bouffalolab/BL702/Logging.cpp | 11 +- .../BL702/ThreadStackManagerImpl.cpp | 64 +- src/platform/bouffalolab/BL702/args.gni | 7 +- .../bouffalolab/BL702/bl702Config.cpp | 1 - third_party/bouffalolab/bl602/BUILD.gn | 12 +- third_party/bouffalolab/bl602/bl602_board.gni | 30 - third_party/bouffalolab/bl602/bl602_sdk.gni | 636 ------------- third_party/bouffalolab/bl602/bl_iot_sdk.gni | 889 ++++++++++++++++++ third_party/bouffalolab/bl702/BUILD.gn | 12 +- .../bouffalolab/bl702/bl702_executable.gni | 72 -- third_party/bouffalolab/bl702/bl702_sdk.gni | 821 ---------------- third_party/bouffalolab/bl702/bl_iot_sdk.gni | 826 ++++++++++++++++ .../bouffalolab_board.gni} | 9 +- .../bouffalolab_executable.gni} | 22 +- .../bl602_riscv.gni => common/rsicv.gni} | 2 - third_party/bouffalolab/repo | 2 +- 51 files changed, 1991 insertions(+), 1852 deletions(-) rename third_party/bouffalolab/bl702/bl702_riscv.gni => config/bouffalolab/args.gni (68%) rename {examples/platform/bouffalolab/common => config/bouffalolab}/toolchain/BUILD.gn (100%) rename {examples/platform/bouffalolab/common => config/bouffalolab}/toolchain/riscv_toolchain.gni (100%) delete mode 100644 third_party/bouffalolab/bl602/bl602_board.gni delete mode 100644 third_party/bouffalolab/bl602/bl602_sdk.gni create mode 100644 third_party/bouffalolab/bl602/bl_iot_sdk.gni delete mode 100644 third_party/bouffalolab/bl702/bl702_executable.gni delete mode 100644 third_party/bouffalolab/bl702/bl702_sdk.gni create mode 100644 third_party/bouffalolab/bl702/bl_iot_sdk.gni rename third_party/bouffalolab/{bl702/bl702_board.gni => common/bouffalolab_board.gni} (78%) rename third_party/bouffalolab/{bl602/bl602_executable.gni => common/bouffalolab_executable.gni} (81%) rename third_party/bouffalolab/{bl602/bl602_riscv.gni => common/rsicv.gni} (96%) diff --git a/build_overrides/bouffalolab_iot_sdk.gni b/build_overrides/bouffalolab_iot_sdk.gni index 77ab3440927271..2a87174c734d84 100644 --- a/build_overrides/bouffalolab_iot_sdk.gni +++ b/build_overrides/bouffalolab_iot_sdk.gni @@ -13,11 +13,7 @@ # limitations under the License. declare_args() { - # Root directory for bl602 SDK build files. - bl602_sdk_build_root = "//third_party/bouffalolab/bl602" - - # Root directory for bl702 SDK build files. - bl702_sdk_build_root = "//third_party/bouffalolab/bl702" + bouffalolab_iot_sdk_build_root = "//third_party/bouffalolab/" bouffalolab_sdk_root = "/opt/bouffalolab_sdk" } diff --git a/third_party/bouffalolab/bl702/bl702_riscv.gni b/config/bouffalolab/args.gni similarity index 68% rename from third_party/bouffalolab/bl702/bl702_riscv.gni rename to config/bouffalolab/args.gni index 2c525322f81cf8..a85d0ea655d0b4 100644 --- a/third_party/bouffalolab/bl702/bl702_riscv.gni +++ b/config/bouffalolab/args.gni @@ -1,4 +1,4 @@ -# Copyright (c) 2020 Project CHIP Authors +# 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. @@ -12,10 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("bl702_board.gni") +# Options from standalone-chip.mk that differ from configure defaults. These +# options are used from examples/. -riscv_arch = "rv32imfc" -riscv_abi = "ilp32f" -# riscv_cpu = "" -# riscv_float_abi = "hard" -# riscv_fpu = "" +custom_toolchain = + "//third_party/connectedhomeip/config/bouffalolab/toolchain:riscv_gcc" diff --git a/examples/platform/bouffalolab/common/toolchain/BUILD.gn b/config/bouffalolab/toolchain/BUILD.gn similarity index 100% rename from examples/platform/bouffalolab/common/toolchain/BUILD.gn rename to config/bouffalolab/toolchain/BUILD.gn diff --git a/examples/platform/bouffalolab/common/toolchain/riscv_toolchain.gni b/config/bouffalolab/toolchain/riscv_toolchain.gni similarity index 100% rename from examples/platform/bouffalolab/common/toolchain/riscv_toolchain.gni rename to config/bouffalolab/toolchain/riscv_toolchain.gni diff --git a/examples/build_overrides/bouffalolab_iot_sdk.gni b/examples/build_overrides/bouffalolab_iot_sdk.gni index 1eb018a7ef2c85..d66989f09abd37 100644 --- a/examples/build_overrides/bouffalolab_iot_sdk.gni +++ b/examples/build_overrides/bouffalolab_iot_sdk.gni @@ -13,13 +13,8 @@ # limitations under the License. declare_args() { - # Root directory for bl602 SDK build files. - bl602_sdk_build_root = - "//third_party/connectedhomeip/third_party/bouffalolab/bl602" - - # Root directory for bl702 SDK build files. - bl702_sdk_build_root = - "//third_party/connectedhomeip/third_party/bouffalolab/bl702" + bouffalolab_iot_sdk_build_root = + "//third_party/connectedhomeip/third_party/bouffalolab" bouffalolab_sdk_root = "/opt/bouffalolab_sdk" } diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index 369b732b02f49b..0b341d50c32675 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -16,8 +16,8 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("${bl602_sdk_build_root}/bl602_executable.gni") -import("${bl602_sdk_build_root}/bl602_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl602/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/device.gni") @@ -51,7 +51,7 @@ declare_args() { baudrate = 2000000 } -bl602_sdk("sdk") { +bl_iot_sdk("sdk") { include_dirs = [ "${chip_root}/src/platform/bouffalolab/BL602", "${example_dir}", @@ -66,6 +66,7 @@ bl602_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", "OTA_PERIODIC_QUERY_TIMEOUT=${ota_periodic_query_timeout}", "CHIP_UART_BAUDRATE=${baudrate}", + "SYS_AOS_LOOP_ENABLE", ] if (chip_enable_pw_rpc) { @@ -77,7 +78,7 @@ bl602_sdk("sdk") { } } -bl602_executable("lighting_app") { +bouffalolab_executable("lighting_app") { output_name = "chip-bl602-lighting-example.out" defines = [ @@ -85,8 +86,10 @@ bl602_executable("lighting_app") { "CHIP_UART_BAUDRATE=${baudrate}", "BL602_ENABLE", "START_ENTRY=bfl_main", + "SYS_AOS_LOOP_ENABLE", ] + bl_plat_name = "bl602" sources = [ "${examples_plat_dir}/route_hook/bl_route_hook.c", "${examples_plat_dir}/route_hook/bl_route_table.c", @@ -195,6 +198,7 @@ bl602_executable("lighting_app") { sources += [ "${examples_plat_common_dir}/plat/OTAConfig.cpp" ] } + cflags_c = [ "-Wno-sign-compare" ] ldscript = "${examples_plat_dir}/ldscripts/flash_rom.ld" ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] diff --git a/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h b/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h index 22befede6a48c4..9e9934c227c465 100644 --- a/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h +++ b/examples/lighting-app/bouffalolab/bl602/CHIPProjectConfig.h @@ -144,3 +144,5 @@ #define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) #define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +#define CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE 128 diff --git a/examples/lighting-app/bouffalolab/bl602/args.gni b/examples/lighting-app/bouffalolab/bl602/args.gni index 464b0c63ff827c..1a7e2dd427e021 100644 --- a/examples/lighting-app/bouffalolab/bl602/args.gni +++ b/examples/lighting-app/bouffalolab/bl602/args.gni @@ -17,7 +17,7 @@ import("//build_overrides/pigweed.gni") import("${chip_root}/config/standalone/args.gni") import("${chip_root}/src/platform/bouffalolab/BL602/args.gni") -bl602_sdk_target = get_label_info(":sdk", "label_no_toolchain") +bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" pw_assert_BACKEND = "$dir_pw_assert_log" diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index 5872505775bd15..65822676f89e04 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -16,8 +16,8 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("${bl702_sdk_build_root}/bl702_executable.gni") -import("${bl702_sdk_build_root}/bl702_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl702/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/device.gni") @@ -54,7 +54,7 @@ declare_args() { baudrate = 2000000 } -bl702_sdk("sdk") { +bl_iot_sdk("sdk") { include_dirs = [ "${example_dir}", "${example_common_dir}", @@ -88,8 +88,9 @@ bl702_sdk("sdk") { } } -bl702_executable("lighting_app") { +bouffalolab_executable("lighting_app") { output_name = "chip-bl702-lighting-example.out" + bl_plat_name = "bl702" defines = [ "APP_TASK_STACK_SIZE=2044", diff --git a/examples/lighting-app/bouffalolab/bl702/args.gni b/examples/lighting-app/bouffalolab/bl702/args.gni index ecfb7424c6d2e6..c76c3d0f267d17 100644 --- a/examples/lighting-app/bouffalolab/bl702/args.gni +++ b/examples/lighting-app/bouffalolab/bl702/args.gni @@ -17,7 +17,7 @@ import("//build_overrides/pigweed.gni") import("${chip_root}/config/standalone/args.gni") import("${chip_root}/src/platform/bouffalolab/BL702/args.gni") -bl702_sdk_target = get_label_info(":sdk", "label_no_toolchain") +bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" pw_assert_BACKEND = "$dir_pw_assert_log" diff --git a/examples/lighting-app/bouffalolab/common/AppTask.cpp b/examples/lighting-app/bouffalolab/common/AppTask.cpp index cae6be58e7dd75..2fe2a403357717 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/common/AppTask.cpp @@ -417,7 +417,8 @@ void AppTask::ChipEventHandler(const ChipDeviceEvent * event, intptr_t arg) #if CHIP_DEVICE_CONFIG_ENABLE_WIFI case DeviceEventType::kWiFiConnectivityChange: - ChipLogProgress(NotSpecified, "Wi-Fi state changed\r\n", ConnectivityMgr().IsWiFiStationConnected()); + ChipLogProgress(NotSpecified, "Wi-Fi state changed to %s.\r\n", + ConnectivityMgr().IsWiFiStationConnected() ? "connected" : "disconnected"); chip::app::DnssdServer::Instance().StartServer(); NetworkCommissioning::BLWiFiDriver::GetInstance().SaveConfiguration(); diff --git a/examples/platform/bouffalolab/bl602/BUILD.gn b/examples/platform/bouffalolab/bl602/BUILD.gn index d6ca0038a370ee..8e85778ebd1f57 100644 --- a/examples/platform/bouffalolab/bl602/BUILD.gn +++ b/examples/platform/bouffalolab/bl602/BUILD.gn @@ -15,7 +15,7 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/chip.gni") -import("${bl602_sdk_build_root}/bl602_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl602/bl_iot_sdk.gni") config("chip_examples_project_config") { include_dirs = [ "project_include" ] diff --git a/examples/platform/bouffalolab/bl602/FreeRTOSConfig.h b/examples/platform/bouffalolab/bl602/FreeRTOSConfig.h index 7d8553139871bb..96379643d791e3 100644 --- a/examples/platform/bouffalolab/bl602/FreeRTOSConfig.h +++ b/examples/platform/bouffalolab/bl602/FreeRTOSConfig.h @@ -97,11 +97,8 @@ 1 tab == 4 spaces! */ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H #include "platform.h" #include @@ -118,116 +115,101 @@ extern "C" { * See http://www.freertos.org/a00110.html. *----------------------------------------------------------*/ -/* Tickless mode is not used. */ - -/* Some of the standard demo test tasks assume a tick rate of 1KHz, even -though that is faster than would normally be warranted by a real -application. */ -#define configTICK_RATE_HZ (1000) - -/* The full demo always has tasks to run so the tick will never be turned -off. The blinky demo will use the default tickless idle implementation to -turn the tick off. */ -#define configUSE_TICKLESS_IDLE (0) +#define configSUPPORT_STATIC_ALLOCATION 1 -/* Hook function related definitions. */ -#define configUSE_TICK_HOOK (0) -#define configCHECK_FOR_STACK_OVERFLOW (2) -#define configUSE_MALLOC_FAILED_HOOK (1) -#define configUSE_IDLE_HOOK (0) - -#define configENERGY_MODE (sleepEM1) - -/* Main functions*/ -/* Run time stats gathering related definitions. */ -#define configGENERATE_RUN_TIME_STATS (0) - -/* Co-routine related definitions. */ -#define configUSE_CO_ROUTINES (0) +#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 related definitions. */ -#define configUSE_TIMERS (1) -#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) /* Highest priority */ -#define configTIMER_QUEUE_LENGTH (4) +/* 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) -/* Cortex-M specific definitions. */ -#ifdef __NVIC_PRIO_BITS -/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */ -#define configPRIO_BITS (__NVIC_PRIO_BITS) -#else -#define configPRIO_BITS 3 /* 7 priority levels */ +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) #endif -/* The lowest interrupt priority that can be used in a call to a "set priority" -function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY (0x07) - -/* The highest interrupt priority that can be used by any interrupt service -routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL -INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER -PRIORITY THAN THIS! (higher priorities are lower numeric values. */ -#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY (0x03) - -/* Interrupt priorities used by the kernel port layer itself. These are generic -to all Cortex-M ports, and do not rely on any particular library functions. */ -#define configKERNEL_INTERRUPT_PRIORITY (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) -/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! -See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ -#define configMAX_SYSCALL_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) - -/* FreeRTOS MPU specific definitions. */ -#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS (0) - -#define configCPU_CLOCK_HZ (10 * 1000 * 1000) -#define configUSE_PREEMPTION (1) -#define configUSE_TIME_SLICING (1) -#define configUSE_PORT_OPTIMISED_TASK_SELECTION (1) -#define configUSE_TICKLESS_IDLE_SIMPLE_DEBUG (1) /* See into vPortSuppressTicksAndSleep source code for explanation */ -#define configMAX_PRIORITIES (32) -#define configMINIMAL_STACK_SIZE ((unsigned short) 112) /* Number of words to use for Idle and Timer stacks */ -#define configMAX_TASK_NAME_LEN (16) -#define configUSE_16_BIT_TICKS (0) -#define configIDLE_SHOULD_YIELD (1) -#define configUSE_MUTEXES (1) -#define configUSE_RECURSIVE_MUTEXES (1) -#define configUSE_COUNTING_SEMAPHORES (1) -#define configQUEUE_REGISTRY_SIZE (8) -// #define configUSE_QUEUE_SETS (0) -// #define configUSE_NEWLIB_REENTRANT (0) -#define configENABLE_BACKWARD_COMPATIBILITY (1) -#define configSUPPORT_STATIC_ALLOCATION (1) - /* Optional functions - most linkers will remove unused functions anyway. */ -#define INCLUDE_vTaskPrioritySet (1) -#define INCLUDE_uxTaskPriorityGet (1) -#define INCLUDE_vTaskDelete (1) -#define INCLUDE_vTaskSuspend (1) -// #define INCLUDE_xResumeFromISR (1) -#define INCLUDE_vTaskDelayUntil (1) -#define INCLUDE_vTaskDelay (1) -#define INCLUDE_xTaskGetSchedulerState (0) -#define INCLUDE_xTaskGetCurrentTaskHandle (0) -#define INCLUDE_uxTaskGetStackHighWaterMark (1) -#define INCLUDE_xTaskGetIdleTaskHandle (0) -// #define INCLUDE_xTimerGetTimerDaemonTaskHandle (1) -// #define INCLUDE_pcTaskGetTaskName (1) -#define INCLUDE_eTaskGetState (1) -// #define INCLUDE_xEventGroupSetBitFromISR (1) -#define INCLUDE_xTimerPendFunctionCall (1) - +#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_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 + +extern void vAssertCalled(void); /* Stop if an assertion fails. */ #define configASSERT(x) \ if ((x) == 0) \ vAssertCalled() -/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS -standard names. */ -// #define vPortSVCHandler SVC_Handler -// #define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler +#if (configUSE_TICKLESS_IDLE != 0) +#include "portmacro.h" +extern void vApplicationSleep(TickType_t xExpectedIdleTime); +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif -#ifdef __cplusplus -} #endif diff --git a/examples/platform/bouffalolab/bl602/route_hook/bl_route_hook.c b/examples/platform/bouffalolab/bl602/route_hook/bl_route_hook.c index 230cccadd52657..bcdbcc4edef34a 100644 --- a/examples/platform/bouffalolab/bl602/route_hook/bl_route_hook.c +++ b/examples/platform/bouffalolab/bl602/route_hook/bl_route_hook.c @@ -12,6 +12,7 @@ #include "lwip/prot/ip6.h" #include "lwip/prot/nd6.h" #include "lwip/raw.h" +#include typedef struct bl_route_hook_t { diff --git a/examples/platform/bouffalolab/bl702/BUILD.gn b/examples/platform/bouffalolab/bl702/BUILD.gn index 8dc352bbdf5be2..df3ea0e637521e 100644 --- a/examples/platform/bouffalolab/bl702/BUILD.gn +++ b/examples/platform/bouffalolab/bl702/BUILD.gn @@ -15,7 +15,7 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/chip.gni") -import("${bl702_sdk_build_root}/bl702_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") config("chip_examples_project_config") { include_dirs = [ "project_include" ] diff --git a/examples/platform/bouffalolab/common/plat/main.cpp b/examples/platform/bouffalolab/common/plat/main.cpp index 29090ddbb02ee2..8dad0e2a958877 100644 --- a/examples/platform/bouffalolab/common/plat/main.cpp +++ b/examples/platform/bouffalolab/common/plat/main.cpp @@ -31,9 +31,10 @@ #include #include -#include extern "C" { +#include + #ifdef BL702_ENABLE #include #include diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index ed22de8ad88bb5..52e1e4e01e90d3 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -89,7 +89,8 @@ def __init__(self, self.argsOpt = [] self.chip_name = bouffalo_chip - toolchain = os.path.join(root, '../../examples/platform/bouffalolab/common/toolchain') + + toolchain = os.path.join(root, os.path.split(os.path.realpath(__file__))[0], '../../../config/bouffalolab/toolchain') toolchain = 'custom_toolchain="{}:riscv_gcc"'.format(toolchain) if toolchain: self.argsOpt.append(toolchain) diff --git a/scripts/examples/gn_bouffalolab_example.sh b/scripts/examples/gn_bouffalolab_example.sh index 7c40790619fed4..2b3725e0ab12ba 100755 --- a/scripts/examples/gn_bouffalolab_example.sh +++ b/scripts/examples/gn_bouffalolab_example.sh @@ -90,7 +90,7 @@ else baudrate=2000000 optArgs="" - optArgs=custom_toolchain=\"$MATTER_ROOT/examples/platform/bouffalolab/common/toolchain:riscv_gcc\" + optArgs=custom_toolchain=\"$MATTER_ROOT/config/bouffalolab/toolchain:riscv_gcc\" shift shift diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index 54f6d44372fc37..22f56ffc310769 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -107,11 +107,11 @@ if (current_os == "zephyr" || current_os == "mbed") { public_configs += [ "${psoc6_sdk_build_root}:psoc6_sdk_config" ] } } else if (lwip_platform == "bl702_lwip") { - import("//build_overrides/bl702_sdk.gni") + import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") group("lwip") { public_deps = [ ":lwip_buildconfig" ] - public_deps += [ "${bl702_sdk_build_root}:bl702_sdk" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] } group("all") { @@ -142,7 +142,7 @@ if (current_os == "zephyr" || current_os == "mbed") { } else if (lwip_platform == "bl602") { group("lwip") { public_deps = [ ":lwip_buildconfig" ] - public_deps += [ "${bl602_sdk_build_root}:bl602_sdk" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl602:bl_iot_sdk" ] } group("all") { @@ -195,9 +195,9 @@ if (current_os == "zephyr" || current_os == "mbed") { } else if (lwip_platform == "cyw30739") { public_deps += [ "${cyw30739_sdk_build_root}:cyw30739_sdk" ] } else if (lwip_platform == "bl602") { - public_deps += [ "${bl602_sdk_build_root}:bl602_sdk" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl602:bl602_sdk" ] } else if (lwip_platform == "bl702") { - public_deps += [ "${bl702_sdk_build_root}:bl702_sdk" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" ] } else if (lwip_platform == "mt793x") { public_deps += [ "${mt793x_sdk_build_root}:mt793x_sdk" ] } diff --git a/src/platform/bouffalolab/BL602/BL602Config.cpp b/src/platform/bouffalolab/BL602/BL602Config.cpp index 6f0d93f4b85b89..140b52d5fa0edd 100644 --- a/src/platform/bouffalolab/BL602/BL602Config.cpp +++ b/src/platform/bouffalolab/BL602/BL602Config.cpp @@ -33,7 +33,6 @@ #include #include -#include #include #include @@ -82,97 +81,69 @@ CHIP_ERROR BL602Config::Init() CHIP_ERROR BL602Config::ReadConfigValue(Key key, bool & val) { CHIP_ERROR err = CHIP_NO_ERROR; - bool tmpVal; - size_t ret, valLen; + size_t valLen = 0; - ret = ef_get_env_blob(key.name, &tmpVal, sizeof(tmpVal), &valLen); - if (ret <= 0) + ef_get_env_blob(key.name, &val, 1, &valLen); + if (0 == valLen) { err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } - SuccessOrExit(err); - - val = tmpVal; -exit: return err; } CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint32_t & val) { CHIP_ERROR err = CHIP_NO_ERROR; - uint32_t tmpVal; - size_t ret, valLen; + size_t valLen = 0; - ret = ef_get_env_blob(key.name, &tmpVal, sizeof(tmpVal), &valLen); - if (ret <= 0) + ef_get_env_blob(key.name, &val, sizeof(val), &valLen); + if (0 == valLen) { err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } - SuccessOrExit(err); - val = tmpVal; - -exit: return err; } CHIP_ERROR BL602Config::ReadConfigValue(Key key, uint64_t & val) { CHIP_ERROR err = CHIP_NO_ERROR; - uint64_t tmpVal; - size_t ret, valLen; + size_t valLen = 0; - ret = ef_get_env_blob(key.name, &tmpVal, sizeof(tmpVal), &valLen); - if (ret <= 0) + ef_get_env_blob(key.name, &val, sizeof(val), &valLen); + if (0 == valLen) { err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } - SuccessOrExit(err); - val = tmpVal; -exit: return err; } CHIP_ERROR BL602Config::ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) { - CHIP_ERROR err = CHIP_NO_ERROR; - char tmpVal[bufSize] = { 0 }; - size_t ret; + CHIP_ERROR err = CHIP_NO_ERROR; - ret = ef_get_env_blob(key.name, tmpVal, sizeof(tmpVal) - 1, NULL); - if ('\0' == tmpVal[0]) + outLen = 0; + ef_get_env_blob(key.name, buf, bufSize, &outLen); + if (0 == outLen) { err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } - SuccessOrExit(err); - outLen = ret; - Platform::CopyString(buf, outLen, tmpVal); - -exit: return err; } CHIP_ERROR BL602Config::ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) { - CHIP_ERROR err = CHIP_NO_ERROR; - char tmpVal[bufSize] = { 0 }; - size_t ret; - size_t savedLen = 0; + CHIP_ERROR err = CHIP_NO_ERROR; - ret = ef_get_env_blob(key.name, tmpVal, sizeof(tmpVal), &savedLen); - if (0 == savedLen) + ef_get_env_blob(key.name, buf, bufSize, &outLen); + if (0 == outLen) { err = CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND; } - SuccessOrExit(err); - outLen = ret; - memcpy(buf, tmpVal, outLen); - -exit: return err; } diff --git a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp b/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp index 5f1f07f97a6a77..3b9b274941bfb8 100644 --- a/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp +++ b/src/platform/bouffalolab/BL602/CHIPMem-Platform.cpp @@ -52,10 +52,10 @@ #include #include #include +#include extern "C" { #include -#include }; #if CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp index f207e295ca882f..5c53153867fbe0 100644 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.cpp @@ -32,9 +32,9 @@ #include extern "C" { -#include #include #include +#include } namespace chip { @@ -213,8 +213,6 @@ void ConfigurationManagerImpl::RunConfigUnitTest(void) void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) { - CHIP_ERROR err; - ChipLogProgress(DeviceLayer, "Performing factory reset"); ef_env_set_default(); ChipLogProgress(DeviceLayer, "System restarting"); diff --git a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h index e4d231711c473d..0183da4e3a007f 100644 --- a/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h +++ b/src/platform/bouffalolab/BL602/ConfigurationManagerImpl.h @@ -33,7 +33,6 @@ #include #endif -#include #include namespace chip { diff --git a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp index 02d296c492abd9..56e3ebf522a36b 100644 --- a/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/ConnectivityManagerImpl.cpp @@ -69,7 +69,7 @@ namespace chip { namespace DeviceLayer { ConnectivityManagerImpl ConnectivityManagerImpl::sInstance; -static ConnectivityManager::WiFiStationState ConnectivityManagerImpl::mWiFiStationState = +ConnectivityManager::WiFiStationState ConnectivityManagerImpl::mWiFiStationState = ConnectivityManager::kWiFiStationState_NotConnected; void ConnectivityManagerImpl::WifiStationStateChange(void) @@ -86,8 +86,6 @@ void ConnectivityManagerImpl::WifiStationStateChange(void) void ConnectivityManagerImpl::DriveStationState() { - -exit: return; } @@ -101,7 +99,7 @@ CHIP_ERROR ConnectivityManagerImpl::_SetWiFiStationMode(WiFiStationMode val) CHIP_ERROR err = CHIP_NO_ERROR; DeviceLayer::SystemLayer().ScheduleWork(DriveStationState, NULL); -exit: + return err; } diff --git a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp index e260e750a51493..9c972071a60631 100644 --- a/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/BL602/DiagnosticDataProviderImpl.cpp @@ -30,11 +30,11 @@ #include extern "C" { -#include #include +#include +#include #include -#include -#include +#include #include } @@ -248,7 +248,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId) CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType) { - int authmode; + // int authmode; // authmode = mgmr_get_security_type(); // securityType = MapAuthModeToSecurityType(authmode); diff --git a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp index a7036b041b0ea2..dc7aee8708d0f5 100644 --- a/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/KeyValueStoreManagerImpl.cpp @@ -47,7 +47,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Get(const char * key, void * value, size_t size_t outlen = 0; BL602Config::Key ckey = { key }; - err = BL602Config::ReadConfigValueBin(ckey, value, value_size, outlen); + err = BL602Config::ReadConfigValueBin(ckey, (uint8_t *) value, value_size, outlen); if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; @@ -69,7 +69,7 @@ CHIP_ERROR KeyValueStoreManagerImpl::_Put(const char * key, const void * value, CHIP_ERROR err = CHIP_NO_ERROR; BL602Config::Key ckey = { key }; - err = BL602Config::WriteConfigValueBin(ckey, value, value_size); + err = BL602Config::WriteConfigValueBin(ckey, (uint8_t *) value, value_size); if (CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND == err) { err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND; diff --git a/src/platform/bouffalolab/BL602/Logging.cpp b/src/platform/bouffalolab/BL602/Logging.cpp index 872fd3c65ce1cf..33397bd520f409 100644 --- a/src/platform/bouffalolab/BL602/Logging.cpp +++ b/src/platform/bouffalolab/BL602/Logging.cpp @@ -6,15 +6,7 @@ #include #include - -// #ifdef LOG_LOCAL_LEVEL -// #undef LOG_LOCAL_LEVEL -// #endif -// #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE - -extern "C" { -#include -} +#include #ifdef PW_RPC_ENABLED #include "PigweedLogger.h" diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index b99b4d212ae739..7cb2bfaad1cc20 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -16,14 +16,14 @@ */ #include +#include +#include #include #include #include +#include #include #include -#include -#include -#include #include #include @@ -47,7 +47,7 @@ constexpr char kWiFiCredentialsKeyName[] = "wifi-pass"; constexpr char blWiFiSSIDKeyName[] = "bl-wifi-ssid"; constexpr char blWiFiCredentialsKeyName[] = "bl-wifi-pass"; -static uint8_t WiFiSSIDStr[DeviceLayer::Internal::kMaxWiFiSSIDLength]; +static char WiFiSSIDStr[DeviceLayer::Internal::kMaxWiFiSSIDLength]; static uint8_t scan_type = 0; } // namespace @@ -184,7 +184,7 @@ CHIP_ERROR BLWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, memcpy(passwd, key, keyLen); wifi_interface_t wifi_interface; wifi_interface = wifi_mgmr_sta_enable(); - wifi_mgmr_sta_connect(wifi_interface, wifi_ssid, passwd, NULL, NULL, 0, 0); + wifi_mgmr_sta_connect(&wifi_interface, wifi_ssid, passwd, NULL, NULL, 0, 0); ReturnErrorOnFailure(ConnectivityMgr().SetWiFiStationMode(ConnectivityManager::kWiFiStationMode_Disabled)); @@ -221,7 +221,6 @@ void BLWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback { CHIP_ERROR err = CHIP_NO_ERROR; Status networkingStatus = Status::kSuccess; - static int save = 0; VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h index 70090297551aa3..fc08f778e8fbff 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.h @@ -16,8 +16,8 @@ */ #pragma once +#include #include -#include namespace chip { namespace DeviceLayer { diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningWiFiDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningWiFiDriver.cpp index c9a35fe40194fe..c469c5a90edb01 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningWiFiDriver.cpp @@ -19,9 +19,9 @@ #include #include #include +#include #include #include -#include #include #include diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp index 2d1e0dc8daf955..16fad1b9ffcf5f 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp @@ -31,14 +31,14 @@ #include #include +#include #include -#include #include #include #include #include -#include +#include #include extern "C" { @@ -165,13 +165,10 @@ static void WifiStaConnected(void) chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::WiFiConnectionStatus::kConnected)); } } +typedef void (*aos_event_cb)(input_event_t * event, void * private_data); void OnWiFiPlatformEvent(input_event_t * event, void * private_data) { - static char * ssid; - static char * password; - int ret; - switch (event->code) { case CODE_WIFI_ON_INIT_DONE: { @@ -223,7 +220,7 @@ void OnWiFiPlatformEvent(input_event_t * event, void * private_data) CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) { - CHIP_ERROR err; + CHIP_ERROR err = CHIP_NO_ERROR; static uint8_t stack_wifi_init = 0; TaskHandle_t backup_eventLoopTask; @@ -238,7 +235,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) if (1 == stack_wifi_init) { log_error("Wi-Fi already initialized!\r\n"); - return; + return CHIP_NO_ERROR; } hal_wifi_start_firmware_task(); @@ -255,6 +252,7 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); SuccessOrExit(err); Internal::GenericPlatformManagerImpl_FreeRTOS::mEventLoopTask = backup_eventLoopTask; + exit: return err; } diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h b/src/platform/bouffalolab/BL602/PlatformManagerImpl.h index f51556099cf911..861e446f0beec3 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.h +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.h @@ -24,20 +24,12 @@ #pragma once +#include #include namespace chip { namespace DeviceLayer { -typedef struct -{ - uint32_t time; - uint16_t type; - uint16_t code; - unsigned long value; - unsigned long extra; -} input_event_t; - /** * Concrete implementation of the PlatformManager singleton object for the BL602 platform. */ diff --git a/src/platform/bouffalolab/BL602/args.gni b/src/platform/bouffalolab/BL602/args.gni index 384290911e92e5..0f32696fb1c914 100644 --- a/src/platform/bouffalolab/BL602/args.gni +++ b/src/platform/bouffalolab/BL602/args.gni @@ -16,9 +16,9 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/chip.gni") import("${chip_root}/examples/platform/bouffalolab/bl602/args.gni") -riscv_platform_config = "${bl602_sdk_build_root}/bl602_riscv.gni" +riscv_platform_config = "${bouffalolab_iot_sdk_build_root}/common/rsicv.gni" -mbedtls_target = "${bl602_sdk_build_root}:bl602_sdk" +mbedtls_target = "${bouffalolab_iot_sdk_build_root}/bl602:bl_iot_sdk" chip_device_platform = "bl602" diff --git a/src/platform/bouffalolab/BL602/wifi_mgmr_portable.c b/src/platform/bouffalolab/BL602/wifi_mgmr_portable.c index 244ad2c1074591..c41c3bcc8562cb 100644 --- a/src/platform/bouffalolab/BL602/wifi_mgmr_portable.c +++ b/src/platform/bouffalolab/BL602/wifi_mgmr_portable.c @@ -1,16 +1,10 @@ -#include "wifi_mgmr.h" -#include "wifi_mgmr_api.h" +#include +#include +#include -#include #include #include -BLOG_DECLARE(tcal_power) -BLOG_DECLARE(scan) -#define USER_UNUSED(a) ((void) (a)) - -#define DEBUG_HEADER "[WF][SM] " - int wifi_mgmr_get_bssid(uint8_t * bssid) { int i; @@ -20,7 +14,7 @@ int wifi_mgmr_get_bssid(uint8_t * bssid) bssid[i] = wifiMgmr.wifi_mgmr_stat_info.bssid[i]; } - return; + return 0; } int wifi_mgmr_get_scan_ap_num(void) diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index 310c721a699d8e..7fde9b5495c34f 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -72,10 +72,10 @@ static_library("BL702") { # needed for MTD/FTD import("//build_overrides/bouffalolab_iot_sdk.gni") - import("${bl702_sdk_build_root}/bl702_sdk.gni") + import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") public_deps += [ - "${bl702_sdk_build_root}:bl702_sdk", - "${bl702_sdk_build_root}:mbedtls", + "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk", + "${bouffalolab_iot_sdk_build_root}/bl702:mbedtls", ] sources += [ diff --git a/src/platform/bouffalolab/BL702/Logging.cpp b/src/platform/bouffalolab/BL702/Logging.cpp index 24193ea434ae28..5bb986d63cb27d 100644 --- a/src/platform/bouffalolab/BL702/Logging.cpp +++ b/src/platform/bouffalolab/BL702/Logging.cpp @@ -14,22 +14,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include #include #include -#include - -extern "C" { -#include -} - #ifdef PW_RPC_ENABLED #include "PigweedLogger.h" #endif +#include +#include +#include + namespace chip { namespace Logging { namespace Platform { diff --git a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp b/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp index be9d29619aae4f..0fb93c75826058 100644 --- a/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/ThreadStackManagerImpl.cpp @@ -49,8 +49,13 @@ CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) CHIP_ERROR err = CHIP_NO_ERROR; ot_alarmInit(); +#ifdef OT_THREAD_PORT_1_3 + otRadio_opt_t opt; + opt.byte = 0; + ot_radioInit(opt); +#else ot_radioInit(); - +#endif // Initialize the generic implementation base classes. err = GenericThreadStackManagerImpl_FreeRTOS::DoInit(); SuccessOrExit(err); @@ -73,15 +78,18 @@ bool ThreadStackManagerImpl::IsInitialized() using namespace ::chip::DeviceLayer; -ot_system_event_t ot_system_event_var; +ot_system_event_t ot_system_event_var = OT_SYSTEM_EVENT_NONE; void otSysProcessDrivers(otInstance * aInstance) { +#ifdef OT_THREAD_PORT_1_3 + ot_system_event_t sevent = otrGetNotifyEvent(); +#else ot_system_event_t sevent = OT_SYSTEM_EVENT_NONE; - OT_GET_NOTIFY(sevent); +#endif + ot_alarmTask(sevent); - // ot_uartTask(sevent); ot_radioTask(sevent); } @@ -117,3 +125,51 @@ extern "C" void otPlatFree(void * aPtr) { free(aPtr); } + +#ifdef OT_THREAD_PORT_1_3 +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) +{ + uint32_t tag = otrEnterCrit(); + ot_system_event_var = (ot_system_event_t)(ot_system_event_var | sevent); + otrExitCrit(tag); + + otSysEventSignalPending(); +} +#endif diff --git a/src/platform/bouffalolab/BL702/args.gni b/src/platform/bouffalolab/BL702/args.gni index 77396b3b094c8d..6d7aad914b6a28 100644 --- a/src/platform/bouffalolab/BL702/args.gni +++ b/src/platform/bouffalolab/BL702/args.gni @@ -20,9 +20,9 @@ import("${chip_root}/examples/platform/bouffalolab/bl702/args.gni") chip_device_platform = "bl702" -riscv_platform_config = "${bl702_sdk_build_root}/bl702_riscv.gni" +riscv_platform_config = "${bouffalolab_iot_sdk_build_root}/common/rsicv.gni" -mbedtls_target = "${bl702_sdk_build_root}:mbedtls" +mbedtls_target = "${bouffalolab_iot_sdk_build_root}/bl702:mbedtls" chip_inet_config_enable_ipv4 = false chip_inet_config_enable_tcp_endpoint = false @@ -37,7 +37,8 @@ openthread_core_config_platform_check_file = "bl702-openthread-core-bl-config-check.h" openthread_project_include_dirs = [ "${chip_root}/src/platform/bouffalolab/BL702" ] -openthread_external_platform = "${bl702_sdk_build_root}:bl702_sdk" +openthread_external_platform = + "${bouffalolab_iot_sdk_build_root}/bl702:bl_iot_sdk" pw_build_LINK_DEPS = [ "$dir_pw_assert:impl", diff --git a/src/platform/bouffalolab/BL702/bl702Config.cpp b/src/platform/bouffalolab/BL702/bl702Config.cpp index d824474b7ad91b..a036a9277afe66 100644 --- a/src/platform/bouffalolab/BL702/bl702Config.cpp +++ b/src/platform/bouffalolab/BL702/bl702Config.cpp @@ -25,7 +25,6 @@ #include #include -// #include #include namespace chip { diff --git a/third_party/bouffalolab/bl602/BUILD.gn b/third_party/bouffalolab/bl602/BUILD.gn index 82413e63efd49c..d358e393114859 100644 --- a/third_party/bouffalolab/bl602/BUILD.gn +++ b/third_party/bouffalolab/bl602/BUILD.gn @@ -13,15 +13,15 @@ # limitations under the License. import("//build_overrides/bouffalolab_iot_sdk.gni") -import("${bl602_sdk_build_root}/bl602_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl602/bl_iot_sdk.gni") declare_args() { - # Build target to use for bl602 SDK. Use this to set global SDK defines. - bl602_sdk_target = "" + # Build target to use for Bouffalo Lab IOT SDK. Use this to set global SDK defines. + bl_iot_sdk_target = "" } -assert(bl602_sdk_target != "", "bl602_sdk_target must be specified") +assert(bl_iot_sdk_target != "", "bl_iot_sdk_target must be specified") -group("bl602_sdk") { - public_deps = [ bl602_sdk_target ] +group("bl_iot_sdk") { + public_deps = [ bl_iot_sdk_target ] } diff --git a/third_party/bouffalolab/bl602/bl602_board.gni b/third_party/bouffalolab/bl602/bl602_board.gni deleted file mode 100644 index 123f6ca46c61e5..00000000000000 --- a/third_party/bouffalolab/bl602/bl602_board.gni +++ /dev/null @@ -1,30 +0,0 @@ -# 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. - -declare_args() { - # BL602 board used - bl602_board = "BL-HWC-G1" -} - -if (bl602_board == "") { - # bl602_board = getenv("BL602_BOARD") - bl602_board = "BL-HWC-G1" -} - -assert(bl602_board != "", "bl602_board must be specified") - -board_defines = [] -# bl602_mcu = "" -# enable_fem = true -# board_defines += [ "PAL_RTCC_CLOCK_LFRCO" ] diff --git a/third_party/bouffalolab/bl602/bl602_sdk.gni b/third_party/bouffalolab/bl602/bl602_sdk.gni deleted file mode 100644 index fb8a661ef263ae..00000000000000 --- a/third_party/bouffalolab/bl602/bl602_sdk.gni +++ /dev/null @@ -1,636 +0,0 @@ -# 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") - -import("bl602_board.gni") - -declare_args() { - # Location of the bl602 SDK. - bl602_sdk_root = "${chip_root}/third_party/bouffalolab/repo" -} - -assert(bl602_sdk_root != "", "bl602_sdk_root must be specified") - -# Defines an bl602 SDK build target. -# -# Parameters: -# bl602_sdk_root - The location of the bl602 SDK. -# sources - The sources files to build. -template("bl602_sdk") { - if (defined(invoker.bl602_sdk_root)) { - bl602_sdk_root = invoker.bl602_sdk_root - } - - assert(bl602_sdk_root != "", "bl602_sdk_root must be specified") - - sdk_target_name = target_name - - config("${sdk_target_name}_config") { - include_dirs = [] - libs = [] - if (defined(invoker.include_dirs)) { - include_dirs += invoker.include_dirs - } - - if (defined(invoker.freertos_config)) { - cflags_c = [ - "-include", - rebase_path("${invoker.freertos_config}", root_build_dir), - ] - } - - # Treat these includes as system includes, so warnings in them are not fatal. - _include_dirs = [ - "${bl602_sdk_root}", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/config", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/panic", - - "${bl602_sdk_root}/components/network/lwip/lwip-port/config", - "${bl602_sdk_root}/components/network/lwip/src/include", - "${bl602_sdk_root}/components/network/lwip/src/include/lwip", - "${bl602_sdk_root}/components/network/lwip/src/include/lwip/apps", - "${bl602_sdk_root}/components/network/lwip/lwip-port", - "${bl602_sdk_root}/components/network/lwip/lwip-port/FreeRTOS", - "${bl602_sdk_root}/components/network/lwip/lwip-port/hook", - "${bl602_sdk_root}/components/network/lwip_mdns", - - #"${bl602_sdk_root}/components/network/lwip_mdns", - - "${bl602_sdk_root}/components/platform/hosal", - "${bl602_sdk_root}/components/platform/hosal/include", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal", - "${bl602_sdk_root}/components/utils/include", - "${bl602_sdk_root}/components/security/blcrypto_suite/priv_inc", - "${bl602_sdk_root}/components/security/blcrypto_suite/inc/blcrypto_suite", - - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Inc", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/platform_print", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/RISCV/Core/Include", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/soft_crc", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/partition", - - "${bl602_sdk_root}/components/sys/bltime/include", - - "${bl602_sdk_root}/components/stage/easyflash4/inc", - "${bl602_sdk_root}/components/sys/blmtd/include", - "${bl602_sdk_root}/components/stage/blfdt/inc", - - "${bl602_sdk_root}/components/stage/blog", - "${bl602_sdk_root}/components/stage/cli/cli/include", - "${bl602_sdk_root}/components/utils/include", - - "${chip_root}/third_party/mbedtls/repo/include", - - "${bl602_sdk_root}/components/sys/bloop/bloop/include", - "${bl602_sdk_root}/components/sys/bloop/loopset/include", - "${bl602_sdk_root}/components/sys/bloop/looprt/include", - - "${bl602_sdk_root}/components/fs/vfs/include", - "${bl602_sdk_root}/components/stage/yloop/include", - - "${bl602_sdk_root}/components/network/wifi/include", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal", - "${bl602_sdk_root}/components/stage/yloop/include/aos", - "${bl602_sdk_root}/components/stage/yloop/include/aos", - - "${bl602_sdk_root}/components/network/ble/blestack/src/common/include/zephyr", - "${bl602_sdk_root}/components/network/ble/blestack/src/port/include", - "${bl602_sdk_root}/components/network/ble/blestack/src", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/include", - "${bl602_sdk_root}/components/network/ble/blestack/src/include", - "${bl602_sdk_root}/components/network/ble/blestack/src/include/bluetooth", - "${bl602_sdk_root}/components/network/ble/blecontroller/ble_inc", - "${bl602_sdk_root}/components/network/ble/blestack/src/host", - "${bl602_sdk_root}/components/network/ble/blestack/src/include/drivers/bluetooth", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/include/misc", - "${bl602_sdk_root}/components/network/ble/blestack/src/common", - "${bl602_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt", - - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/include", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver", - "${bl602_sdk_root}/components/network/dns_server/include", - "${bl602_sdk_root}/components/network/rfparam_adapter_tmp/rftlv", - - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Inc", - "${bl602_sdk_root}/components/security/blcrypto_suite/inc/blcrypto_suite", - "${bl602_sdk_root}/components/security/blcrypto_suite/inc", - "${bl602_sdk_root}/components/security/blcrypto_suite/priv_inc", - "${bl602_sdk_root}/components/network/wifi/modules/supplicant/src/sae", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/platform_print", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/ring_buffer", - "${bl602_sdk_root}/components/utils/include", - - "${bl602_sdk_root}/components/stage/cli/cli/include/", - "${bl602_sdk_root}/components/sys/blota/include", - "${bl602_sdk_root}/components/utils/include/", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Inc/", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/", - - #bl602 portable - "${chip_root}/third_party/bouffalolab/bl602/portable", - - # rebase add - "${bl602_sdk_root}/components/network/wifi_hosal/include", - "${bl602_sdk_root}/components/os/bl_os_adapter/bl_os_adapter", - "${bl602_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/include", - "${bl602_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/include/bl_os_adapter", - "${bl602_sdk_root}/components/security/wpa_supplicant/include/bl_supplicant", - - # wpa_supplicant - "${bl602_sdk_root}/components/security/wpa_supplicant/port", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/ap", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/common", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/eap_peer", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/rsn_supp", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/utils", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps", - "${bl602_sdk_root}/components/security/wpa_supplicant/test", - "${bl602_sdk_root}/components/security/wpa_supplicant/port/include", - "${bl602_sdk_root}/components/security/wpa_supplicant/src", - "${bl602_sdk_root}/components/security/wpa_supplicant/include", - - "${bl602_sdk_root}/security/wpa_supplicant/src/", - - # hosal - "${bl602_sdk_root}/components/platform/hosal/sec_common", - ] - - # if (bl602_board == "BL-HWC-G1") { - # _include_dirs += [ "${bl602_sdk_root}/hardware/board/config/bl_hwc_g1" ] - # } - - bl_sdk_ver = getenv("BL_SDK_VER") - defines = [ - "MBEDTLS_CONFIG_FILE=\"bl602-chip-mbedtls-config.h\"", - "__STARTUP_CLEAR_BSS", - "HARD_FAULT_LOG_ENABLE", - "RETARGET_VCOM", - "RETARGET_USART0", - "ARCH_RISCV", - "portasmHANDLE_INTERRUPT=interrupt_entry", - - "SYS_APP_TASK_STACK_SIZE=2048", - "SYS_APP_TASK_PRIORITY=28", - "BL_SDK_VER=\"$bl_sdk_ver\"", - - "SYS_BLOG_ENABLE=1", - "SYS_VFS_ENABLE=1", - "SYS_AOS_LOOP_ENABLE=1", - "BL602_USE_HAL_DRIVER=1", - "BL602=BL602", - - "CFG_TXDESC=2", - "CFG_STA_MAX=1", - "CFG_CHIP_BL602", - - # "SYS_AOS_CLI_ENABLE=1", - - # set CONFIG_RENDEZVOUS_MODE to RENDEZVOUS_MODE_BLE (2) - "CONFIG_RENDEZVOUS_MODE=2", - - # bluetooth - "CONFIG_SET_TX_PWR", - "CFG_BLE_ENABLE", - "BFLB_BLE", - "CFG_BLE", - "CFG_SLEEP", - "OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER", - "CFG_BT_RESET", - "CFG_CON=1", - "CFG_BLE_TX_BUFF_DATA=2", - - # "CONFIG_BLE_TX_BUFF_DATA=2", - "CONFIG_BT_PERIPHERAL=1", - "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_GATT_DYNAMIC_DB", - "CONFIG_BT_GATT_SERVICE_CHANGED", - "CONFIG_BT_KEYS_OVERWRITE_OLDEST", - "CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING", - "CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS", - "CONFIG_BT_BONDABLE", - "CONFIG_BT_HCI_VS_EVT_USER", - "CONFIG_BT_ASSERT", - "CONFIG_BT_SETTINGS_CCC_LAZY_LOADING", - "CONFIG_BT_SETTINGS_USE_PRINTK", - "CFG_BLE_STACK_DBG_PRINT", - - #"__FILENAME__=__FILE__", - "__FILENAME__=\"\b\"", - "BL602_LOG_ENABLED=1", - "ENOTSUP=134", - - #dump backtrace - "CONF_ENABLE_FRAME_PTR=1", - "CONF_ENABLE_FUNC_BACKTRACE_ELF=out/bl602-light/chip-bl602-lighting-example.out", - "CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE=128", - - # board defines - "BL_CHIP_NAME=\"BL602\"", - - #include defines - "OS_USING_FREERTOS", - "BL602_MATTER_SUPPORT", - "PBUF_POOL_SIZE=20", - "TD_DIAGNOSIS_STA", - "CONFIG_ENABLE_IPV6_ADDR_CALLBACK", - "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", - "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", - ] - - defines += board_defines - - libs += [ - "${bl602_sdk_root}/components/network/wifi/lib/libwifi.a", - "${bl602_sdk_root}/components/network/ble/blecontroller_602_m0s1/lib/libblecontroller_602_m0s1.a", - ] - - cflags = [ - "-include", - rebase_path( - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/errno.h", - root_build_dir), - ] - - cflags += [ - "-Wno-maybe-uninitialized", - "-Wno-shadow", - "-Wno-error", - "-fcommon", - "-fno-jump-tables", - ] - - cflags_cc = [ "-fpermissive" ] - - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - - cflags += [ "-save-temps=obj" ] - cflags += [ "-Wno-maybe-uninitialized" ] - - if (defined(invoker.defines)) { - defines += invoker.defines - } - } - - source_set(sdk_target_name) { - sources = [ - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_boot2.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_flash.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_wdt.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hosal_gpio.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hosal_ota.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_cfg_ext.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sflash_ext.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_timer.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_xip_sflash_ext.c", - "${bl602_sdk_root}/components/stage/cli/cli/cli.c", - "${bl602_sdk_root}/components/stage/easyflash4/src/easyflash.c", - "${bl602_sdk_root}/components/stage/easyflash4/src/ef_env.c", - "${bl602_sdk_root}/components/stage/easyflash4/src/ef_port.c", - "${bl602_sdk_root}/components/stage/easyflash4/src/ef_utils.c", - "${bl602_sdk_root}/components/sys/blmtd/bl_mtd.c", - "${bl602_sdk_root}/components/sys/blota/bl_sys_ota_cli.c", - "${bl602_sdk_root}/components/utils/src/utils_hex.c", - "${bl602_sdk_root}/components/utils/src/utils_hexdump.c", - "${bl602_sdk_root}/components/utils/src/utils_sha256.c", - "${chip_root}/third_party/mbedtls/repo/library/aes.c", - "${chip_root}/third_party/mbedtls/repo/library/asn1parse.c", - "${chip_root}/third_party/mbedtls/repo/library/asn1write.c", - "${chip_root}/third_party/mbedtls/repo/library/bignum.c", - "${chip_root}/third_party/mbedtls/repo/library/ccm.c", - "${chip_root}/third_party/mbedtls/repo/library/cipher.c", - "${chip_root}/third_party/mbedtls/repo/library/cipher_wrap.c", - "${chip_root}/third_party/mbedtls/repo/library/constant_time.c", - "${chip_root}/third_party/mbedtls/repo/library/ctr_drbg.c", - "${chip_root}/third_party/mbedtls/repo/library/ecdh.c", - "${chip_root}/third_party/mbedtls/repo/library/ecdsa.c", - "${chip_root}/third_party/mbedtls/repo/library/ecp.c", - "${chip_root}/third_party/mbedtls/repo/library/ecp_curves.c", - "${chip_root}/third_party/mbedtls/repo/library/entropy.c", - "${chip_root}/third_party/mbedtls/repo/library/hkdf.c", - "${chip_root}/third_party/mbedtls/repo/library/hmac_drbg.c", - "${chip_root}/third_party/mbedtls/repo/library/md.c", - "${chip_root}/third_party/mbedtls/repo/library/oid.c", - "${chip_root}/third_party/mbedtls/repo/library/pk.c", - "${chip_root}/third_party/mbedtls/repo/library/pk_wrap.c", - "${chip_root}/third_party/mbedtls/repo/library/pkcs5.c", - "${chip_root}/third_party/mbedtls/repo/library/pkwrite.c", - "${chip_root}/third_party/mbedtls/repo/library/platform.c", - "${chip_root}/third_party/mbedtls/repo/library/platform_util.c", - "${chip_root}/third_party/mbedtls/repo/library/sha256.c", - "${chip_root}/third_party/mbedtls/repo/library/sha512.c", - "${chip_root}/third_party/mbedtls/repo/library/x509_create.c", - "${chip_root}/third_party/mbedtls/repo/library/x509write_csr.c", - ] - - sources += [ - "${bl602_sdk_root}/components/fs/vfs/device/vfs_uart.c", - "${bl602_sdk_root}/components/fs/vfs/src/vfs.c", - "${bl602_sdk_root}/components/fs/vfs/src/vfs_file.c", - "${bl602_sdk_root}/components/fs/vfs/src/vfs_inode.c", - "${bl602_sdk_root}/components/fs/vfs/src/vfs_register.c", - "${bl602_sdk_root}/components/libc/newlibc/stdatomic.c", - "${bl602_sdk_root}/components/libc/newlibc/syscalls.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/atomic_c.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/buf.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/dec.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/log.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/poll.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/common/work_q.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/hci_onchip/hci_driver.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/att.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/bl_host_assist.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/conn.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/crypto.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/gatt.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/hci_core.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/l2cap.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/settings.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/host/uuid.c", - "${bl602_sdk_root}/components/network/ble/blestack/src/port/bl_port.c", - "${bl602_sdk_root}/components/network/dns_server/src/dns_server.c", - "${bl602_sdk_root}/components/network/dns_server/src/web_server.c", - "${bl602_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c", - "${bl602_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/sys_arch.c", - "${bl602_sdk_root}/components/network/lwip/src/api/api_lib.c", - "${bl602_sdk_root}/components/network/lwip/src/api/api_msg.c", - "${bl602_sdk_root}/components/network/lwip/src/api/err.c", - "${bl602_sdk_root}/components/network/lwip/src/api/if_api.c", - "${bl602_sdk_root}/components/network/lwip/src/api/netbuf.c", - "${bl602_sdk_root}/components/network/lwip/src/api/netdb.c", - "${bl602_sdk_root}/components/network/lwip/src/api/netifapi.c", - "${bl602_sdk_root}/components/network/lwip/src/api/sockets.c", - "${bl602_sdk_root}/components/network/lwip/src/api/tcpip.c", - "${bl602_sdk_root}/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c", - "${bl602_sdk_root}/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls_mem.c", - "${bl602_sdk_root}/components/network/lwip/src/core/altcp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/altcp_alloc.c", - "${bl602_sdk_root}/components/network/lwip/src/core/altcp_tcp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/def.c", - "${bl602_sdk_root}/components/network/lwip/src/core/dns.c", - "${bl602_sdk_root}/components/network/lwip/src/core/inet_chksum.c", - "${bl602_sdk_root}/components/network/lwip/src/core/init.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ip.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/autoip.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/dhcp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/etharp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/icmp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/igmp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/ip4.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/ip4_addr.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv4/ip4_frag.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/dhcp6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/ethip6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/icmp6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/inet6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/ip6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/ip6_addr.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/ip6_frag.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/mld6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/ipv6/nd6.c", - "${bl602_sdk_root}/components/network/lwip/src/core/mem.c", - "${bl602_sdk_root}/components/network/lwip/src/core/memp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/netif.c", - "${bl602_sdk_root}/components/network/lwip/src/core/pbuf.c", - "${bl602_sdk_root}/components/network/lwip/src/core/raw.c", - "${bl602_sdk_root}/components/network/lwip/src/core/stats.c", - "${bl602_sdk_root}/components/network/lwip/src/core/sys.c", - "${bl602_sdk_root}/components/network/lwip/src/core/tcp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/tcp_in.c", - "${bl602_sdk_root}/components/network/lwip/src/core/tcp_out.c", - "${bl602_sdk_root}/components/network/lwip/src/core/timeouts.c", - "${bl602_sdk_root}/components/network/lwip/src/core/udp.c", - "${bl602_sdk_root}/components/network/lwip/src/core/utils.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/bridgeif.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/bridgeif_fdb.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/ethernet.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/lowpan6.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/lowpan6_ble.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/lowpan6_common.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/slipif.c", - "${bl602_sdk_root}/components/network/lwip/src/netif/zepif.c", - "${bl602_sdk_root}/components/network/lwip_dhcpd/dhcp_server_raw.c", - - #"${bl602_sdk_root}/components/network/lwip_mdns/mdns_server.c", - "${bl602_sdk_root}/components/network/sntp/sntp.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_cmds.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_irqs.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_main.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_mod_params.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_msg_rx.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_msg_tx.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_platform.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_rx.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_tx.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_utils.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/ipc_host.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/stateMachine.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_api.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_cli.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_event.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_ext.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_profile.c", - "${bl602_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_netif.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_chip.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_dma.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_efuse.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_gpio.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_hbn.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_irq.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_pds.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_pm.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_pwm.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_rtc.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_sec.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_sys.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_timer.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_uart.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/bl_wifi.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_board.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_boot2.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_button.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_gpio.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_hbn.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_sys.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hal_wifi.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hosal_dma.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hosal_pwm.c", - "${bl602_sdk_root}/components/platform/hosal/bl602_hal/hosal_uart.c", - "${bl602_sdk_root}/components/platform/hosal/sec_common/bl_sec_sha.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602/evb/src/boot/gcc/start.S", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602/evb/src/debug.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602/evb/src/strntoumax.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/platform_print/platform_device.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dma.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_ef_ctrl.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_glb.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_hbn.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_pwm.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sec_eng.c", - "${bl602_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_uart.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/event_groups.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/list.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/misaligned/fp_asm.S", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/misaligned/misaligned_ldst.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/panic/panic_c.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portASM.S", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/queue.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/stream_buffer.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/tasks.c", - "${bl602_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/timers.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_aes.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_bignum.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_ecp.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_ecp_curves.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_export_fw.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc_glue.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc_secp256r1_mul.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_platform_util.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_porting.c", - "${bl602_sdk_root}/components/stage/blfdt/src/fdt.c", - "${bl602_sdk_root}/components/stage/blfdt/src/fdt_ro.c", - "${bl602_sdk_root}/components/stage/blog/blog.c", - "${bl602_sdk_root}/components/stage/yloop/src/aos_freertos.c", - "${bl602_sdk_root}/components/stage/yloop/src/device.c", - "${bl602_sdk_root}/components/stage/yloop/src/local_event.c", - "${bl602_sdk_root}/components/stage/yloop/src/select.c", - "${bl602_sdk_root}/components/stage/yloop/src/yloop.c", - "${bl602_sdk_root}/components/sys/bloop/bloop/src/bloop_base.c", - "${bl602_sdk_root}/components/sys/bloop/bloop/src/bloop_handler_sys.c", - "${bl602_sdk_root}/components/sys/bloop/looprt/src/looprt.c", - "${bl602_sdk_root}/components/sys/bloop/loopset/src/loopset_led.c", - "${bl602_sdk_root}/components/sys/bltime/bl_sys_time.c", - "${bl602_sdk_root}/components/utils/src/utils_crc.c", - "${bl602_sdk_root}/components/utils/src/utils_dns.c", - "${bl602_sdk_root}/components/utils/src/utils_hmac_sha1_fast.c", - "${bl602_sdk_root}/components/utils/src/utils_list.c", - "${bl602_sdk_root}/components/utils/src/utils_log.c", - "${bl602_sdk_root}/components/utils/src/utils_notifier.c", - "${bl602_sdk_root}/components/utils/src/utils_psk_fast.c", - "${bl602_sdk_root}/components/utils/src/utils_rbtree.c", - - #rebase add - "${bl602_sdk_root}/components/network/rfparam_adapter_tmp/rftlv/phy_rftlv.c", - "${bl602_sdk_root}/components/network/wifi_hosal/port/wifi_hosal_bl602.c", - "${bl602_sdk_root}/components/network/wifi_hosal/wifi_hosal.c", - "${bl602_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/bl_os_hal.c", - "${bl602_sdk_root}/components/platform/hosal/sec_common/bl_sec_aes.c", - "${bl602_sdk_root}/components/platform/hosal/sec_common/bl_sec_pka.c", - "${bl602_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_supplicant_api.c", - "${bl602_sdk_root}/components/utils/src/utils_getopt.c", - "${bl602_sdk_root}/components/utils/src/utils_string.c", - "${bl602_sdk_root}/components/utils/src/utils_tlv_bl.c", - - #bl602 portable - # "${chip_root}/third_party/bouffalolab/bl602/portable/async_log.c", - # "${chip_root}/third_party/bouffalolab/bl602/portable/bfl_main.c", - # "${chip_root}/third_party/bouffalolab/bl602/portable/debug.c", - # "${chip_root}/third_party/bouffalolab/bl602/portable/wifi_mgmr_portable.c", - - #wap_supplicant - "${bl602_sdk_root}/components/security/wpa_supplicant/port/os_bl.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/ap/ap_config.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/ap/wpa_auth_ie.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/ap/wpa_auth_rsn_ccmp_only.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_hostap.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpa3.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpa_main.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpas_glue.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wps.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/common/sae.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/common/wpa_common.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-cbc.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-internal-bl.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-omac1.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-unwrap.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-wrap.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/crypto_internal-modexp.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/dh_group5.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/dh_groups.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/md5-internal.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/md5.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/rc4.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1-internal.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1-pbkdf2.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256-internal.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256-prf.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/eap_peer/eap_common.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/pmksa_cache.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/wpa.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/wpa_ie.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/utils/common.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/utils/wpa_debug.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/utils/wpabuf.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_build.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_parse.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_process.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_common.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_dev_attr.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_enrollee.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_registrar.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/src/wps/wps_validate.c", - "${bl602_sdk_root}/components/security/wpa_supplicant/test/test_crypto-bl.c", - ] - - # } else if (bl_family == "bl706") { - # sources += [ - # ] - # } - - public_deps = [ - # "${segger_rtt_root}:segger_rtt", - # "${segger_rtt_root}:segger_rtt_printf", - # "${segger_rtt_root}:segger_rtt_syscalls", - ] - - if (defined(invoker.sources)) { - sources += invoker.sources - } - - public_configs = [ ":${sdk_target_name}_config" ] - } -} diff --git a/third_party/bouffalolab/bl602/bl_iot_sdk.gni b/third_party/bouffalolab/bl602/bl_iot_sdk.gni new file mode 100644 index 00000000000000..f527f27132f791 --- /dev/null +++ b/third_party/bouffalolab/bl602/bl_iot_sdk.gni @@ -0,0 +1,889 @@ +# 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() { + bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" +} + +assert(bl_iot_sdk_root != "", "bl_iot_sdk_root must be specified") + +# Defines an Bouffa Lab IOT SDK build target. +# +# Parameters: +# bl_iot_sdk_root - The location of Bouffalo Lab IOT SDK. +# sources - The sources files to build. +template("bl_iot_sdk") { + sdk_target_name = target_name + + config("${sdk_target_name}_config") { + defines = [ + "__FILENAME__=strrchr(__FILE__,'/')?strrchr(__FILE__,'/')+1:__FILE__", + "ARCH_RISCV", + "BL602=BL602", + "BL602_USE_HAL_DRIVER=1", + + "CFG_CHIP_BL602", + + "MBEDTLS_CONFIG_FILE=\"bl602-chip-mbedtls-config.h\"", + + #dump backtrace + "CONF_ENABLE_FRAME_PTR=1", + "CONF_ENABLE_FUNC_BACKTRACE_ELF=out/bl602-light/chip-bl602-lighting-example.out", + ] + + include_dirs = [ "${chip_root}/third_party/mbedtls/repo/include" ] + if (defined(invoker.include_dirs)) { + include_dirs += invoker.include_dirs + } + + if (defined(invoker.defines)) { + defines += invoker.defines + } + + if (defined(invoker.freertos_config)) { + cflags_c = [ + "-include", + rebase_path("${invoker.freertos_config}", root_build_dir), + ] + } + } + + source_set("${sdk_target_name}_code") { + sources = [ + "${chip_root}/third_party/mbedtls/repo/library/aes.c", + "${chip_root}/third_party/mbedtls/repo/library/asn1parse.c", + "${chip_root}/third_party/mbedtls/repo/library/asn1write.c", + "${chip_root}/third_party/mbedtls/repo/library/bignum.c", + "${chip_root}/third_party/mbedtls/repo/library/ccm.c", + "${chip_root}/third_party/mbedtls/repo/library/cipher.c", + "${chip_root}/third_party/mbedtls/repo/library/cipher_wrap.c", + "${chip_root}/third_party/mbedtls/repo/library/constant_time.c", + "${chip_root}/third_party/mbedtls/repo/library/ctr_drbg.c", + "${chip_root}/third_party/mbedtls/repo/library/ecdh.c", + "${chip_root}/third_party/mbedtls/repo/library/ecdsa.c", + "${chip_root}/third_party/mbedtls/repo/library/ecp.c", + "${chip_root}/third_party/mbedtls/repo/library/ecp_curves.c", + "${chip_root}/third_party/mbedtls/repo/library/entropy.c", + "${chip_root}/third_party/mbedtls/repo/library/hkdf.c", + "${chip_root}/third_party/mbedtls/repo/library/hmac_drbg.c", + "${chip_root}/third_party/mbedtls/repo/library/md.c", + "${chip_root}/third_party/mbedtls/repo/library/oid.c", + "${chip_root}/third_party/mbedtls/repo/library/pk.c", + "${chip_root}/third_party/mbedtls/repo/library/pk_wrap.c", + "${chip_root}/third_party/mbedtls/repo/library/pkcs5.c", + "${chip_root}/third_party/mbedtls/repo/library/pkwrite.c", + "${chip_root}/third_party/mbedtls/repo/library/platform.c", + "${chip_root}/third_party/mbedtls/repo/library/platform_util.c", + "${chip_root}/third_party/mbedtls/repo/library/sha256.c", + "${chip_root}/third_party/mbedtls/repo/library/sha512.c", + "${chip_root}/third_party/mbedtls/repo/library/x509_create.c", + "${chip_root}/third_party/mbedtls/repo/library/x509write_csr.c", + ] + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ ":${sdk_target_name}_config" ] + } + + source_set("${sdk_target_name}_soc") { + defines = [ "BL602_MATTER_SUPPORT" ] + + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602/evb/src/boot/gcc/start.S", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602/evb/src/debug.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602/evb/src/strntoumax.c", + ] + cflags_c = [ "-Wno-format-truncation" ] + } + + config("${sdk_target_name}_config_BSP_Driver") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/RISCV/Device/Bouffalo/BL602/Startup", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/RISCV/Core/Include", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Device/Bouffalo/BL602/Peripherals", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Inc", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/platform_print", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/soft_crc", + ] + } + + source_set("${sdk_target_name}_BSP_Driver") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/ring_buffer", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/partition", + ] + + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/Common/platform_print/platform_device.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_acomp.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_adc.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_aon.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_common.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_common_ext.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dac.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_dma.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_ef_ctrl.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_glb.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_hbn.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_i2c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_ir.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_l1c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_efuse.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_flash.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_mfg_media.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_pds.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_pwm.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_romapi.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sdu.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sec_dbg.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sec_eng.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_cfg.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_cfg_ext.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sf_ctrl.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sflash.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_sflash_ext.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_spi.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_timer.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_tzc_sec.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_uart.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_xip_sflash.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/bl602_std/bl602_std/StdDriver/Src/bl602_xip_sflash_ext.c", + ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_BSP_Driver", + ] + cflags_c = [ + "-Wno-sign-compare", + "-Wno-unused-variable", + ] + } + + config("${sdk_target_name}_config_freertos") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/config", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/panic", + ] + } + + source_set("${sdk_target_name}_bl602_freertos") { + defines = [ "portasmHANDLE_INTERRUPT=interrupt_entry" ] + 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 = [ + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/event_groups.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/list.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/misaligned/fp_asm.S", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/misaligned/misaligned_ldst.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/panic/panic_c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/port.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/GCC/RISC-V/portASM.S", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/portable/MemMang/heap_5.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/queue.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/stream_buffer.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/tasks.c", + "${bl_iot_sdk_root}/components/platform/soc/bl602/freertos_riscv_ram/timers.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-old-style-declaration", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_freertos", + ] + } + + config("${sdk_target_name}_config_hosal") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/hosal/include", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/include", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common", + ] + + cflags_cc = [ "-Wno-literal-suffix" ] + } + + source_set("${sdk_target_name}_hosal") { + 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", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_chip.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_cks.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_clocktree.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_dac_audio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_dma.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_efuse.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_flash.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_gpio_cli.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_hbn.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_i2c.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_ir.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_irq.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_pds.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_pm.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_pwm.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_rtc.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_sec.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_sys.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_sys_cli.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_timer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_uart.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_wdt.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_wdt_cli.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/bl_wifi.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_board.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_boot2.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_button.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_hbn.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_hbnram.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_hwtimer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_ir.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_pds.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_sys.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hal_wifi.c", + + # hosal_adc.c is included by the code in wifi module + # "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_adc.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_dac.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_dma.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_efuse.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_flash.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_i2c.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_ota.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_pwm.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_rng.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_rtc.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_spi.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_timer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_uart.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl602_hal/hosal_wdg.c", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_aes.c", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_common.c", + "${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", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-shadow", + "-Wno-unused-but-set-variable", + "-Wno-old-style-declaration", + "-Wno-stringop-overflow", + "-Wno-format-truncation", + ] + configs += [ + ":${sdk_target_name}_config_wifi", + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_sys", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_hosal", + ] + } + + config("${sdk_target_name}_config_fs") { + include_dirs = [ "${bl_iot_sdk_root}/components/fs/vfs/include" ] + } + + source_set("${sdk_target_name}_fs") { + sources = [ + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_adc.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_gpio.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_pwm.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_spi.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_uart.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_file.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_inode.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_register.c", + ] + cflags_c = [ + "-Wno-sign-compare", + "-Wno-builtin-declaration-mismatch", + ] + configs += [ + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_fs", + ] + } + + source_set("${sdk_target_name}_libc") { + sources = [ + "${bl_iot_sdk_root}/components/libc/newlibc/assert.c", + "${bl_iot_sdk_root}/components/libc/newlibc/stdatomic.c", + "${bl_iot_sdk_root}/components/libc/newlibc/syscalls.c", + ] + cflags_c = [ "-Wno-builtin-declaration-mismatch" ] + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ ":${sdk_target_name}_config" ] + } + + config("${sdk_target_name}_config_stage") { + include_dirs = [ + "${bl_iot_sdk_root}/components/stage/easyflash4/inc", + "${bl_iot_sdk_root}/components/stage/yloop/include", + "${bl_iot_sdk_root}/components/stage/blog", + "${bl_iot_sdk_root}/components/stage/yloop/include/aos", + "${bl_iot_sdk_root}/components/stage/blfdt/inc", + "${bl_iot_sdk_root}/components/stage/cli/cli/include", + ] + } + + source_set("${sdk_target_name}_stage") { + sources = [ + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_addresses.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_empty_tree.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_overlay.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_ro.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_rw.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_strerror.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_sw.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_wip.c", + "${bl_iot_sdk_root}/components/stage/blog/blog.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/easyflash.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_env.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_port.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_utils.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/aos_freertos.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/device.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/local_event.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/select.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/yloop.c", + ] + cflags_c = [ "-Wno-sign-compare" ] + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_sys", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_stage", + ] + } + + config("${sdk_target_name}_config_sys") { + include_dirs = [ + "${bl_iot_sdk_root}/components/sys/bloop/bloop/include", + "${bl_iot_sdk_root}/components/sys/bloop/looprt/include", + "${bl_iot_sdk_root}/components/sys/bloop/loopset/include", + "${bl_iot_sdk_root}/components/sys/blmtd/include", + ] + } + + source_set("${sdk_target_name}_sys") { + include_dirs = [ "${bl_iot_sdk_root}/components/sys/bltime/include" ] + sources = [ + "${bl_iot_sdk_root}/components/sys/blmtd/bl_mtd.c", + "${bl_iot_sdk_root}/components/sys/bltime/bl_sys_time.c", + ] + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_sys", + ] + } + + config("${sdk_target_name}_config_utils") { + include_dirs = [ "${bl_iot_sdk_root}/components/utils/include/" ] + } + + source_set("${sdk_target_name}_utils") { + sources = [ + "${bl_iot_sdk_root}/components/utils/src/utils_base64.c", + "${bl_iot_sdk_root}/components/utils/src/utils_crc.c", + "${bl_iot_sdk_root}/components/utils/src/utils_dns.c", + "${bl_iot_sdk_root}/components/utils/src/utils_fec.c", + "${bl_iot_sdk_root}/components/utils/src/utils_getopt.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hex.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hexdump.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hmac_sha1_fast.c", + "${bl_iot_sdk_root}/components/utils/src/utils_list.c", + "${bl_iot_sdk_root}/components/utils/src/utils_log.c", + "${bl_iot_sdk_root}/components/utils/src/utils_memp.c", + "${bl_iot_sdk_root}/components/utils/src/utils_notifier.c", + "${bl_iot_sdk_root}/components/utils/src/utils_psk_fast.c", + "${bl_iot_sdk_root}/components/utils/src/utils_rbtree.c", + "${bl_iot_sdk_root}/components/utils/src/utils_sha256.c", + "${bl_iot_sdk_root}/components/utils/src/utils_string.c", + "${bl_iot_sdk_root}/components/utils/src/utils_time.c", + "${bl_iot_sdk_root}/components/utils/src/utils_tlv_bl.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + ] + configs += [ + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ] + } + + config("${sdk_target_name}_ble_config") { + include_dirs = [ + "${bl_iot_sdk_root}/components/network/ble/blecontroller/ble_inc", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include/bluetooth", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include/drivers/bluetooth", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include/zephyr", + "${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", + ] + + defines = [ + "BFLB_BLE", + "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", + ] + + cflags_cc = [ "-Wno-conversion" ] + } + + 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", + ] + + libs = [ "${bl_iot_sdk_root}/components/network/ble/blecontroller_602_m0s1/lib/libblecontroller_602_m0s1.a" ] + + include_dirs = [ + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include/misc", + ] + + sources = [ + "${bl_iot_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/atomic_c.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/buf.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/dec.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/log.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/poll.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/work_q.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/hci_onchip/hci_driver.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/att.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/bl_host_assist.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/conn.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/crypto.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/gatt.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/hci_core.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/l2cap.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/settings.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/uuid.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/port/bl_port.c", + ] + + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_ble_config", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-unused-but-set-variable", + "-Wno-misleading-indentation", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-function", + "-Wno-incompatible-pointer-types", + "-Wno-discarded-qualifiers", + ] + } + + config("${sdk_target_name}_config_blcrypto_suite") { + include_dirs = [ + "${bl_iot_sdk_root}/components/security/blcrypto_suite/inc", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/inc/blcrypto_suite", + ] + } + + source_set("${sdk_target_name}_blcrypto_suite") { + include_dirs = [ + "${bl_iot_sdk_root}/components/security/blcrypto_suite/priv_inc", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/priv_inc", + ] + sources = [ + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_aes.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_bignum.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_ecp.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_ecp_curves.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_export_fw.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc_glue.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_hacc_secp256r1_mul.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_platform_util.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_porting.c", + "${bl_iot_sdk_root}/components/security/blcrypto_suite/src/blcrypto_suite_supplicant_api.c", + ] + + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_blcrypto_suite", + ] + } + + config("${sdk_target_name}_config_wifi") { + defines = [ + "CFG_TXDESC=2", + "CFG_STA_MAX=1", + "BL_CHIP_NAME=\"BL602\"", + "TD_DIAGNOSIS_STA", + "OS_USING_FREERTOS", + ] + include_dirs = [ + "${bl_iot_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/include", + "${bl_iot_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/include/bl_os_adapter", + "${bl_iot_sdk_root}/components/network/wifi/include", + "${bl_iot_sdk_root}/components/network/wifi_hosal/include", + "${bl_iot_sdk_root}/components/network/wifi_manager", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/include", + ] + + cflags_c = [ "-Wno-sign-compare" ] + cflags_cc = [ "-Wno-sign-compare" ] + } + + source_set("${sdk_target_name}_wifi") { + defines = [ "BL602_MATTER_SUPPORT" ] + + include_dirs = [ + "${bl_iot_sdk_root}/components/os/bl_os_adapter/bl_os_adapter", + "${bl_iot_sdk_root}/components/network/dns_server/include", + "${bl_iot_sdk_root}/components/network/dns_server/include", + "${bl_iot_sdk_root}/components/network/rfparam_adapter_tmp/rftlv", + "${bl_iot_sdk_root}/components/network/wifi/modules/supplicant/src/sae", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/include", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/include/bl_supplicant", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/port", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/ap", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/common", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/eap_peer", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/rsn_supp", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/test", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/port/include", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/utils", + ] + + sources = [ "${bl_iot_sdk_root}/components/os/bl_os_adapter/bl_os_adapter/bl_os_hal.c" ] + + sources += [ + "${bl_iot_sdk_root}/components/network/rfparam_adapter_tmp/rftlv/phy_rftlv.c", + "${bl_iot_sdk_root}/components/network/wifi_hosal/port/wifi_hosal_bl602.c", + "${bl_iot_sdk_root}/components/network/wifi_hosal/wifi_hosal.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_cmds.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_irqs.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_main.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_mod_params.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_msg_rx.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_msg_tx.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_platform.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_rx.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_tx.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/bl_utils.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/ipc_host.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/stateMachine.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_api.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_cli.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_event.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_ext.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_mgmr_profile.c", + "${bl_iot_sdk_root}/components/network/wifi_manager/bl60x_wifi_driver/wifi_netif.c", + + #wap_supplicant + "${bl_iot_sdk_root}/components/network/dns_server/src/dns_server.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/port/os_bl.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/ap/ap_config.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/ap/wpa_auth_ie.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/ap/wpa_auth_rsn_ccmp_only.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_hostap.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpa3.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpa_main.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wpas_glue.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/bl_supplicant/bl_wps.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/common/sae.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/common/wpa_common.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-cbc.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-internal-bl.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-omac1.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-unwrap.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/aes-wrap.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/crypto_internal-modexp.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/dh_group5.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/dh_groups.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/md5-internal.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/md5.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/rc4.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1-internal.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1-pbkdf2.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha1.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256-internal.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256-prf.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/crypto/sha256.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/eap_peer/eap_common.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/pmksa_cache.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/wpa.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/rsn_supp/wpa_ie.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/utils/common.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/utils/wpa_debug.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/utils/wpabuf.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_build.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_parse.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_attr_process.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_common.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_dev_attr.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_enrollee.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_registrar.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/src/wps/wps_validate.c", + "${bl_iot_sdk_root}/components/security/wpa_supplicant/test/test_crypto-bl.c", + ] + + libs = [ "${bl_iot_sdk_root}/components/network/wifi/lib/libwifi.a" ] + + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_lwip", + ":${sdk_target_name}_config_blcrypto_suite", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_wifi", + ] + + deps = [ ":${sdk_target_name}_hosal" ] + + cflags_c = [ + "-Wno-unused-function", + "-Wno-shadow", + "-Wno-old-style-declaration", + "-Wno-incompatible-pointer-types", + "-Wno-format-security", + "-Wno-format-nonliteral", + "-Wno-unused-but-set-variable", + "-Wno-unused-variable", + "-fcommon", + ] + } + + config("${sdk_target_name}_config_lwip") { + include_dirs = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/config", + "${bl_iot_sdk_root}/components/network/lwip/src/include", + "${bl_iot_sdk_root}/components/network/lwip/src/include/lwip/apps", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/hook", + ] + + defines = [ + "LWIP_IPV6=1", + "LWIP_IPV4=1", + "LWIP_IPV6_DHCP6=1", + "LWIP_IPV6_SCOPES=0", + "LWIP_AUTOIP=1", + "LWIP_IPV6_MLD=1", + "LWIP_ND6_RDNSS_MAX_DNS_SERVERS=1", + "PBUF_POOL_SIZE=20", + "PBUF_POOL_BUFSIZE=(1280+150)", + "CONFIG_ENABLE_IPV6_ADDR_CALLBACK", + "CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT", + "CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT", + ] + } + + source_set("${sdk_target_name}_lwip") { + sources = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/sys_arch.c", + ] + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/netif/bridgeif.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/bridgeif_fdb.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/ethernet.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/slipif.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/zepif.c", + ] + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/core/def.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/dns.c", + "${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", + "${bl_iot_sdk_root}/components/network/lwip/src/core/raw.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/stats.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/sys.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp_in.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp_out.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/timeouts.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/udp.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", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/etharp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/icmp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/igmp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4_addr.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4_frag.c", + ] + + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/dhcp6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ethip6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/icmp6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/inet6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_addr.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_frag.c", + + #"${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_route_table.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/mld6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/nd6.c", + ] + + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/api/api_lib.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/api_msg.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/err.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/if_api.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/netbuf.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/netifapi.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/sockets.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/tcpip.c", + ] + sources += + [ "${bl_iot_sdk_root}/components/network/lwip/src/apps/mdns/mdns.c" ] + sources += + [ "${bl_iot_sdk_root}/components/network/lwip_dhcpd/dhcp_server_raw.c" ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lwip", + ] + } + + group(sdk_target_name) { + public_deps = [ + ":${sdk_target_name}_BSP_Driver", + ":${sdk_target_name}_bl602_freertos", + ":${sdk_target_name}_blcrypto_suite", + ":${sdk_target_name}_ble", + ":${sdk_target_name}_code", + ":${sdk_target_name}_fs", + ":${sdk_target_name}_hosal", + ":${sdk_target_name}_libc", + ":${sdk_target_name}_lwip", + ":${sdk_target_name}_soc", + ":${sdk_target_name}_stage", + ":${sdk_target_name}_sys", + ":${sdk_target_name}_utils", + ":${sdk_target_name}_wifi", + ] + } +} diff --git a/third_party/bouffalolab/bl702/BUILD.gn b/third_party/bouffalolab/bl702/BUILD.gn index 9842ba2b23ec24..3fe15787e3e0c8 100644 --- a/third_party/bouffalolab/bl702/BUILD.gn +++ b/third_party/bouffalolab/bl702/BUILD.gn @@ -14,14 +14,14 @@ import("//build_overrides/bouffalolab_iot_sdk.gni") import("//build_overrides/openthread.gni") -import("${bl702_sdk_build_root}/bl702_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl702/bl_iot_sdk.gni") declare_args() { - # Build target to use for bl702 SDK. Use this to set global SDK defines. - bl702_sdk_target = "" + # Build target to use for Bouffalo Lab IOT SDK. Use this to set global SDK defines. + bl_iot_sdk_target = "" } -assert(bl702_sdk_target != "", "bl702_sdk_target must be specified") +assert(bl_iot_sdk_target != "", "bl_iot_sdk_target must be specified") config("bl702_mbedtls_config") { defines = [ "MBEDTLS_CONFIG_FILE=\"bl702-chip-mbedtls-config.h\"" ] @@ -32,6 +32,6 @@ mbedtls_target("mbedtls") { include_dirs = [ "${chip_root}/src/platform/bouffalolab/BL702" ] } -group("bl702_sdk") { - public_deps = [ bl702_sdk_target ] +group("bl_iot_sdk") { + public_deps = [ bl_iot_sdk_target ] } diff --git a/third_party/bouffalolab/bl702/bl702_executable.gni b/third_party/bouffalolab/bl702/bl702_executable.gni deleted file mode 100644 index e50120b0255f24..00000000000000 --- a/third_party/bouffalolab/bl702/bl702_executable.gni +++ /dev/null @@ -1,72 +0,0 @@ -# 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") -import("//build_overrides/chip.gni") - -import("//build_overrides/bouffalolab_iot_sdk.gni") -import("${build_root}/toolchain/flashable_executable.gni") - -template("bl702_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" - } else if ("mac" == host_os || "darwin" == host_os) { - objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Darwin/bin/riscv64-unknown-elf-objcopy" - } - - # Copy flashing dependencies to the output directory so that the output - # is collectively self-contained; this allows flashing to work reliably - # even if the build and flashing steps take place on different machines - # or in different containers. - flashing_runtime_target = target_name + ".flashing_runtime" - flashing_script_inputs = [ - "${chip_root}/scripts/flashing/bouffalolab_firmware_utils.py", - "${chip_root}/scripts/flashing/firmware_utils.py", - - "${chip_root}/examples/platform/bouffalolab/bl702/flash_config/partition_cfg_2M.toml", - ] - copy(flashing_runtime_target) { - sources = flashing_script_inputs - outputs = [ "${root_out_dir}/{{source_file_part}}" ] - } - - flashing_script_generator = - "${chip_root}/scripts/flashing/gen_flashing_script.py" - flashing_script_name = output_base_name + ".flash.py" - flashing_options = [ "bouffalolab" ] - flashing_options += [ "--chipname" ] - flashing_options += [ "bl702" ] - flashing_options += [ "--xtal" ] - flashing_options += [ "32M" ] - flashing_options += [ "--pt" ] - flashing_options += - [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] - flashing_options += [ "--ota" ] - flashing_options += [ "ota_images/" ] - - # set 2000000 baudrate for image download by default - flashing_options += [ "--baudrate" ] - flashing_options += [ "2000000" ] - - flashable_executable(target_name) { - forward_variables_from(invoker, "*") - data_deps = [ ":${flashing_runtime_target}" ] - } -} diff --git a/third_party/bouffalolab/bl702/bl702_sdk.gni b/third_party/bouffalolab/bl702/bl702_sdk.gni deleted file mode 100644 index ebc49817e068e3..00000000000000 --- a/third_party/bouffalolab/bl702/bl702_sdk.gni +++ /dev/null @@ -1,821 +0,0 @@ -# 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("//build_overrides/openthread.gni") -import("${chip_root}/src/lib/lib.gni") -import("bl702_board.gni") - -import("${mbedtls_root}/mbedtls.gni") - -declare_args() { - # Location of the bl702 SDK. - bl702_sdk_root = "${chip_root}/third_party/bouffalolab/repo" - - enable_zigbee = false - - enable_cdc_module = false -} - -assert(bl702_sdk_root != "", "bl702_sdk_root must be specified") - -# Defines an bl702 SDK build target. -# -# Parameters: -# bl702_sdk_root - The location of the bl702 SDK. -# sources - The sources files to build. -template("bl702_sdk") { - sdk_target_name = target_name - - if (defined(invoker.bl702_sdk_root)) { - bl702_sdk_root = invoker.bl702_sdk_root - } - - if (defined(invoker.enable_zigbee)) { - enable_zigbee = invoker.enable_zigbee - } - - if (defined(invoker.enable_cdc_module)) { - enable_cdc_module = invoker.enable_cdc_module - } - - config("${sdk_target_name}_config") { - include_dirs = [] - if (defined(invoker.include_dirs)) { - include_dirs += invoker.include_dirs - } - - defines = [ - "CONFIG_RENDEZVOUS_MODE=2", - "CONFIG_ENABLE_PW_RPC=0", - "__FILENAME__=strrchr(__FILE__,'/')?strrchr(__FILE__,'/')+1:__FILE__", - "OT_FREERTOS_ENABLE=1", - ] - - if (defined(invoker.defines)) { - defines += invoker.defines - } - } - - config("${sdk_target_name}_plat_config") { - _include_dirs = [ - "${bl702_sdk_root}", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/config", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/panic", - - "${bl702_sdk_root}/components/sys/blmtd/include", - "${bl702_sdk_root}/components/utils/include/", - - "${bl702_sdk_root}/components/stage/yloop/include", - "${bl702_sdk_root}/components/stage/blfdt/inc", - "${bl702_sdk_root}/components/stage/blog/", - "${bl702_sdk_root}/components/stage/cli/cli/include", - "${bl702_sdk_root}/components/stage/coredump/inc", - "${bl702_sdk_root}/components/stage/easyflash4/inc", - - "${bl702_sdk_root}/components/fs/vfs/include", - - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Board", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/risc-v/Core/Include", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/regs", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/startup", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/inc", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/soft_crc", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/misc", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/ring_buffer", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/device", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/list", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/memheap", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Common/platform", - - "${bl702_sdk_root}/components/platform/hosal/bl702_hal", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/include", - "${bl702_sdk_root}/components/platform/hosal/include", - "${bl702_sdk_root}/components/platform/hosal/sec_common", - ] - - defines = [ - "ARCH_RISCV", - "bl706_iot=1", - ] - - defines += board_defines - - cflags = [] - cflags_c = [] - if (defined(invoker.freertos_config)) { - cflags_c += [ - "-include", - rebase_path("${invoker.freertos_config}", root_build_dir), - ] - } - - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - - if (defined(invoker.defines)) { - defines += invoker.defines - } - } - - source_set("${sdk_target_name}_drv") { - defines = [ - "BFLB_USE_ROM_DRIVER=1", - "BFLB_USE_HAL_DRIVER=1", - "CFG_USE_XTAL32K=1", - "CFG_BLE_ENABLE=1", - "BL702", - ] - - include_dirs = - [ "${bl702_sdk_root}/components/network/ble/blecontroller/ble_inc/" ] - - sources = [ - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_adc.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_boot2.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_chip.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_cks.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_dma.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_efuse.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_flash.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_gpio.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_hbn.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_irq.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_pds.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_psram.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_pwm.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_rtc.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_sec.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_sys.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_timer.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_uart.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_wdt.c", - - # "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_sec_aes.c", - # "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_sec_sha.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_wireless.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_board.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_boot2.c", - - # "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_tcal.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_button.c", - - # "${bl702_sdk_root}/components/platform/hosal/bl702_hal/bl_emac.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_gpio.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_hbn.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_hwtimer.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_pds.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_sys.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_adc.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_dac.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_dma.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_flash.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_gpio.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_i2c.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_ota.c", - - # "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_spi.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_pwm.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_rng.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_rtc.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_timer.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_uart.c", - "${bl702_sdk_root}/components/platform/hosal/bl702_hal/hosal_wdg.c", - - #"${bl702_sdk_root}/components/platform/hosal/bl702_hal/hal_uart.c", - ] - - sources += [ - "${bl702_sdk_root}/components/platform/hosal/sec_common/bl_sec_aes.c", - "${bl702_sdk_root}/components/platform/hosal/sec_common/bl_sec_pka.c", - - #"${bl702_sdk_root}/components/platform/hosal/sec_common/bl_sec_sha.c", - ] - - libs = [ "${bl702_sdk_root}/components/platform/soc/bl702/bl702_rf/lib/libbl702_rf.a" ] - - cflags_c = [ - "-Wno-unused-variable", - "-Wno-enum-conversion", - "-Wno-sign-compare", - "-Wno-old-style-declaration", - "-Wno-stringop-overflow", - "-Wno-format-truncation", - ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ] - } - - source_set("${sdk_target_name}_app") { - sources = [] - if (defined(invoker.sources)) { - sources += invoker.sources - } - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ] - } - - source_set("${sdk_target_name}_cdc") { - include_dirs = [ - "${bl702_sdk_root}/components/fs/vfs/include", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Inc", - ] - - defines = [ - "BFLB_USE_ROM_DRIVER=1", - "BFLB_USE_HAL_DRIVER=1", - ] - - sources = [ - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/bl702_hal_pcd.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/bl702_usb_cdc.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usb_device.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_cdc.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_cdc_if.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_conf.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_core.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_ctlreq.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_desc.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_ioreq.c", - ] - - cflags_c = [ "-Wno-sign-compare" ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ] - } - - source_set("${sdk_target_name}_bflb_platform") { - defines = [ - "BFLB_USE_ROM_DRIVER=1", - "BFLB_USE_HAL_DRIVER=1", - ] - - include_dirs = [ "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/hal_drv/inc" ] - - sources = [ - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_acomp.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_adc.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_aon.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_cam.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_clock.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_common.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_dac.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_dma.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_ef_ctrl.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_glb.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_hbn.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_i2c.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_i2s.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_ir.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_l1c.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_mjpeg.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_pds.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_psram.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_pwm.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_qdec.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_romapi.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sec_dbg.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sec_eng.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_cfg.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_cfg_ext.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_ctrl.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sflash.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sflash_ext.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_spi.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_timer.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_uart.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_usb.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_xip_sflash.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_xip_sflash_ext.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/misc/misc.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/ring_buffer/ring_buffer.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/soft_crc/softcrc.c", - ] - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ] - cflags_c = [ - "-Wno-sign-compare", - "-Wno-unused-variable", - ] - } - - source_set("${sdk_target_name}_plat") { - defines = [ - "portasmHANDLE_INTERRUPT=interrupt_entry", - "CFG_CPP_ENABLE=1", - "BL_SDK_VER=\"1.0\"", - "BFLB_USE_ROM_DRIVER=1", - "BFLB_USE_HAL_DRIVER=1", - ] - - sources = [ - "${bl702_sdk_root}/components/libc/newlibc/assert.c", - "${bl702_sdk_root}/components/libc/newlibc/stdatomic.c", - "${bl702_sdk_root}/components/libc/newlibc/syscalls.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702/evb/src/boot/gcc/start.S", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702/evb/src/debug.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702/evb/src/strntoumax.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702/evb/src/vprint.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/event_groups.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/list.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/misaligned/fp_asm.S", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/misaligned/misaligned_ldst.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/panic/panic_c.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/port.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/portASM.S", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/MemMang/heap_5.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/MemMang/heap_5_psram.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/queue.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/stream_buffer.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/tasks.c", - "${bl702_sdk_root}/components/platform/soc/bl702/bl702_freertos/timers.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_addresses.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_empty_tree.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_overlay.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_ro.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_rw.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_strerror.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_sw.c", - "${bl702_sdk_root}/components/stage/blfdt/src/fdt_wip.c", - "${bl702_sdk_root}/components/stage/blog/blog.c", - "${bl702_sdk_root}/components/stage/easyflash4/src/easyflash.c", - "${bl702_sdk_root}/components/stage/easyflash4/src/ef_env.c", - "${bl702_sdk_root}/components/stage/easyflash4/src/ef_port.c", - "${bl702_sdk_root}/components/stage/easyflash4/src/ef_utils.c", - "${bl702_sdk_root}/components/sys/blmtd/bl_mtd.c", - "${bl702_sdk_root}/components/utils/src/utils_list.c", - "${bl702_sdk_root}/components/utils/src/utils_log.c", - "${bl702_sdk_root}/components/utils/src/utils_string.c", - ] - - cflags_c = [ - "-Wno-old-style-declaration", - "-Wno-enum-conversion", - "-Wno-sign-compare", - ] - cflags_c += [ - "-Wno-builtin-declaration-mismatch", - "-Wno-format-truncation", - ] - - sources += [ - "${bl702_sdk_root}/components/fs/vfs/device/vfs_adc.c", - "${bl702_sdk_root}/components/fs/vfs/device/vfs_gpio.c", - "${bl702_sdk_root}/components/fs/vfs/device/vfs_pwm.c", - "${bl702_sdk_root}/components/fs/vfs/device/vfs_spi.c", - "${bl702_sdk_root}/components/fs/vfs/device/vfs_uart.c", - "${bl702_sdk_root}/components/fs/vfs/src/vfs.c", - "${bl702_sdk_root}/components/fs/vfs/src/vfs_file.c", - "${bl702_sdk_root}/components/fs/vfs/src/vfs_inode.c", - "${bl702_sdk_root}/components/fs/vfs/src/vfs_register.c", - "${bl702_sdk_root}/components/stage/yloop/src/aos_freertos.c", - "${bl702_sdk_root}/components/stage/yloop/src/device.c", - "${bl702_sdk_root}/components/stage/yloop/src/local_event.c", - "${bl702_sdk_root}/components/stage/yloop/src/select.c", - "${bl702_sdk_root}/components/stage/yloop/src/yloop.c", - "${bl702_sdk_root}/components/utils/src/utils_base64.c", - "${bl702_sdk_root}/components/utils/src/utils_crc.c", - "${bl702_sdk_root}/components/utils/src/utils_dns.c", - "${bl702_sdk_root}/components/utils/src/utils_fec.c", - "${bl702_sdk_root}/components/utils/src/utils_getopt.c", - "${bl702_sdk_root}/components/utils/src/utils_hex.c", - "${bl702_sdk_root}/components/utils/src/utils_hexdump.c", - "${bl702_sdk_root}/components/utils/src/utils_hmac_sha1_fast.c", - "${bl702_sdk_root}/components/utils/src/utils_memp.c", - "${bl702_sdk_root}/components/utils/src/utils_notifier.c", - "${bl702_sdk_root}/components/utils/src/utils_psk_fast.c", - "${bl702_sdk_root}/components/utils/src/utils_rbtree.c", - "${bl702_sdk_root}/components/utils/src/utils_sha256.c", - "${bl702_sdk_root}/components/utils/src/utils_time.c", - "${bl702_sdk_root}/components/utils/src/utils_tlv_bl.c", - ] - - cflags_c += [ "-Wno-shadow" ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ] - } - - config("${sdk_target_name}_ble_config") { - _include_dirs = [ - "${bl702_sdk_root}/components/network/ble/blestack/src/include", - "${bl702_sdk_root}/components/network/ble/blestack/src", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/include", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/include/misc", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/include/zephyr", - "${bl702_sdk_root}/components/network/ble/blestack/src/port/include", - "${bl702_sdk_root}/components/network/ble/blestack/src/include/bluetooth", - "${bl702_sdk_root}/components/network/ble/blecontroller/ble_inc", - "${bl702_sdk_root}/components/network/ble/blestack/src/include/drivers/bluetooth", - "${bl702_sdk_root}/components/network/ble/blestack/src/host", - ] - - defines = [ - "CONFIG_SET_TX_PWR", - "CFG_BLE_ENABLE", - "BFLB_BLE", - "CFG_BLE", - "CFG_SLEEP", - "OPTIMIZE_DATA_EVT_FLOW_FROM_CONTROLLER", - "CFG_BT_RESET", - "CFG_CON=1", - "CFG_BLE_TX_BUFF_DATA=2", - "CONFIG_BT_PERIPHERAL=1", - "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_GATT_DYNAMIC_DB", - "CONFIG_BT_GATT_SERVICE_CHANGED", - "CONFIG_BT_KEYS_OVERWRITE_OLDEST", - "CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING", - "CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS", - "CONFIG_BT_BONDABLE", - "CONFIG_BT_HCI_VS_EVT_USER", - "CONFIG_BT_ASSERT", - "CONFIG_BT_SETTINGS_CCC_LAZY_LOADING", - "CONFIG_BT_SETTINGS_USE_PRINTK", - "CFG_BLE_STACK_DBG_PRINT", - ] - - cflags = [] - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - } - - source_set("${sdk_target_name}_ble") { - defines = [ "BL702=1" ] - - include_dirs = [ - "${bl702_sdk_root}/components/network/ble/blestack/src/include", - "${bl702_sdk_root}/components/network/ble/blecontroller/ble_inc", - "${bl702_sdk_root}/components/network/ble/blestack/src/host", - "${bl702_sdk_root}/components/network/ble/blestack/src/include/drivers/bluetooth", - "${bl702_sdk_root}/components/network/ble/blestack/src/common", - "${bl702_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt", - ] - - sources = [ - "${bl702_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/atomic_c.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/buf.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/dec.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/log.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/poll.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/common/work_q.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/hci_onchip/hci_driver.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/att.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/bl_host_assist.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/conn.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/crypto.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/gatt.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/hci_core.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/l2cap.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/settings.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/host/uuid.c", - "${bl702_sdk_root}/components/network/ble/blestack/src/port/bl_port.c", - ] - - libs = [ "${bl702_sdk_root}/components/network/ble/blecontroller_702_std/lib/libblecontroller_702_std.a" ] - - configs += [ ":${sdk_target_name}_plat_config" ] - public_configs = [ ":${sdk_target_name}_ble_config" ] - - cflags_c = [ - "-Wno-sign-compare", - "-Wno-unused-but-set-variable", - "-Wno-misleading-indentation", - "-Wno-format", - "-Wno-format-nonliteral", - "-Wno-format-security", - "-Wno-unused-function", - "-Wno-incompatible-pointer-types", - "-Wno-discarded-qualifiers", - ] - } - - config("${sdk_target_name}_otport_config") { - _include_dirs = [ - "${chip_root}/platform/bl702", - "${chip_root}/third_party/openthread/repo/src/core", - "${chip_root}/third_party/openthread/repo/examples/platforms", - "${bl702_sdk_root}/components/network/thread/openthread_port/include", - ] - - cflags = [] - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - } - - source_set("${sdk_target_name}_otport") { - import("//build_overrides/openthread.gni") - - include_dirs = [ - "${bl702_sdk_root}/components/network/lmac154/include", - "${openthread_root}/examples/platforms/utils/", - "${openthread_root}/examples", - ] - - sources = [ - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_alarm.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_diag.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_entropy.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_logging.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_misc.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_radio.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_settings.c", - "${bl702_sdk_root}/components/network/thread/openthread_port/ot_uart.c", - - # "${bl702_sdk_root}/components/network/thread/openthread_port/ot_system.c", - # "${bl702_sdk_root}/components/network/thread/openthread_port/ot_freertos.c", - # "${bl702_sdk_root}/components/network/thread/openthread_port/ot_memory.c" - ] - - libs = [ "${bl702_sdk_root}/components/network/lmac154/lib/liblmac154.a" ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ":${sdk_target_name}_otport_config", - ] - - public_deps = [ - ":${sdk_target_name}_plat", - "${bl702_sdk_build_root}:mbedtls", - "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", - "${openthread_root}/src/core:libopenthread_core_headers", - ] - } - - config("${sdk_target_name}_lwip_port_config") { - _include_dirs = [ - "${bl702_sdk_root}/components/network/lwip/lwip-port", - "${bl702_sdk_root}/components/network/lwip/lwip-port/config", - "${bl702_sdk_root}/components/stage/virt_net/include", - "${bl702_sdk_root}/components/stage/throughput/bl702/inc", - ] - - defines = [ - "TCPIP_THREAD_PRIO=24", - "CFG_ETHERNET_ENABLE=1", - ] - - cflags = [] - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - - cflags += [ - "-Wno-conversion", - "-Wno-unused-function", - ] - } - - source_set("${sdk_target_name}_lwip_port") { - defines = [ - "SPI_WIFI_RXBUFF_IN_PSRAM=1", - "VIRT_NET_SPI_RX_TASK_PRIORITY=25", - ] - - # include_dirs = [ - # "${bl702_sdk_root}/components/network/lwip/lwip-port/arch", - # "${bl702_sdk_root}/components/network/lwip/lwip-port/FreeRTOS", - # "${bl702_sdk_root}/components/stage/throughput" - # ] - - # sources = [ - # "${bl702_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c", - # "${bl702_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/sys_arch.c" - # ] - - # sources += [ - # "${bl702_sdk_root}/components/stage/throughput/bl702/src/tp_spi_master.c", - # ] - # sources += [ - # "${bl702_sdk_root}/components/stage/virt_net/src/virt_net.c", - # "${bl702_sdk_root}/components/stage/virt_net/src/virt_net_spi.c", - # ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ":${sdk_target_name}_lwip_port_config", - ":${sdk_target_name}_lwip_config", - ] - - cflags = [ "-Wno-sign-compare" ] - } - - config("${sdk_target_name}_lwip_config") { - _include_dirs = [ - "${bl702_sdk_root}/components/network/lwip/src/include", - # "${bl702_sdk_root}/components/network/lwip_mdns", - ] - - defines = [ - "LWIP_IPV6=1", - "LWIP_IPV4=1", - "LWIP_IPV6_DHCP6=1", - "LWIP_IPV6_SCOPES=0", - "PBUF_POOL_SIZE=12", - "PBUF_POOL_BUFSIZE=(1280+150)", - ] - - cflags = [] - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - } - - source_set("${sdk_target_name}_lwip") { - sources = [ - "${bl702_sdk_root}/components/network/lwip/src/api/api_lib.c", - "${bl702_sdk_root}/components/network/lwip/src/api/api_msg.c", - "${bl702_sdk_root}/components/network/lwip/src/api/err.c", - "${bl702_sdk_root}/components/network/lwip/src/api/if_api.c", - "${bl702_sdk_root}/components/network/lwip/src/api/netbuf.c", - "${bl702_sdk_root}/components/network/lwip/src/api/netifapi.c", - "${bl702_sdk_root}/components/network/lwip/src/api/sockets.c", - "${bl702_sdk_root}/components/network/lwip/src/api/tcpip.c", - ] - - sources += [ - "${bl702_sdk_root}/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls.c", - "${bl702_sdk_root}/components/network/lwip/src/apps/altcp_tls/altcp_tls_mbedtls_mem.c", - ] - - sources += [ - "${bl702_sdk_root}/components/network/lwip/src/core/def.c", - "${bl702_sdk_root}/components/network/lwip/src/core/dns.c", - "${bl702_sdk_root}/components/network/lwip/src/core/inet_chksum.c", - "${bl702_sdk_root}/components/network/lwip/src/core/init.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ip.c", - "${bl702_sdk_root}/components/network/lwip/src/core/mem.c", - "${bl702_sdk_root}/components/network/lwip/src/core/memp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/netif.c", - "${bl702_sdk_root}/components/network/lwip/src/core/pbuf.c", - "${bl702_sdk_root}/components/network/lwip/src/core/raw.c", - "${bl702_sdk_root}/components/network/lwip/src/core/stats.c", - "${bl702_sdk_root}/components/network/lwip/src/core/sys.c", - "${bl702_sdk_root}/components/network/lwip/src/core/tcp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/tcp_in.c", - "${bl702_sdk_root}/components/network/lwip/src/core/tcp_out.c", - "${bl702_sdk_root}/components/network/lwip/src/core/timeouts.c", - "${bl702_sdk_root}/components/network/lwip/src/core/udp.c", - "${bl702_sdk_root}/components/network/lwip/src/include/lwip/priv/api_msg.h", - "${bl702_sdk_root}/components/network/lwip/src/include/lwip/priv/memp_std.h", - "${bl702_sdk_root}/components/network/lwip/src/include/lwip/priv/nd6_priv.h", - ] - - sources += [ - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/autoip.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/dhcp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/etharp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/icmp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/igmp.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/ip4.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/ip4_addr.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv4/ip4_frag.c", - ] - - sources += [ - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/dhcp6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/ethip6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/icmp6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/inet6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/ip6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/ip6_addr.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/ip6_frag.c", - - #"${bl702_sdk_root}/components/network/lwip/src/core/ipv6/ip6_route_table.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/mld6.c", - "${bl702_sdk_root}/components/network/lwip/src/core/ipv6/nd6.c", - ] - - sources += - [ "${bl702_sdk_root}/components/network/lwip/src/netif/slipif.c" ] - sources += - [ "${bl702_sdk_root}/components/network/lwip/src/netif/bridgeif.c" ] - sources += - [ "${bl702_sdk_root}/components/network/lwip/src/netif/bridgeif_fdb.c" ] - sources += - [ "${bl702_sdk_root}/components/network/lwip/src/netif/ethernet.c" ] - sources += [ "${bl702_sdk_root}/components/network/lwip/src/netif/zepif.c" ] - - sources += - [ "${bl702_sdk_root}/components/network/lwip/src/apps/mdns/mdns.c" ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ":${sdk_target_name}_lwip_port_config", - ":${sdk_target_name}_lwip_config", - ] - } - - config("${sdk_target_name}_zigbee_config") { - _include_dirs = [ - "${bl702_sdk_root}/components/network/zigbee/zbstack/", - "${bl702_sdk_root}/components/network/zigbee/zbstack/include", - "${bl702_sdk_root}/components/network/zigbee/zbstack/include/core", - "${bl702_sdk_root}/components/network/zigbee/zbstack/include/zcl", - "${bl702_sdk_root}/components/network/zigbee/zbcli/", - ] - - defines = [ "CFG_ZIGBEE_TOUCHLINK=1" ] - - cflags = [] - foreach(include_dir, _include_dirs) { - cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] - } - } - - source_set("${sdk_target_name}_zigbee") { - #sources = [ "${bl702_sdk_root}/components/network/zigbee/zbcli/zb_stack_cli.c" ] - - libs = [ - "${bl702_sdk_root}/components/network/zigbee/zbstack/lib/libzbstack.a", - "${bl702_sdk_root}/components/network/zigbee/zbstack/lib/libzbstackex.a", - ] - - public_configs = [ - ":${sdk_target_name}_config", - ":${sdk_target_name}_plat_config", - ":${sdk_target_name}_zigbee_config", - ] - ldflags = [ "-Wl,--defsym=__LD_CONFIG_FLASH_SIZE=0x100000" ] - cflags = [ - "-Wno-implicit-function-declaration", - "-Wno-incompatible-pointer-types", - "-Wno-unused-variable", - ] - } - - group(sdk_target_name) { - public_deps = [ - ":${sdk_target_name}_bflb_platform", - ":${sdk_target_name}_ble", - ":${sdk_target_name}_drv", - ":${sdk_target_name}_plat", - ] - - if (chip_enable_openthread) { - public_deps += [ ":${sdk_target_name}_otport" ] - } - - if (chip_enable_wifi) { - public_deps += [ ":${sdk_target_name}_lwip_port" ] - public_deps += [ ":${sdk_target_name}_lwip" ] - } - - if (enable_zigbee) { - public_deps += [ ":${sdk_target_name}_zigbee" ] - } - - if (enable_cdc_module) { - public_deps += [ ":${sdk_target_name}_cdc" ] - } - - public_deps += [ ":${sdk_target_name}_app" ] - } -} diff --git a/third_party/bouffalolab/bl702/bl_iot_sdk.gni b/third_party/bouffalolab/bl702/bl_iot_sdk.gni new file mode 100644 index 00000000000000..9e96105373928a --- /dev/null +++ b/third_party/bouffalolab/bl702/bl_iot_sdk.gni @@ -0,0 +1,826 @@ +# 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("//build_overrides/openthread.gni") +import("${chip_root}/src/lib/lib.gni") + +import("${mbedtls_root}/mbedtls.gni") + +declare_args() { + bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo" + + enable_cdc_module = false + + thread_port_1_3 = false +} + +assert(bl_iot_sdk_root != "", "bl_iot_sdk_root must be specified") + +# Defines an Bouffa Lab IOT SDK build target. +# +# Parameters: +# bl_iot_sdk_root - The location of Bouffalo Lab IOT SDK. +# sources - The sources files to build. +template("bl_iot_sdk") { + sdk_target_name = target_name + + if (defined(invoker.enable_zigbee)) { + enable_zigbee = invoker.enable_zigbee + } + + if (defined(invoker.enable_cdc_module)) { + enable_cdc_module = invoker.enable_cdc_module + } + + config("${sdk_target_name}_config") { + defines = [ + "__FILENAME__=strrchr(__FILE__,'/')?strrchr(__FILE__,'/')+1:__FILE__", + "ARCH_RISCV", + "BL702=BL702", + "BFLB_USE_ROM_DRIVER=1", + "BFLB_USE_HAL_DRIVER=1", + ] + + include_dirs = [] + if (defined(invoker.include_dirs)) { + include_dirs += invoker.include_dirs + } + + if (defined(invoker.defines)) { + defines += invoker.defines + } + + if (defined(invoker.freertos_config)) { + cflags_c = [ + "-include", + rebase_path("${invoker.freertos_config}", root_build_dir), + ] + } + } + + config("${sdk_target_name}_config_soc") { + include_dirs = + [ "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_rf/include" ] + } + + source_set("${sdk_target_name}_soc") { + defines = [ "CFG_CPP_ENABLE" ] + + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702/evb/src/boot/gcc/start.S", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702/evb/src/debug.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702/evb/src/strntoumax.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702/evb/src/vprint.c", + ] + + libs = [ "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_rf/lib/libbl702_rf.a" ] + + cflags_c = [ "-Wno-format-truncation" ] + } + + config("${sdk_target_name}_config_BSP_Driver") { + include_dirs = [ + "${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", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/risc-v/Core/Include", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/soft_crc", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/MCU_Common/misc", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Common/platform/", + ] + + defines = [ "bl706_iot" ] + } + + source_set("${sdk_target_name}_BSP_Driver") { + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_acomp.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_adc.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_aon.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_cam.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_clock.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_common.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_dac.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_dma.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_ef_ctrl.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_emac.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_glb.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_hbn.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_i2c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_i2c_gpio_sim.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_i2s.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_ir.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_kys.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_l1c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_mjpeg.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_pds.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_psram.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_pwm.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_qdec.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_romapi.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sec_dbg.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sec_eng.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_cfg.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_cfg_ext.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sf_ctrl.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sflash.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_sflash_ext.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_spi.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_timer.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_uart.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_usb.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_xip_sflash.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_std/BSP_Driver/std_drv/src/bl702_xip_sflash_ext.c", + ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_BSP_Driver", + ] + cflags_c = [ + "-Wno-sign-compare", + "-Wno-unused-variable", + ] + } + + config("${sdk_target_name}_config_freertos") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/config", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/panic", + ] + } + + source_set("${sdk_target_name}_bl702_freertos") { + defines = [ "portasmHANDLE_INTERRUPT=interrupt_entry" ] + include_dirs = [ "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/chip_specific_extensions/RV32F_float_abi_single" ] + + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/event_groups.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/list.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/misaligned/fp_asm.S", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/misaligned/misaligned_ldst.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/panic/panic_c.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/port.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/GCC/RISC-V/portASM.S", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/MemMang/heap_5.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/portable/MemMang/heap_5_psram.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/queue.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/stream_buffer.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/tasks.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_freertos/timers.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-old-style-declaration", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_freertos", + ] + } + + source_set("${sdk_target_name}_bl702_usb_cdc") { + include_dirs = [ + "${bl_iot_sdk_root}/components/fs/vfs/include", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Inc", + ] + + sources = [ + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/bl702_hal_pcd.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/bl702_usb_cdc.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usb_device.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_cdc.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_cdc_if.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_conf.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_core.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_ctlreq.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_desc.c", + "${bl_iot_sdk_root}/components/platform/soc/bl702/bl702_usb_cdc/Src/usbd_ioreq.c", + ] + + cflags_c = [ "-Wno-sign-compare" ] + + public_configs = [ ":${sdk_target_name}_config" ] + } + + config("${sdk_target_name}_config_hosal") { + include_dirs = [ + "${bl_iot_sdk_root}/components/platform/hosal/include", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/include", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common", + ] + + cflags_cc = [ "-Wno-literal-suffix" ] + } + + source_set("${sdk_target_name}_hosal") { + defines = [ "CFG_USE_XTAL32K=1" ] + + 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", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_chip.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_cks.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_dma.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_efuse.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_emac.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_flash.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_hbn.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_ir.c", + "${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_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", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_sys.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_timer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_uart.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_wdt.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/bl_wireless.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_board.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_boot2.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_button.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_hbn.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_hwtimer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_pds.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_sys.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hal_tcal.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_adc.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_dac.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_dma.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_flash.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_gpio.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_i2c.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_ota.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_pwm.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_rng.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_rtc.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_spi.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_timer.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_uart.c", + "${bl_iot_sdk_root}/components/platform/hosal/bl702_hal/hosal_wdg.c", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_aes.c", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_common.c", + "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_pka.c", + + # need update bl_sec_sha.c to fix compile error + # "${bl_iot_sdk_root}/components/platform/hosal/sec_common/bl_sec_sha.c", + ] + + cflags_c = [ + "-Wno-unused-variable", + "-Wno-sign-compare", + "-Wno-enum-conversion", + "-Wno-old-style-declaration", + "-Wno-stringop-overflow", + "-Wno-format-truncation", + ] + configs += [ + ":${sdk_target_name}_config_soc", + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_sys", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_hosal", + ] + } + + config("${sdk_target_name}_config_fs") { + include_dirs = [ "${bl_iot_sdk_root}/components/fs/vfs/include" ] + } + + source_set("${sdk_target_name}_fs") { + sources = [ + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_adc.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_gpio.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_pwm.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_spi.c", + "${bl_iot_sdk_root}/components/fs/vfs/device/vfs_uart.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_file.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_inode.c", + "${bl_iot_sdk_root}/components/fs/vfs/src/vfs_register.c", + ] + cflags_c = [ + "-Wno-sign-compare", + "-Wno-builtin-declaration-mismatch", + ] + configs += [ + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_fs", + ] + } + + source_set("${sdk_target_name}_libc") { + sources = [ + "${bl_iot_sdk_root}/components/libc/newlibc/assert.c", + "${bl_iot_sdk_root}/components/libc/newlibc/stdatomic.c", + "${bl_iot_sdk_root}/components/libc/newlibc/syscalls.c", + ] + cflags_c = [ "-Wno-builtin-declaration-mismatch" ] + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ ":${sdk_target_name}_config" ] + } + + config("${sdk_target_name}_config_stage") { + include_dirs = [ + "${bl_iot_sdk_root}/components/stage/easyflash4/inc", + "${bl_iot_sdk_root}/components/stage/yloop/include", + "${bl_iot_sdk_root}/components/stage/blog", + "${bl_iot_sdk_root}/components/stage/yloop/include/aos", + "${bl_iot_sdk_root}/components/stage/blfdt/inc", + "${bl_iot_sdk_root}/components/stage/cli/cli/include", + ] + } + + source_set("${sdk_target_name}_stage") { + sources = [ + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_addresses.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_empty_tree.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_overlay.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_ro.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_rw.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_strerror.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_sw.c", + "${bl_iot_sdk_root}/components/stage/blfdt/src/fdt_wip.c", + "${bl_iot_sdk_root}/components/stage/blog/blog.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/easyflash.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_env.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_port.c", + "${bl_iot_sdk_root}/components/stage/easyflash4/src/ef_utils.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/aos_freertos.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/device.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/local_event.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/select.c", + "${bl_iot_sdk_root}/components/stage/yloop/src/yloop.c", + ] + cflags_c = [ "-Wno-sign-compare" ] + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_fs", + ":${sdk_target_name}_config_sys", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_stage", + ] + } + + config("${sdk_target_name}_config_sys") { + include_dirs = [ + "${bl_iot_sdk_root}/components/sys/bloop/bloop/include", + "${bl_iot_sdk_root}/components/sys/bloop/looprt/include", + "${bl_iot_sdk_root}/components/sys/bloop/loopset/include", + "${bl_iot_sdk_root}/components/sys/blmtd/include", + ] + } + + source_set("${sdk_target_name}_sys") { + include_dirs = [ "${bl_iot_sdk_root}/components/sys/bltime/include" ] + sources = [ + "${bl_iot_sdk_root}/components/sys/blmtd/bl_mtd.c", + "${bl_iot_sdk_root}/components/sys/bltime/bl_sys_time.c", + ] + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_sys", + ] + } + + config("${sdk_target_name}_config_utils") { + include_dirs = [ "${bl_iot_sdk_root}/components/utils/include/" ] + } + + source_set("${sdk_target_name}_utils") { + sources = [ + "${bl_iot_sdk_root}/components/utils/src/utils_base64.c", + "${bl_iot_sdk_root}/components/utils/src/utils_crc.c", + "${bl_iot_sdk_root}/components/utils/src/utils_dns.c", + "${bl_iot_sdk_root}/components/utils/src/utils_fec.c", + "${bl_iot_sdk_root}/components/utils/src/utils_getopt.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hex.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hexdump.c", + "${bl_iot_sdk_root}/components/utils/src/utils_hmac_sha1_fast.c", + "${bl_iot_sdk_root}/components/utils/src/utils_list.c", + "${bl_iot_sdk_root}/components/utils/src/utils_log.c", + "${bl_iot_sdk_root}/components/utils/src/utils_memp.c", + "${bl_iot_sdk_root}/components/utils/src/utils_notifier.c", + "${bl_iot_sdk_root}/components/utils/src/utils_psk_fast.c", + "${bl_iot_sdk_root}/components/utils/src/utils_rbtree.c", + "${bl_iot_sdk_root}/components/utils/src/utils_sha256.c", + "${bl_iot_sdk_root}/components/utils/src/utils_string.c", + "${bl_iot_sdk_root}/components/utils/src/utils_time.c", + "${bl_iot_sdk_root}/components/utils/src/utils_tlv_bl.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + ] + configs += [ + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ] + } + + config("${sdk_target_name}_ble_config") { + include_dirs = [ + "${bl_iot_sdk_root}/components/network/ble/blecontroller/ble_inc", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include/bluetooth", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/include/drivers/bluetooth", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include/zephyr", + "${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", + ] + + defines = [ + "BFLB_BLE", + "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", + ] + + cflags_cc = [ "-Wno-conversion" ] + } + + 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", + ] + + libs = [ "${bl_iot_sdk_root}/components/network/ble/blecontroller_702_std/lib/libblecontroller_702_std.a" ] + + include_dirs = [ + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/tinycrypt/include/tinycrypt", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/include/misc", + ] + + sources = [ + "${bl_iot_sdk_root}/components/network/ble/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/atomic_c.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/buf.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/dec.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/log.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/poll.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/common/work_q.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/hci_onchip/hci_driver.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/att.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/bl_host_assist.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/conn.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/crypto.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/gatt.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/hci_core.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/l2cap.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/settings.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/host/uuid.c", + "${bl_iot_sdk_root}/components/network/ble/blestack/src/port/bl_port.c", + ] + + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_ble_config", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-unused-but-set-variable", + "-Wno-misleading-indentation", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-function", + "-Wno-incompatible-pointer-types", + "-Wno-discarded-qualifiers", + ] + } + + config("${sdk_target_name}_config_openthread_port") { + defines = [ "OT_FREERTOS_ENABLE=1" ] + if (thread_port_1_3) { + defines += [ "OT_THREAD_PORT_1_3" ] + } + + include_dirs = [ + "${chip_root}/platform/bl702", + "${chip_root}/third_party/openthread/repo/src/core", + "${chip_root}/third_party/openthread/repo/examples/platforms", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/include", + ] + + if (thread_port_1_3) { + include_dirs += [ + "${bl_iot_sdk_root}/components/network/thread/openthread_utils/include", + ] + } + } + + source_set("${sdk_target_name}_openthread") { + import("//build_overrides/openthread.gni") + + include_dirs = [ + "${bl_iot_sdk_root}/components/network/lmac154/include", + "${bl_iot_sdk_root}/components/network/thread/openthread_port", + "${openthread_root}/examples/platforms/utils/", + "${openthread_root}/examples", + ] + + sources = [ + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_alarm.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_diag.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_entropy.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_logging.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_misc.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_radio.c", + "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_settings.c", + ] + + libs = [ "${bl_iot_sdk_root}/components/network/lmac154/lib/liblmac154.a" ] + + if (thread_port_1_3) { + sources += [ "${bl_iot_sdk_root}/components/network/thread/openthread_port/ot_linkmetric.c" ] + libs += [ "${bl_iot_sdk_root}/components/network/thread/openthread_utils/lib/libopenthread_utils.a" ] + } + + configs += [ + ":${sdk_target_name}_config_BSP_Driver", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_hosal", + ":${sdk_target_name}_config_stage", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_openthread_port", + ] + + public_deps = [ + "${bouffalolab_iot_sdk_build_root}/bl702:mbedtls", + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + "${openthread_root}/src/core:libopenthread_core_headers", + ] + } + + config("${sdk_target_name}_config_lwip_port") { + _include_dirs = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/config", + "${bl_iot_sdk_root}/components/stage/virt_net/include", + "${bl_iot_sdk_root}/components/stage/throughput/bl702/inc", + ] + + defines = [ + "TCPIP_THREAD_PRIO=24", + "CFG_ETHERNET_ENABLE=1", + ] + + cflags = [] + foreach(include_dir, _include_dirs) { + cflags += [ "-isystem" + rebase_path(include_dir, root_build_dir) ] + } + + cflags += [ + "-Wno-conversion", + "-Wno-unused-function", + ] + } + + source_set("${sdk_target_name}_lwip_port") { + defines = [ + "SPI_WIFI_RXBUFF_IN_PSRAM=1", + "VIRT_NET_SPI_RX_TASK_PRIORITY=25", + ] + + # include_dirs = [ + # "${bl_iot_sdk_root}/components/network/lwip/lwip-port/arch", + # "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS", + # "${bl_iot_sdk_root}/components/stage/throughput" + # ] + + # sources = [ + # "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c", + # "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/sys_arch.c" + # ] + + # sources += [ + # "${bl_iot_sdk_root}/components/stage/throughput/bl702/src/tp_spi_master.c", + # ] + # sources += [ + # "${bl_iot_sdk_root}/components/stage/virt_net/src/virt_net.c", + # "${bl_iot_sdk_root}/components/stage/virt_net/src/virt_net_spi.c", + # ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lwip_port", + ":${sdk_target_name}_config_lwip", + ] + + cflags = [ "-Wno-sign-compare" ] + } + + config("${sdk_target_name}_config_lwip") { + include_dirs = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/config", + "${bl_iot_sdk_root}/components/network/lwip/src/include", + "${bl_iot_sdk_root}/components/network/lwip/src/include/lwip/apps", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/hook", + ] + + defines = [ + "LWIP_IPV6=1", + "LWIP_IPV4=1", + "LWIP_IPV6_DHCP6=1", + "LWIP_IPV6_SCOPES=0", + "PBUF_POOL_SIZE=20", + "PBUF_POOL_BUFSIZE=(1280+150)", + ] + } + + source_set("${sdk_target_name}_lwip") { + sources = [ + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/ethernetif.c", + "${bl_iot_sdk_root}/components/network/lwip/lwip-port/FreeRTOS/sys_arch.c", + ] + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/netif/bridgeif.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/bridgeif_fdb.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/ethernet.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/slipif.c", + "${bl_iot_sdk_root}/components/network/lwip/src/netif/zepif.c", + ] + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/core/def.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/dns.c", + "${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", + "${bl_iot_sdk_root}/components/network/lwip/src/core/raw.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/stats.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/sys.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp_in.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/tcp_out.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/timeouts.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/udp.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", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/etharp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/icmp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/igmp.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4_addr.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/ip4_frag.c", + ] + + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/dhcp6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ethip6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/icmp6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/inet6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_addr.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_frag.c", + + #"${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/ip6_route_table.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/mld6.c", + "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv6/nd6.c", + ] + + sources += [ + "${bl_iot_sdk_root}/components/network/lwip/src/api/api_lib.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/api_msg.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/err.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/if_api.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/netbuf.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/netifapi.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/sockets.c", + "${bl_iot_sdk_root}/components/network/lwip/src/api/tcpip.c", + ] + sources += + [ "${bl_iot_sdk_root}/components/network/lwip/src/apps/mdns/mdns.c" ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lwip", + ] + } + + group(sdk_target_name) { + public_deps = [ + ":${sdk_target_name}_BSP_Driver", + ":${sdk_target_name}_bl702_freertos", + ":${sdk_target_name}_ble", + ":${sdk_target_name}_fs", + ":${sdk_target_name}_hosal", + ":${sdk_target_name}_libc", + ":${sdk_target_name}_soc", + ":${sdk_target_name}_stage", + ":${sdk_target_name}_sys", + ":${sdk_target_name}_utils", + ] + + if (chip_enable_openthread) { + public_deps += [ ":${sdk_target_name}_openthread" ] + } + + if (chip_enable_wifi) { + public_deps += [ ":${sdk_target_name}_lwip_port" ] + public_deps += [ ":${sdk_target_name}_lwip" ] + } + + if (enable_cdc_module) { + public_deps += [ ":${sdk_target_name}_bl702_usb_cdc" ] + } + } +} diff --git a/third_party/bouffalolab/bl702/bl702_board.gni b/third_party/bouffalolab/common/bouffalolab_board.gni similarity index 78% rename from third_party/bouffalolab/bl702/bl702_board.gni rename to third_party/bouffalolab/common/bouffalolab_board.gni index 5aa17fd891eb73..c21e839dbfe372 100644 --- a/third_party/bouffalolab/bl702/bl702_board.gni +++ b/third_party/bouffalolab/common/bouffalolab_board.gni @@ -13,14 +13,13 @@ # limitations under the License. declare_args() { - # BL602 board used - bl702_board = "BL-IOT-DVK" + bouffalolab_bard = "BL-IOT-DVK" } -if (bl702_board == "") { - bl702_board = "BL-IOT-DVK" +if (bouffalolab_bard == "") { + bouffalolab_bard = "BL-IOT-DVK" } -assert(bl702_board != "", "bl702_board must be specified") +assert(bouffalolab_bard != "", "bouffalolab_bard must be specified") board_defines = [] diff --git a/third_party/bouffalolab/bl602/bl602_executable.gni b/third_party/bouffalolab/common/bouffalolab_executable.gni similarity index 81% rename from third_party/bouffalolab/bl602/bl602_executable.gni rename to third_party/bouffalolab/common/bouffalolab_executable.gni index 5c327b0f913540..54f4c031ee263c 100644 --- a/third_party/bouffalolab/bl602/bl602_executable.gni +++ b/third_party/bouffalolab/common/bouffalolab_executable.gni @@ -18,7 +18,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/bouffalolab_iot_sdk.gni") import("${build_root}/toolchain/flashable_executable.gni") -template("bl602_executable") { +template("bouffalolab_executable") { output_base_name = get_path_info(invoker.output_name, "name") objcopy_image_name = output_base_name + ".bin" @@ -40,9 +40,13 @@ template("bl602_executable") { "${chip_root}/scripts/flashing/bouffalolab_firmware_utils.py", "${chip_root}/scripts/flashing/firmware_utils.py", - "${chip_root}/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_2M.toml", - "${chip_root}/examples/platform/bouffalolab/bl602/flash_config/partition_cfg_4M.toml", + "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_2M.toml", ] + + if (invoker.bl_plat_name == "bl602") { + flashing_script_inputs += [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml" ] + } + copy(flashing_runtime_target) { sources = flashing_script_inputs outputs = [ "${root_out_dir}/{{source_file_part}}" ] @@ -53,12 +57,16 @@ template("bl602_executable") { flashing_script_name = output_base_name + ".flash.py" flashing_options = [ "bouffalolab" ] flashing_options += [ "--chipname" ] - flashing_options += [ "bl602" ] + flashing_options += [ "${invoker.bl_plat_name}" ] flashing_options += [ "--xtal" ] - flashing_options += [ "40M" ] - flashing_options += [ "--pt" ] + if (invoker.bl_plat_name == "bl602") { + flashing_options += [ "40M" ] + } else if (invoker.bl_plat_name == "bl702") { + flashing_options += [ "32M" ] + } - if (invoker.board == "BL602-IOT-DVK-3S") { + flashing_options += [ "--pt" ] + if (invoker.board == "BL602-IOT-DVK-3S" || invoker.bl_plat_name == "bl702") { flashing_options += [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] } else { diff --git a/third_party/bouffalolab/bl602/bl602_riscv.gni b/third_party/bouffalolab/common/rsicv.gni similarity index 96% rename from third_party/bouffalolab/bl602/bl602_riscv.gni rename to third_party/bouffalolab/common/rsicv.gni index 3c72c6fdf06fe9..dc75aaa22232d6 100644 --- a/third_party/bouffalolab/bl602/bl602_riscv.gni +++ b/third_party/bouffalolab/common/rsicv.gni @@ -12,8 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("bl602_board.gni") - riscv_arch = "rv32imfc" riscv_abi = "ilp32f" # riscv_cpu = "" diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo index ae0622d85476ed..abf04dcdc4ce5f 160000 --- a/third_party/bouffalolab/repo +++ b/third_party/bouffalolab/repo @@ -1 +1 @@ -Subproject commit ae0622d85476ed838ebc3efde9743c376bc9f96d +Subproject commit abf04dcdc4ce5f94c57b6150d6ba52a22b700880 From def892adb6194f18ffd6fc54417a01471b4bf980 Mon Sep 17 00:00:00 2001 From: pankore <86098180+pankore@users.noreply.github.com> Date: Thu, 5 Jan 2023 00:51:08 +0800 Subject: [PATCH 08/31] [Ameba] Add Macro to InitBindingHandler (#24186) --- examples/all-clusters-app/ameba/main/chipinterface.cpp | 2 ++ examples/light-switch-app/ameba/main/chipinterface.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/examples/all-clusters-app/ameba/main/chipinterface.cpp b/examples/all-clusters-app/ameba/main/chipinterface.cpp index ad92123d5795e7..e55666d1d6aee2 100644 --- a/examples/all-clusters-app/ameba/main/chipinterface.cpp +++ b/examples/all-clusters-app/ameba/main/chipinterface.cpp @@ -141,7 +141,9 @@ static void InitServer(intptr_t context) PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); } +#if CONFIG_ENABLE_CHIP_SHELL InitBindingHandler(); +#endif } extern "C" void ChipTest(void) diff --git a/examples/light-switch-app/ameba/main/chipinterface.cpp b/examples/light-switch-app/ameba/main/chipinterface.cpp index fcdf8b963fc7bc..24e32a72decf39 100644 --- a/examples/light-switch-app/ameba/main/chipinterface.cpp +++ b/examples/light-switch-app/ameba/main/chipinterface.cpp @@ -116,7 +116,9 @@ static void InitServer(intptr_t context) PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); } +#if CONFIG_ENABLE_CHIP_SHELL InitBindingHandler(); +#endif } extern "C" void ChipTest(void) From e3a3aaad583a5cb11ebf5856ca2b8912d72e347d Mon Sep 17 00:00:00 2001 From: Maciej Bojczuk Date: Wed, 4 Jan 2023 17:54:02 +0100 Subject: [PATCH 09/31] [Telink] Change factory data generator utility (#24213) * [Telink] Manufacturing Partition Generator Utility This tool can be used to generate factory data for more bunch of devices. Signed-off-by: Maciej Bojczuk * [Telink] Add additional python requirements MFG tool require some additional python modules like: * future * pypng * PyQRCode Signed-off-by: Maciej Bojczuk * [Telink] MFG tool integration with build system Use new tool for factory data generation during building when below config is set: CONFIG_CHIP_FACTORY_DATA=y CONFIG_CHIP_FACTORY_DATA_BUILD=y Signed-off-by: Maciej Bojczuk * [Telink] Remove old, not needed scripts Remove old, not needed python scripts for factory data generation. Signed-off-by: Maciej Bojczuk Signed-off-by: Maciej Bojczuk --- config/telink/chip-module/CMakeLists.txt | 2 +- .../chip-module/generate_factory_data.cmake | 159 ++-- scripts/requirements.telink.txt | 3 + scripts/requirements.txt | 3 + .../generate_telink_chip_factory_data.py | 493 ------------ scripts/tools/telink/mfg_tool.py | 755 ++++++++++++++++++ scripts/tools/telink/readme.md | 212 +++++ scripts/tools/telink/requirements.txt | 6 + .../tools/telink/telink_factory_data.schema | 164 ---- .../tools/telink/telink_generate_partition.py | 169 ---- 10 files changed, 1041 insertions(+), 925 deletions(-) create mode 100644 scripts/requirements.telink.txt delete mode 100644 scripts/tools/telink/generate_telink_chip_factory_data.py create mode 100644 scripts/tools/telink/mfg_tool.py create mode 100644 scripts/tools/telink/readme.md create mode 100644 scripts/tools/telink/requirements.txt delete mode 100644 scripts/tools/telink/telink_factory_data.schema delete mode 100644 scripts/tools/telink/telink_generate_partition.py diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 6113325da57f95..2328ef28c13893 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -327,7 +327,7 @@ endif() if (CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE) add_custom_target(merge_factory_data ALL COMMAND - dd if=${PROJECT_BINARY_DIR}/factory_data.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=2000 + dd if=${PROJECT_BINARY_DIR}/factory/factory_data.bin of=${PROJECT_BINARY_DIR}/zephyr.bin bs=1024 seek=2000 ) if (CONFIG_CHIP_OTA_IMAGE_BUILD) add_dependencies(merge_factory_data merge_mcuboot) diff --git a/config/telink/chip-module/generate_factory_data.cmake b/config/telink/chip-module/generate_factory_data.cmake index a1c9f0ef9780a0..6b7681defc8224 100644 --- a/config/telink/chip-module/generate_factory_data.cmake +++ b/config/telink/chip-module/generate_factory_data.cmake @@ -15,49 +15,63 @@ # -# Create a JSON file based on factory data given via kConfigs. +# Create a binary file with factory data given via kConfigs. # -# This function creates a list of arguments for external script and then run it to write a JSON file. -# Created JSON file can be checked using JSON SCHEMA file if it is provided. +# This function creates a list of arguments for external script and then run it to write a factory data file. # # This script can be manipulated using following kConfigs: # - To merge generated factory data with final zephyr.hex file set kConfig CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE=y # - To use default certification paths set CONFIG_CHIP_FACTORY_DATA_USE_DEFAULTS_CERTS_PATH=y # -# During generation process a some file will be created in zephyr's build directory: -# - .json a file containing all factory data written in JSON format. +# During generation process a some file will be created in zephyr's build directory under factory subdirectory: +# - factory_data.bin +# - factory_data.hex +# - DAC_cert.der +# - DAC_cert.pem +# - DAC_key.pem +# - DAC_private_key.bin +# - DAC_public_key.bin +# - pai_cert.der +# - onb_codes.csv +# - pin_disc.csv +# - qrcode.png +# - summary.json # # [Args]: # factory_data_target - a name for target to generate factory_data. # script_path - a path to script that makes a JSON factory data file from given arguments. -# schema_path - a path to JSON schema file which can be used to verify generated factory data JSON file. -# This argument is optional, if you don't want to verify the JSON file put it empty "". # output_path - a path to output directory, where created JSON file will be stored. -function(telink_create_factory_data_json factory_data_target script_path schema_path output_path) +function(telink_create_factory_data_json factory_data_target script_path output_path) # set script args for future purpose set(script_args) ## generate all script arguments -string(APPEND script_args "--sn \"${CONFIG_CHIP_DEVICE_SERIAL_NUMBER}\"\n") -string(APPEND script_args "--date \"${CONFIG_CHIP_DEVICE_MANUFACTURING_DATE}\"\n") -string(APPEND script_args "--vendor_id ${CONFIG_CHIP_DEVICE_VENDOR_ID}\n") -string(APPEND script_args "--product_id ${CONFIG_CHIP_DEVICE_PRODUCT_ID}\n") -string(APPEND script_args "--vendor_name \"${CONFIG_CHIP_DEVICE_VENDOR_NAME}\"\n") -string(APPEND script_args "--product_name \"${CONFIG_CHIP_DEVICE_PRODUCT_NAME}\"\n") -string(APPEND script_args "--hw_ver ${CONFIG_CHIP_DEVICE_HARDWARE_VERSION}\n") -string(APPEND script_args "--hw_ver_str \"${CONFIG_CHIP_DEVICE_HARDWARE_VERSION_STRING}\"\n") +string(APPEND script_args "--serial-num \"${CONFIG_CHIP_DEVICE_SERIAL_NUMBER}\"\n") +string(APPEND script_args "--mfg-date \"${CONFIG_CHIP_DEVICE_MANUFACTURING_DATE}\"\n") +string(APPEND script_args "--vendor-id ${CONFIG_CHIP_DEVICE_VENDOR_ID}\n") +string(APPEND script_args "--product-id ${CONFIG_CHIP_DEVICE_PRODUCT_ID}\n") +string(APPEND script_args "--vendor-name \"${CONFIG_CHIP_DEVICE_VENDOR_NAME}\"\n") +string(APPEND script_args "--product-name \"${CONFIG_CHIP_DEVICE_PRODUCT_NAME}\"\n") +string(APPEND script_args "--hw-ver ${CONFIG_CHIP_DEVICE_HARDWARE_VERSION}\n") +string(APPEND script_args "--hw-ver-str \"${CONFIG_CHIP_DEVICE_HARDWARE_VERSION_STRING}\"\n") +string(APPEND script_args "--overwrite\n") +string(APPEND script_args "--in-tree\n") # check if Rotating Device Id Unique Id should be generated if(NOT CONFIG_CHIP_DEVICE_GENERATE_ROTATING_DEVICE_UID) if(NOT DEFINED CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID) message(FATAL_ERROR "CHIP_DEVICE_ROTATING_DEVICE_UID was not provided. To generate it use CONFIG_CHIP_DEVICE_GENERATE_ROTATING_DEVICE_UID=y") else() - string(APPEND script_args "--rd_uid \"${CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID}\"\n") + string(APPEND script_args "--rd-id-uid \"${CONFIG_CHIP_DEVICE_ROTATING_DEVICE_UID}\"\n") endif() else() - string(APPEND script_args "--generate_rd_uid\n") + string(APPEND script_args "--enable-rotating-device-id\n") endif() +# find chip cert tool +find_program(chip_cert_exe NAMES chip-cert REQUIRED) +string(APPEND script_args "--chip-cert-path ${chip_cert_exe}\n") + # for development purpose user can use default certs instead of generating or providing them if(CONFIG_CHIP_FACTORY_DATA_USE_DEFAULT_CERTS) # convert decimal PID to its hexadecimal representation to find out certification files in repository @@ -66,99 +80,57 @@ if(CONFIG_CHIP_FACTORY_DATA_USE_DEFAULT_CERTS) string(TOUPPER ${raw_pid} raw_pid_upper) # all certs are located in ${CHIP_ROOT}/credentials/development/attestation # it can be used during development without need to generate new certifications - string(APPEND script_args "--dac_cert \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-DAC-${raw_pid_upper}-Cert.der\"\n") - string(APPEND script_args "--dac_key \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-DAC-${raw_pid_upper}-Key.der\"\n") - string(APPEND script_args "--pai_cert \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-PAI-noPID-Cert.der\"\n") + string(APPEND script_args "--dac-cert \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-DAC-${raw_pid_upper}-Cert.pem\"\n") + string(APPEND script_args "--dac-key \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-DAC-${raw_pid_upper}-Key.pem\"\n") + string(APPEND script_args "--cert \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-PAI-noPID-Cert.pem\"\n") + string(APPEND script_args "--key \"${CHIP_ROOT}/credentials/development/attestation/Matter-Development-PAI-noPID-Key.pem\"\n") + string(APPEND script_args "-cd \"${CHIP_ROOT}/credentials/development/cd-certs/Chip-Test-CD-Cert.der\"\n") + string(APPEND script_args "--pai\n") else() - find_program(chip_cert_exe NAMES chip-cert REQUIRED) - string(APPEND script_args "--gen_cd\n") - string(APPEND script_args "--chip_cert_path ${chip_cert_exe}\n") + # generate PAI and DAC certs + string(APPEND script_args "--cert \"${CHIP_ROOT}/credentials/test/attestation/Chip-Test-PAA-NoVID-Cert.pem\"\n") + string(APPEND script_args "--key \"${CHIP_ROOT}/credentials/test/attestation/Chip-Test-PAA-NoVID-Key.pem\"\n") + string(APPEND script_args "-cd \"${CHIP_ROOT}/credentials/development/cd-certs/Chip-Test-CD-Cert.der\"\n") + string(APPEND script_args "--paa\n") endif() +# find chip tool requied for generating QRCode +find_program(chip_tool_exe NAMES chip-tool REQUIRED) +string(APPEND script_args "--chip-tool-path ${chip_tool_exe}\n") + # add Password-Authenticated Key Exchange parameters -string(APPEND script_args "--spake2_it \"${CONFIG_CHIP_DEVICE_SPAKE2_IT}\"\n") -string(APPEND script_args "--spake2_salt \"${CONFIG_CHIP_DEVICE_SPAKE2_SALT}\"\n") +string(APPEND script_args "--spake2-it \"${CONFIG_CHIP_DEVICE_SPAKE2_IT}\"\n") string(APPEND script_args "--discriminator ${CONFIG_CHIP_DEVICE_DISCRIMINATOR}\n") string(APPEND script_args "--passcode ${CONFIG_CHIP_DEVICE_SPAKE2_PASSCODE}\n") -string(APPEND script_args "--include_passcode\n") -string(APPEND script_args "--overwrite\n") -# check if spake2 verifier should be generated using script -if(CONFIG_CHIP_FACTORY_DATA_GENERATE_SPAKE2_VERIFIER) - # request script to generate a new spake2_verifier - # by adding an argument to script_args - find_program(spake_exe NAMES spake2p REQUIRED) - string(APPEND script_args "--spake2p_path ${spake_exe}\n") -else() - # Spake2 verifier should be provided using kConfig - string(APPEND script_args "--spake2_verifier \"${CONFIG_CHIP_DEVICE_SPAKE2_TEST_VERIFIER}\"\n") -endif() +# request spake2p to generate a new spake2_verifier +find_program(spake_exe NAMES spake2p REQUIRED) +string(APPEND script_args "--spake2-path ${spake_exe}\n") if(CONFIG_CHIP_DEVICE_ENABLE_KEY) # Add optional EnableKey that triggers user-specific action. -string(APPEND script_args "--enable_key \"${CONFIG_CHIP_DEVICE_ENABLE_KEY}\"\n") +string(APPEND script_args "--enable-key \"${CONFIG_CHIP_DEVICE_ENABLE_KEY}\"\n") endif() -# Set output JSON file and path to SCHEMA file to validate generated factory data -set(factory_data_json ${output_path}/${factory_data_target}.json) -string(APPEND script_args "-o \"${factory_data_json}\"\n") -string(APPEND script_args "-s \"${schema_path}\"\n") +string(APPEND script_args "--output \"${output_path}\"/factory\n") + +set(factory_data_bin ${output_path}/factory/factory_data.bin) -# execute first script to create a JSON file +# execute a script to create a factory data file separate_arguments(separated_script_args NATIVE_COMMAND ${script_args}) add_custom_command( - OUTPUT ${factory_data_json} + OUTPUT ${factory_data_bin} DEPENDS ${FACTORY_DATA_SCRIPT_PATH} COMMAND ${Python3_EXECUTABLE} ${FACTORY_DATA_SCRIPT_PATH} ${separated_script_args} COMMENT "Generating new Factory Data..." ) add_custom_target(${factory_data_target} ALL - DEPENDS ${factory_data_json} + DEPENDS ${factory_data_bin} ) endfunction() -# Create a .hex file with factory data in CBOR format. -# -# This function creates a .hex and .cbor files from given JSON factory data file. -# -# -# During generation process some files will be created in zephyr's build directory: -# - .hex a file containing all factory data in CBOR format. -# - .bin a binary file containing all raw factory data in CBOR format. -# - .cbor a file containing all factory data in CBOR format. -# -# [Args]: -# factory_data_hex_target - a name for target to generate factory data HEX file. -# factory_data_target - a name for target to generate factory data JSON file. -# script_path - a path to script that makes a factory data .hex file from given arguments. -# output_path - a path to output directory, where created JSON file will be stored. -function(telink_create_factory_data_hex_file factory_data_hex_target factory_data_target script_path output_path) - -# Pass the argument list via file -set(cbor_script_args "-i ${output_path}/${factory_data_target}.json\n") -string(APPEND cbor_script_args "-o ${output_path}/${factory_data_target}\n") -# get partition address and offset from partition manager during compilation -string(APPEND cbor_script_args "--offset 0x1f4000\n") -string(APPEND cbor_script_args "--size 0x1000\n") -string(APPEND cbor_script_args "-r\n") - -# execute second script to create a hex file containing factory data in cbor format -separate_arguments(separated_cbor_script_args NATIVE_COMMAND ${cbor_script_args}) -set(factory_data_hex ${output_path}/${factory_data_target}.hex) - -add_custom_command(OUTPUT ${factory_data_hex} - COMMAND ${Python3_EXECUTABLE} ${script_path} ${separated_cbor_script_args} - COMMENT "Generating factory data HEX file..." - DEPENDS ${factory_data_target} ${script_path} - ) -add_custom_target(${factory_data_hex_target} ALL - DEPENDS ${factory_data_hex} - ) - -endfunction() - # Generate factory data partition using given args # # @@ -176,21 +148,12 @@ message(FATAL_ERROR "CHIP_ROOT variable is not set, please add it to CMakeLists. endif() # Localize all scripts needed to generate factory data partition -set(FACTORY_DATA_SCRIPT_PATH ${CHIP_ROOT}/scripts/tools/telink/generate_telink_chip_factory_data.py) -set(GENERATE_CBOR_SCRIPT_PATH ${CHIP_ROOT}/scripts/tools/telink/telink_generate_partition.py) -set(FACTORY_DATA_SCHEMA_PATH ${CHIP_ROOT}/scripts/tools/telink/telink_factory_data.schema) +set(FACTORY_DATA_SCRIPT_PATH ${CHIP_ROOT}/scripts/tools/telink/mfg_tool.py) set(OUTPUT_FILE_PATH ${APPLICATION_BINARY_DIR}/zephyr) -# create a JSON file with all factory data +# create a binary file with all factory data telink_create_factory_data_json(factory_data - ${FACTORY_DATA_SCRIPT_PATH} - ${FACTORY_DATA_SCHEMA_PATH} + ${FACTORY_DATA_SCRIPT_PATH} ${OUTPUT_FILE_PATH}) -# create a .hex file with factory data in CBOR format based on the JSON file created previously -telink_create_factory_data_hex_file(factory_data_hex - factory_data - ${GENERATE_CBOR_SCRIPT_PATH} - ${OUTPUT_FILE_PATH}) - endfunction() diff --git a/scripts/requirements.telink.txt b/scripts/requirements.telink.txt new file mode 100644 index 00000000000000..7d2093551af69c --- /dev/null +++ b/scripts/requirements.telink.txt @@ -0,0 +1,3 @@ +future==0.18.2 +pypng==0.0.21 +PyQRCode==1.2.1 diff --git a/scripts/requirements.txt b/scripts/requirements.txt index 6fec358caf1986..b39ec86833bf6e 100644 --- a/scripts/requirements.txt +++ b/scripts/requirements.txt @@ -20,6 +20,9 @@ virtualenv # TI -r requirements.ti.txt +# Telink +-r requirements.telink.txt + # cirque tests requests>=2.24.0 diff --git a/scripts/tools/telink/generate_telink_chip_factory_data.py b/scripts/tools/telink/generate_telink_chip_factory_data.py deleted file mode 100644 index 7605184700461a..00000000000000 --- a/scripts/tools/telink/generate_telink_chip_factory_data.py +++ /dev/null @@ -1,493 +0,0 @@ -#!/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. -# - -from os.path import exists -import os -import sys -import json -import jsonschema -import secrets -import argparse -import subprocess -import logging as log -import base64 -from collections import namedtuple -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives.serialization import load_der_private_key - -# A user can not change the factory data version and must be coherent with -# the factory data version set in the Telink platform Kconfig file (CHIP_FACTORY_DATA_VERSION). -FACTORY_DATA_VERSION = 1 - -MATTER_ROOT = os.path.dirname(os.path.realpath(__file__))[:-len("/scripts/tools/telink")] -HEX_PREFIX = "hex:" -PUB_KEY_PREFIX = b'\x04' -INVALID_PASSCODES = [00000000, 11111111, 22222222, 33333333, 44444444, - 55555555, 66666666, 77777777, 88888888, 99999999, 12345678, 87654321] - - -def get_raw_private_key_der(der_file: str, password: str): - """ Split given der file to get separated key pair consisting of public and private keys. - - Args: - der_file (str): Path to .der file containing public and private keys - password (str): Password to decrypt Keys. It can be None, and then KEY is not encrypted. - - Returns: - hex string: return a hex string containing extracted and decrypted private KEY from given .der file. - """ - try: - with open(der_file, 'rb') as file: - key_data = file.read() - if password is None: - log.warning("KEY password has not been provided. It means that DAC key is not encrypted.") - keys = load_der_private_key(key_data, password, backend=default_backend()) - private_key = keys.private_numbers().private_value.to_bytes(32, byteorder='big') - - return private_key - - except IOError or ValueError: - return None - - -def gen_test_certs(chip_cert_exe: str, - output: str, - vendor_id: int, - product_id: int, - device_name: str, - generate_cd: bool = False, - cd_type: int = 1, - paa_cert_path: str = None, - paa_key_path: str = None): - """ - Generate Matter certificates according to given Vendor ID and Product ID using the chip-cert executable. - To use own Product Attestation Authority certificate provide paa_cert_path and paa_key_path arguments. - Without providing these arguments a PAA certificate will be get from /credentials/test/attestation directory - in the Matter repository. - - Args: - chip_cert_exe (str): path to chip-cert executable - output (str): output path to store a newly generated certificates (CD, DAC, PAI) - vendor_id (int): an identification number specific to Vendor - product_id (int): an identification number specific to Product - device_name (str): human-readable device name - generate_cd (bool, optional): Generate Certificate Declaration and store it in thee output directory. Defaults to False. - paa_cert_path (str, optional): provide PAA certification path. Defaults to None - a path will be set to /credentials/test/attestation directory. - paa_key_path (str, optional): provide PAA key path. Defaults to None - a path will be set to /credentials/test/attestation directory. - - Returns: - dictionary: ["PAI_CERT": (str), - "DAC_CERT": (str), - "DAC_KEY": (str)] - """ - - CD_PATH = MATTER_ROOT + "/credentials/test/certification-declaration/Chip-Test-CD-Signing-Cert.pem" - CD_KEY_PATH = MATTER_ROOT + "/credentials/test/certification-declaration/Chip-Test-CD-Signing-Key.pem" - PAA_PATH = paa_cert_path if paa_cert_path != None else MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAA-NoVID-Cert.pem" - PAA_KEY_PATH = paa_key_path if paa_key_path != None else MATTER_ROOT + "/credentials/test/attestation/Chip-Test-PAA-NoVID-Key.pem" - - attestation_certs = namedtuple("attestation_certs", ["dac_cert", "dac_key", "pai_cert"]) - - log.info("Generating new certificates using chip-cert...") - - if generate_cd: - # generate Certification Declaration - cmd = [chip_cert_exe, "gen-cd", - "--key", CD_KEY_PATH, - "--cert", CD_PATH, - "--out", output + "/CD.der", - "--format-version", "1", - "--vendor-id", hex(vendor_id), - "--product-id", hex(product_id), - "--device-type-id", "0", - "--certificate-id", "FFFFFFFFFFFFFFFFFFF", - "--security-level", "0", - "--security-info", "0", - "--certification-type", str(cd_type), - "--version-number", "0xFFFF", - ] - subprocess.run(cmd) - - new_certificates = {"PAI_CERT": output + "/PAI_cert", - "PAI_KEY": output + "/PAI_key", - "DAC_CERT": output + "/DAC_cert", - "DAC_KEY": output + "/DAC_key" - } - - # generate PAI - cmd = [chip_cert_exe, "gen-att-cert", - "-t", "i", - "-c", device_name, - "-V", hex(vendor_id), - "-C", PAA_PATH, - "-K", PAA_KEY_PATH, - "-o", new_certificates["PAI_CERT"] + ".pem", - "-O", new_certificates["PAI_KEY"] + ".pem", - "-l", str(10000), - ] - subprocess.run(cmd) - - # generate DAC - cmd = [chip_cert_exe, "gen-att-cert", - "-t", "d", - "-c", device_name, - "-V", hex(vendor_id), - "-P", hex(product_id), - "-C", new_certificates["PAI_CERT"] + ".pem", - "-K", new_certificates["PAI_KEY"] + ".pem", - "-o", new_certificates["DAC_CERT"] + ".pem", - "-O", new_certificates["DAC_KEY"] + ".pem", - "-l", str(10000), - ] - subprocess.run(cmd) - - # convert to .der files - for cert_k, cert_v in new_certificates.items(): - action_type = "convert-cert" if cert_k.find("CERT") != -1 else "convert-key" - log.info(cert_v + ".der") - cmd = [chip_cert_exe, action_type, - cert_v + ".pem", - cert_v + ".der", - "--x509-der", - ] - subprocess.run(cmd) - - return attestation_certs(new_certificates["DAC_CERT"] + ".der", - new_certificates["DAC_KEY"] + ".der", - new_certificates["PAI_CERT"] + ".der") - - -def gen_spake2p_verifier(passcode: int, it: int, salt: bytes) -> str: - """ Generate Spake2+ verifier using SPAKE2+ Python Tool - - Args: - passcode (int): Pairing passcode using in Spake2+ - it (int): Iteration counter for Spake2+ verifier generation - salt (str): Salt used to generate Spake2+ verifier - - Returns: - verifier encoded in Base64 - """ - - cmd = [ - os.path.join(MATTER_ROOT, 'scripts/tools/spake2p/spake2p.py'), 'gen-verifier', - '--passcode', str(passcode), - '--salt', base64.b64encode(salt).decode('ascii'), - '--iteration-count', str(it), - ] - return subprocess.check_output(cmd) - - -class FactoryDataGenerator: - """ - Class to generate factory data from given arguments and generate a JSON file - - """ - - def __init__(self, arguments) -> None: - """ - Args: - arguments (any):All input arguments parsed using ArgParse - """ - self._args = arguments - self._factory_data = list() - self._user_data = dict() - - try: - self._validate_args() - except AssertionError as e: - log.error(e) - sys.exit(-1) - - def _validate_args(self): - if self._args.user: - try: - self._user_data = json.loads(self._args.user) - except json.decoder.JSONDecodeError as e: - raise AssertionError("Provided wrong user data, this is not a JSON format! {}".format(e)) - assert self._args.spake2_verifier or self._args.passcode, \ - "Cannot find Spake2+ verifier, to generate a new one please provide passcode (--passcode)" - assert (self._args.chip_cert_path or (self._args.dac_cert and self._args.pai_cert and self._args.dac_key)), \ - "Cannot find paths to DAC or PAI certificates .der files. To generate a new ones please provide a path to chip-cert executable (--chip_cert_path)" - assert self._args.output.endswith(".json"), \ - "Output path doesn't contain .json file path. ({})".format(self._args.output) - assert not (self._args.passcode in INVALID_PASSCODES), \ - "Provided invalid passcode!" - - def generate_json(self): - """ - This function generates JSON data, .json file and validates it. - - To validate generated JSON data a scheme must be provided within script's arguments. - - - In the first part, if the rotating device id unique id has been not provided - as an argument, it will be created. - - If user-provided passcode and Spake2+ verifier have been not provided - as an argument, it will be created using an external script - - Passcode is not stored in JSON by default. To store it for debugging purposes, add --include_passcode argument. - - Validating output JSON is not mandatory, but highly recommended. - - """ - # generate missing data if needed - if not self._args.rd_uid: - if self._args.generate_rd_uid: - rd_uid = self._generate_rotating_device_uid() - else: - # rotating device ID unique ID was not provided, so do not store it in factory data. - rd_uid = None - else: - rd_uid = HEX_PREFIX + self._args.rd_uid - - if not self._args.spake2_verifier: - spake_2_verifier = self._generate_spake2_verifier() - else: - spake_2_verifier = self._args.spake2_verifier - - # convert salt to bytestring to be coherent with Spake2+ verifier type - spake_2_salt = self._args.spake2_salt - - if self._args.chip_cert_path: - certs = gen_test_certs(self._args.chip_cert_path, - self._args.output[:self._args.output.rfind("/")], - self._args.vendor_id, - self._args.product_id, - self._args.vendor_name + "_" + self._args.product_name, - self._args.gen_cd, - self._args.cd_type, - self._args.paa_cert, - self._args.paa_key) - dac_cert = certs.dac_cert - pai_cert = certs.pai_cert - dac_key = certs.dac_key - else: - dac_cert = self._args.dac_cert - dac_key = self._args.dac_key - pai_cert = self._args.pai_cert - - # try to read DAC public and private keys - dac_priv_key = get_raw_private_key_der(dac_key, self._args.dac_key_password) - if dac_priv_key is None: - log.error("Cannot read DAC keys from : {}".format(dac_key)) - sys.exit(-1) - - try: - json_file = open(self._args.output, "w+") - except FileNotFoundError: - print("Cannot create JSON file in this location: {}".format(self._args.output)) - sys.exit(-1) - with json_file: - # serialize data - self._add_entry("version", FACTORY_DATA_VERSION) - self._add_entry("sn", self._args.sn) - self._add_entry("vendor_id", self._args.vendor_id) - self._add_entry("product_id", self._args.product_id) - self._add_entry("vendor_name", self._args.vendor_name) - self._add_entry("product_name", self._args.product_name) - self._add_entry("product_label", self._args.product_label) - self._add_entry("product_url", self._args.product_url) - self._add_entry("part_number", self._args.part_number) - self._add_entry("date", self._args.date) - self._add_entry("hw_ver", self._args.hw_ver) - self._add_entry("hw_ver_str", self._args.hw_ver_str) - self._add_entry("dac_cert", self._process_der(dac_cert)) - self._add_entry("dac_key", dac_priv_key) - self._add_entry("pai_cert", self._process_der(pai_cert)) - if self._args.include_passcode: - self._add_entry("passcode", self._args.passcode) - self._add_entry("spake2_it", self._args.spake2_it) - self._add_entry("spake2_salt", spake_2_salt) - self._add_entry("spake2_verifier", spake_2_verifier) - self._add_entry("discriminator", self._args.discriminator) - if rd_uid: - self._add_entry("rd_uid", rd_uid) - if self._args.enable_key: - self._add_entry("enable_key", HEX_PREFIX + self._args.enable_key) - if self._args.user: - self._add_entry("user", self._args.user) - - factory_data_dict = dict(self._factory_data) - - json_object = json.dumps(factory_data_dict) - is_json_valid = True - - if self._args.schema: - is_json_valid = self._validate_output_json(json_object) - else: - log.warning("JSON Schema file has not been provided, the output file can be wrong. Be aware of that.") - try: - if is_json_valid: - json_file.write(json_object) - except IOError as e: - log.error("Cannot save output file into directory: {}".format(self._args.output)) - - def _add_entry(self, name: str, value: any): - """ Add single entry to list of tuples ("key", "value") """ - if(isinstance(value, bytes) or isinstance(value, bytearray)): - value = HEX_PREFIX + value.hex() - if value or (isinstance(value, int) and value == 0): - log.debug("Adding entry '{}' with size {} and type {}".format(name, sys.getsizeof(value), type(value))) - self._factory_data.append((name, value)) - - def _generate_spake2_verifier(self): - """ If verifier has not been provided in arguments list it should be generated via external script """ - return base64.b64decode(gen_spake2p_verifier(self._args.passcode, self._args.spake2_it, self._args.spake2_salt)) - - def _generate_rotating_device_uid(self): - """ If rotating device unique ID has not been provided it should be generated """ - log.warning("Cannot find rotating device UID in provided arguments list. A new one will be generated.") - rdu = secrets.token_bytes(16) - log.info("\n\nThe new rotate device UID: {}\n".format(rdu.hex())) - return rdu - - def _validate_output_json(self, output_json: str): - """ - Validate output JSON data with provided .scheme file - This function will raise error if JSON does not match schema. - - """ - try: - with open(self._args.schema) as schema_file: - log.info("Validating JSON with schema...") - schema = json.loads(schema_file.read()) - validator = jsonschema.Draft202012Validator(schema=schema) - validator.validate(instance=json.loads(output_json)) - except IOError as e: - log.error("Provided JSON schema file is wrong: {}".format(self._args.schema)) - return False - else: - log.info("Validate OK") - return True - - def _process_der(self, path: str): - log.debug("Processing der file...") - try: - with open(path, 'rb') as f: - data = f.read() - return data - except IOError as e: - log.error(e) - raise e - - -def main(): - parser = argparse.ArgumentParser(description="Telink Factory Data NVS generator tool") - - def allow_any_int(i): return int(i, 0) - def base64_str(s): return base64.b64decode(s) - - mandatory_arguments = parser.add_argument_group("Mandatory keys", "These arguments must be provided to generate JSON file") - optional_arguments = parser.add_argument_group( - "Optional keys", "These arguments are optional and they depend on the user-purpose") - parser.add_argument("-s", "--schema", type=str, - help="JSON schema file to validate JSON output data") - parser.add_argument("-o", "--output", type=str, required=True, - help="Output path to store .json file, e.g. my_dir/output.json") - parser.add_argument("-v", "--verbose", action="store_true", - help="Run this script with DEBUG logging level") - parser.add_argument("--include_passcode", action="store_true", - help="Include passcode in factory data. By default, it is used only for generating Spake2+ verifier.") - parser.add_argument("--overwrite", action="store_true", - help="If output JSON file exist this argument allows to generate new factory data and overwrite it.") - # Json known-keys values - # mandatory keys - mandatory_arguments.add_argument("--sn", type=str, required=True, - help="[ascii string] Serial number of a device which can be used to identify \ - the serial number field in the Matter certificate structure. \ - Maximum length of serial number is 20 bytes. \ - Strings longer than 20 bytes will be declined in script") - mandatory_arguments.add_argument("--vendor_id", type=allow_any_int, - help="[int | hex int] Provide Vendor Identification Number") - mandatory_arguments.add_argument("--product_id", type=allow_any_int, - help="[int | hex int] Provide Product Identification Number") - mandatory_arguments.add_argument("--vendor_name", type=str, - help="[string] provide human-readable vendor name") - mandatory_arguments.add_argument("--product_name", type=str, - help="[string] provide human-readable product name") - mandatory_arguments.add_argument("--date", type=str, required=True, - help="[ascii string] Provide manufacturing date \ - A manufacturing date specifies the date that the Node was manufactured. \ - Used format for providing a manufacturing date is ISO 8601 e.g. YYYY-MM-DD.") - mandatory_arguments.add_argument("--hw_ver", type=allow_any_int, required=True, - help="[int | hex int] Provide hardware version in int format.") - mandatory_arguments.add_argument("--hw_ver_str", type=str, required=True, - help="[ascii string] Provide hardware version in string format.") - mandatory_arguments.add_argument("--spake2_it", type=allow_any_int, required=True, - help="[int | hex int] Provide Spake2+ iteration count.") - mandatory_arguments.add_argument("--spake2_salt", type=base64_str, required=True, - help="[base64 string] Provide Spake2+ salt.") - mandatory_arguments.add_argument("--discriminator", type=allow_any_int, required=True, - help="[int] Provide BLE pairing discriminator. \ - A 12-bit value matching the field of the same name in \ - the setup code. Discriminator is used during a discovery process.") - - # optional keys - optional_arguments.add_argument("--product_url", type=str, - help="[string] provide link to product-specific web page") - optional_arguments.add_argument("--product_label", type=str, - help="[string] provide human-readable product label") - optional_arguments.add_argument("--part_number", type=str, - help="[string] provide human-readable product number") - optional_arguments.add_argument("--chip_cert_path", type=str, - help="Generate DAC and PAI certificates instead giving a path to .der files. This option requires a path to chip-cert executable." - "By default you can find chip-cert in connectedhomeip/src/tools/chip-cert directory and build it there.") - optional_arguments.add_argument("--dac_cert", type=str, - help="[.der] Provide the path to .der file containing DAC certificate.") - optional_arguments.add_argument("--dac_key", type=str, - help="[.der] Provide the path to .der file containing DAC keys.") - optional_arguments.add_argument("--generate_rd_uid", action="store_true", - help="Generate a new rotating device unique ID, print it out to console output and store it in factory data.") - optional_arguments.add_argument("--dac_key_password", type=str, - help="Provide a password to decode dac key. If dac key is not encrypted do not provide this argument.") - optional_arguments.add_argument("--pai_cert", type=str, - help="[.der] Provide the path to .der file containing PAI certificate.") - optional_arguments.add_argument("--rd_uid", type=str, - help="[hex string] [128-bit hex-encoded] Provide the rotating device unique ID. If this argument is not provided a new rotating device id unique id will be generated.") - optional_arguments.add_argument("--passcode", type=allow_any_int, - help="[int | hex] Default PASE session passcode. (This is mandatory to generate Spake2+ verifier).") - optional_arguments.add_argument("--spake2_verifier", type=base64_str, - help="[base64 string] Provide Spake2+ verifier without generating it.") - optional_arguments.add_argument("--enable_key", type=str, - help="[hex string] [128-bit hex-encoded] The Enable Key is a 128-bit value that triggers manufacturer-specific action while invoking the TestEventTrigger Command." - "This value is used during Certification Tests, and should not be present on production devices.") - optional_arguments.add_argument("--user", type=str, - help="[string] Provide additional user-specific keys in JSON format: {'name_1': 'value_1', 'name_2': 'value_2', ... 'name_n', 'value_n'}.") - optional_arguments.add_argument("--gen_cd", action="store_true", default=False, - help="Generate a new Certificate Declaration in .der format according to used Vendor ID and Product ID. This certificate will not be included to the factory data.") - optional_arguments.add_argument("--cd_type", type=int, default=1, - help="[int] Type of generated Certification Declaration: 0 - development, 1 - provisional, 2 - official") - optional_arguments.add_argument("--paa_cert", type=str, - help="Provide a path to the Product Attestation Authority (PAA) certificate to generate the PAI certificate. Without providing it, a testing PAA stored in the Matter repository will be used.") - optional_arguments.add_argument("--paa_key", type=str, - help="Provide a path to the Product Attestation Authority (PAA) key to generate the PAI certificate. Without providing it, a testing PAA key stored in the Matter repository will be used.") - args = parser.parse_args() - - if args.verbose: - log.basicConfig(format='[%(asctime)s][%(levelname)s] %(message)s', level=log.DEBUG) - else: - log.basicConfig(format='[%(levelname)s] %(message)s', level=log.INFO) - - # check if json file already exist - if(exists(args.output) and not args.overwrite): - log.error("Output file: {} already exist, to create a new one add argument '--overwrite'. By default overwriting is disabled".format(args.output)) - return - - generator = FactoryDataGenerator(args) - generator.generate_json() - - -if __name__ == "__main__": - main() diff --git a/scripts/tools/telink/mfg_tool.py b/scripts/tools/telink/mfg_tool.py new file mode 100644 index 00000000000000..2c4390c0d0eed3 --- /dev/null +++ b/scripts/tools/telink/mfg_tool.py @@ -0,0 +1,755 @@ +#!/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 csv +import json +import os +import random +import shutil +import subprocess +import logging as logger +import sys +import cryptography.hazmat.backends +import cryptography.x509 +import pyqrcode +import cbor2 as cbor +from intelhex import IntelHex + +TOOLS = { + 'spake2p': None, + 'chip-cert': None, + 'chip-tool': None, +} + +INVALID_PASSCODES = [00000000, 11111111, 22222222, 33333333, 44444444, 55555555, + 66666666, 77777777, 88888888, 99999999, 12345678, 87654321] + +FACTORY_DATA_VERSION = 1 +SERIAL_NUMBER_LEN = 32 + +# Lengths for manual pairing codes and qrcode +SHORT_MANUALCODE_LEN = 11 +LONG_MANUALCODE_LEN = 21 +QRCODE_LEN = 22 +ROTATING_DEVICE_ID_UNIQUE_ID_LEN_BITS = 128 +HEX_PREFIX = "hex:" +DEV_SN_CSV_HDR = "Serial Number,\n" + +NVS_MEMORY = dict() + + +def nvs_memory_append(key, value): + if isinstance(value, str): + NVS_MEMORY[key] = value.encode("utf-8") + else: + NVS_MEMORY[key] = value + + +def nvs_memory_update(key, value): + if isinstance(value, str): + NVS_MEMORY.update({key: value.encode("utf-8")}) + else: + NVS_MEMORY.update({key: value}) + + +def check_tools_exists(args): + if args.spake2_path: + TOOLS['spake2p'] = shutil.which(args.spake2_path) + else: + TOOLS['spake2p'] = shutil.which('spake2p') + + if TOOLS['spake2p'] is None: + logger.error('spake2p not found, please specify --spake2-path argument') + sys.exit(1) + # if the certs and keys are not in the generated partitions or the specific dac cert and key are used, + # the chip-cert is not needed. + if args.paa or (args.pai and (args.dac_cert is None and args.dac_key is None)): + if args.chip_cert_path: + TOOLS['chip-cert'] = shutil.which(args.chip_cert_path) + else: + TOOLS['chip-cert'] = shutil.which('chip-cert') + if TOOLS['chip-cert'] is None: + logger.error('chip-cert not found, please specify --chip-cert-path argument') + sys.exit(1) + + if args.chip_tool_path: + TOOLS['chip-tool'] = shutil.which(args.chip_tool_path) + else: + TOOLS['chip-tool'] = shutil.which('chip-tool') + if TOOLS['chip-tool'] is None: + logger.error('chip-tool not found, please specify --chip-tool-path argument') + sys.exit(1) + + logger.debug('Using following tools:') + logger.debug('spake2p: {}'.format(TOOLS['spake2p'])) + logger.debug('chip-cert: {}'.format(TOOLS['chip-cert'])) + logger.debug('chip-tool: {}'.format(TOOLS['chip-tool'])) + + +def execute_cmd(cmd): + logger.debug('Executing Command: {}'.format(cmd)) + status = subprocess.run(cmd, capture_output=True) + + try: + status.check_returncode() + except subprocess.CalledProcessError as e: + if status.stderr: + logger.error('[stderr]: {}'.format(status.stderr.decode('utf-8').strip())) + logger.error('Command failed with error: {}'.format(e)) + sys.exit(1) + + +def check_str_range(s, min_len, max_len, name): + if s and ((len(s) < min_len) or (len(s) > max_len)): + logger.error('%s must be between %d and %d characters', name, min_len, max_len) + sys.exit(1) + + +def check_int_range(value, min_value, max_value, name): + if value and ((value < min_value) or (value > max_value)): + logger.error('%s is out of range, should be in range [%d, %d]', name, min_value, max_value) + sys.exit(1) + + +def vid_pid_str(vid, pid): + return '_'.join([hex(vid)[2:], hex(pid)[2:]]) + + +def read_der_file(path: str): + logger.debug("Reading der file {}...", path) + try: + with open(path, 'rb') as f: + data = f.read() + return data + except IOError as e: + logger.error(e) + raise e + + +def read_key_bin_file(path: str): + try: + with open(path, 'rb') as file: + key_data = file.read() + + return key_data + + except IOError or ValueError: + return None + + +def setup_out_dir(out_dir_top, args, serial: str): + out_dir = os.sep.join([out_dir_top, vid_pid_str(args.vendor_id, args.product_id)]) + + if args.in_tree: + out_dir = out_dir_top + + os.makedirs(out_dir, exist_ok=True) + + dirs = { + 'output': os.sep.join([out_dir, serial]), + 'internal': os.sep.join([out_dir, serial, 'internal']), + } + + if args.in_tree: + dirs['output'] = out_dir + dirs['internal'] = os.sep.join([out_dir, 'internal']) + + os.makedirs(dirs['output'], exist_ok=True) + os.makedirs(dirs['internal'], exist_ok=True) + + return dirs + + +def convert_x509_cert_from_pem_to_der(pem_file, out_der_file): + with open(pem_file, 'rb') as f: + pem_data = f.read() + + pem_cert = cryptography.x509.load_pem_x509_certificate(pem_data, cryptography.hazmat.backends.default_backend()) + der_cert = pem_cert.public_bytes(cryptography.hazmat.primitives.serialization.Encoding.DER) + + with open(out_der_file, 'wb') as f: + f.write(der_cert) + + +def generate_passcode(args, out_dirs): + salt_len_max = 32 + + cmd = [ + TOOLS['spake2p'], 'gen-verifier', + '--iteration-count', str(args.spake2_it), + '--salt-len', str(salt_len_max), + '--out', os.sep.join([out_dirs['output'], 'pin.csv']) + ] + + # If passcode is provided, use it + if (args.passcode): + cmd.extend(['--pin-code', str(args.passcode)]) + + execute_cmd(cmd) + + +def generate_discriminator(args, out_dirs): + # If discriminator is provided, use it + if args.discriminator: + disc = args.discriminator + else: + disc = random.randint(0x0000, 0x0FFF) + # Append discriminator to each line of the passcode file + with open(os.sep.join([out_dirs['output'], 'pin.csv']), 'r') as fd: + lines = fd.readlines() + + lines[0] = ','.join([lines[0].strip(), 'Discriminator']) + for i in range(1, len(lines)): + lines[i] = ','.join([lines[i].strip(), str(disc)]) + + with open(os.sep.join([out_dirs['output'], 'pin_disc.csv']), 'w') as fd: + fd.write('\n'.join(lines) + '\n') + + os.remove(os.sep.join([out_dirs['output'], 'pin.csv'])) + + +def generate_pai_certs(args, ca_key, ca_cert, out_key, out_cert): + cmd = [ + TOOLS['chip-cert'], 'gen-att-cert', + '--type', 'i', + '--subject-cn', '"{} PAI {}"'.format(args.cn_prefix, '00'), + '--out-key', out_key, + '--out', out_cert, + ] + + if args.lifetime: + cmd.extend(['--lifetime', str(args.lifetime)]) + if args.valid_from: + cmd.extend(['--valid-from', str(args.valid_from)]) + + cmd.extend([ + '--subject-vid', hex(args.vendor_id)[2:], + '--subject-pid', hex(args.product_id)[2:], + '--ca-key', ca_key, + '--ca-cert', ca_cert, + ]) + + execute_cmd(cmd) + logger.info('Generated PAI certificate: {}'.format(out_cert)) + logger.info('Generated PAI private key: {}'.format(out_key)) + + +def setup_root_certificates(args, dirs): + pai_cert = { + 'cert_pem': None, + 'cert_der': None, + 'key_pem': None, + } + # If PAA is passed as input, then generate PAI certificate + if args.paa: + # output file names + pai_cert['cert_pem'] = os.sep.join([dirs['internal'], 'pai_cert.pem']) + pai_cert['cert_der'] = os.sep.join([dirs['internal'], 'pai_cert.der']) + pai_cert['key_pem'] = os.sep.join([dirs['internal'], 'pai_key.pem']) + + generate_pai_certs(args, args.key, args.cert, pai_cert['key_pem'], pai_cert['cert_pem']) + convert_x509_cert_from_pem_to_der(pai_cert['cert_pem'], pai_cert['cert_der']) + logger.info('Generated PAI certificate in DER format: {}'.format(pai_cert['cert_der'])) + + # If PAI is passed as input, generate DACs + elif args.pai: + pai_cert['cert_pem'] = args.cert + pai_cert['key_pem'] = args.key + pai_cert['cert_der'] = os.sep.join([dirs['internal'], 'pai_cert.der']) + + convert_x509_cert_from_pem_to_der(pai_cert['cert_pem'], pai_cert['cert_der']) + logger.info('Generated PAI certificate in DER format: {}'.format(pai_cert['cert_der'])) + + return pai_cert + + +# Generate the Public and Private key pair binaries +def generate_keypair_bin(pem_file, out_privkey_bin, out_pubkey_bin): + with open(pem_file, 'rb') as f: + pem_data = f.read() + + key_pem = cryptography.hazmat.primitives.serialization.load_pem_private_key(pem_data, None) + private_number_val = key_pem.private_numbers().private_value + public_number_x = key_pem.public_key().public_numbers().x + public_number_y = key_pem.public_key().public_numbers().y + public_key_first_byte = 0x04 + + with open(out_privkey_bin, 'wb') as f: + f.write(private_number_val.to_bytes(32, byteorder='big')) + + with open(out_pubkey_bin, 'wb') as f: + f.write(public_key_first_byte.to_bytes(1, byteorder='big')) + f.write(public_number_x.to_bytes(32, byteorder='big')) + f.write(public_number_y.to_bytes(32, byteorder='big')) + + +def generate_dac_cert(iteration, args, out_dirs, discriminator, passcode, ca_key, ca_cert): + out_key_pem = os.sep.join([out_dirs['internal'], 'DAC_key.pem']) + out_cert_pem = out_key_pem.replace('key.pem', 'cert.pem') + out_cert_der = out_key_pem.replace('key.pem', 'cert.der') + out_private_key_bin = out_key_pem.replace('key.pem', 'private_key.bin') + out_public_key_bin = out_key_pem.replace('key.pem', 'public_key.bin') + + cmd = [ + TOOLS['chip-cert'], 'gen-att-cert', + '--type', 'd', + '--subject-cn', '"{} DAC {}"'.format(args.cn_prefix, iteration), + '--out-key', out_key_pem, + '--out', out_cert_pem, + ] + + if args.lifetime: + cmd.extend(['--lifetime', str(args.lifetime)]) + if args.valid_from: + cmd.extend(['--valid-from', str(args.valid_from)]) + + cmd.extend(['--subject-vid', hex(args.vendor_id)[2:], + '--subject-pid', hex(args.product_id)[2:], + '--ca-key', ca_key, + '--ca-cert', ca_cert, + ]) + + execute_cmd(cmd) + logger.info('Generated DAC certificate: {}'.format(out_cert_pem)) + logger.info('Generated DAC private key: {}'.format(out_key_pem)) + + convert_x509_cert_from_pem_to_der(out_cert_pem, out_cert_der) + logger.info('Generated DAC certificate in DER format: {}'.format(out_cert_der)) + + generate_keypair_bin(out_key_pem, out_private_key_bin, out_public_key_bin) + logger.info('Generated DAC private key in binary format: {}'.format(out_private_key_bin)) + logger.info('Generated DAC public key in binary format: {}'.format(out_public_key_bin)) + + return out_cert_der, out_private_key_bin, out_public_key_bin + + +def use_dac_cert_from_args(args, out_dirs): + logger.info('Using DAC from command line arguments...') + logger.info('DAC Certificate: {}'.format(args.dac_cert)) + logger.info('DAC Private Key: {}'.format(args.dac_key)) + + # There should be only one UUID in the UUIDs list if DAC is specified + out_cert_der = os.sep.join([out_dirs['internal'], 'DAC_cert.der']) + out_private_key_bin = out_cert_der.replace('cert.der', 'private_key.bin') + out_public_key_bin = out_cert_der.replace('cert.der', 'public_key.bin') + + convert_x509_cert_from_pem_to_der(args.dac_cert, out_cert_der) + logger.info('Generated DAC certificate in DER format: {}'.format(out_cert_der)) + + generate_keypair_bin(args.dac_key, out_private_key_bin, out_public_key_bin) + logger.info('Generated DAC private key in binary format: {}'.format(out_private_key_bin)) + logger.info('Generated DAC public key in binary format: {}'.format(out_public_key_bin)) + + return out_cert_der, out_private_key_bin, out_public_key_bin + + +def get_manualcode_args(vid, pid, flow, discriminator, passcode): + payload_args = list() + payload_args.append('--discriminator') + payload_args.append(str(discriminator)) + payload_args.append('--setup-pin-code') + payload_args.append(str(passcode)) + payload_args.append('--version') + payload_args.append('0') + payload_args.append('--vendor-id') + payload_args.append(str(vid)) + payload_args.append('--product-id') + payload_args.append(str(pid)) + payload_args.append('--commissioning-mode') + payload_args.append(str(flow)) + return payload_args + + +def get_qrcode_args(vid, pid, flow, discriminator, passcode, disc_mode): + payload_args = get_manualcode_args(vid, pid, flow, discriminator, passcode) + payload_args.append('--rendezvous') + payload_args.append(str(1 << disc_mode)) + return payload_args + + +def get_chip_qrcode(chip_tool, vid, pid, flow, discriminator, passcode, disc_mode): + payload_args = get_qrcode_args(vid, pid, flow, discriminator, passcode, disc_mode) + cmd_args = [chip_tool, 'payload', 'generate-qrcode'] + cmd_args.extend(payload_args) + data = subprocess.check_output(cmd_args) + + # Command output is as below: + # \x1b[0;32m[1655386003372] [23483:7823617] CHIP: [TOO] QR Code: MT:Y.K90-WB010E7648G00\x1b[0m + return data.decode('utf-8').split('QR Code: ')[1][:QRCODE_LEN] + + +def get_chip_manualcode(chip_tool, vid, pid, flow, discriminator, passcode): + payload_args = get_manualcode_args(vid, pid, flow, discriminator, passcode) + cmd_args = [chip_tool, 'payload', 'generate-manualcode'] + cmd_args.extend(payload_args) + data = subprocess.check_output(cmd_args) + + # Command output is as below: + # \x1b[0;32m[1655386909774] [24424:7837894] CHIP: [TOO] Manual Code: 749721123365521327689\x1b[0m\n + # OR + # \x1b[0;32m[1655386926028] [24458:7838229] CHIP: [TOO] Manual Code: 34972112338\x1b[0m\n + # Length of manual code depends on the commissioning flow: + # For standard commissioning flow it is 11 digits + # For User-intent and custom commissioning flow it is 21 digits + manual_code_len = LONG_MANUALCODE_LEN if flow else SHORT_MANUALCODE_LEN + return data.decode('utf-8').split('Manual Code: ')[1][:manual_code_len] + + +def generate_onboarding_data(args, out_dirs, discriminator, passcode): + chip_manualcode = get_chip_manualcode(TOOLS['chip-tool'], args.vendor_id, args.product_id, + args.commissioning_flow, discriminator, passcode) + chip_qrcode = get_chip_qrcode(TOOLS['chip-tool'], args.vendor_id, args.product_id, + args.commissioning_flow, discriminator, passcode, args.discovery_mode) + + logger.info('Generated QR code: ' + chip_qrcode) + logger.info('Generated manual code: ' + chip_manualcode) + + csv_data = 'qrcode,manualcode,discriminator,passcode\n' + csv_data += chip_qrcode + ',' + chip_manualcode + ',' + str(discriminator) + ',' + str(passcode) + '\n' + + onboarding_data_file = os.sep.join([out_dirs['output'], 'onb_codes.csv']) + with open(onboarding_data_file, 'w') as f: + f.write(csv_data) + + # Create QR code image as mentioned in the spec + qrcode_file = os.sep.join([out_dirs['output'], 'qrcode.png']) + chip_qr = pyqrcode.create(chip_qrcode, version=2, error='M') + chip_qr.png(qrcode_file, scale=6) + + logger.info('Generated onboarding data and QR Code') + + +# This function generates the DACs, picks the commissionable data from the already present csv file, +# and generates the onboarding payloads, and writes everything to the master csv +def write_device_unique_data(args, out_dirs, pai_cert): + with open(os.sep.join([out_dirs['output'], 'pin_disc.csv']), 'r') as csvf: + pin_disc_dict = csv.DictReader(csvf) + row = pin_disc_dict.__next__() + + nvs_memory_append('discriminator', int(row['Discriminator'])) + nvs_memory_append('spake2_it', int(row['Iteration Count'])) + nvs_memory_append('spake2_salt', base64.b64decode(row['Salt'])) + nvs_memory_append('spake2_verifier', base64.b64decode(row['Verifier'])) + nvs_memory_append('passcode', int(row['PIN Code'])) + + if args.paa or args.pai: + if args.dac_key is not None and args.dac_cert is not None: + dacs = use_dac_cert_from_args(args, out_dirs) + else: + dacs = generate_dac_cert(int(row['Index']), args, out_dirs, int(row['Discriminator']), + int(row['PIN Code']), pai_cert['key_pem'], pai_cert['cert_pem']) + + nvs_memory_append('dac_cert', read_der_file(dacs[0])) + nvs_memory_append('dac_key', read_key_bin_file(dacs[1])) + nvs_memory_append('pai_cert', read_der_file(pai_cert['cert_der'])) + + nvs_memory_append('cert_dclrn', read_der_file(args.cert_dclrn)) + + if (args.enable_rotating_device_id is True) and (args.rd_id_uid is None): + nvs_memory_update('rd_uid', binascii.b2a_hex(os.urandom( + int(ROTATING_DEVICE_ID_UNIQUE_ID_LEN_BITS / 8))).decode('utf-8')) + + # Generate onboarding data + generate_onboarding_data(args, out_dirs, int(row['Discriminator']), int(row['PIN Code'])) + + return dacs + + +def generate_partition(args, out_dirs): + logger.info('Generating partition image: offset: 0x{:X} size: 0x{:X}'.format(args.offset, args.size)) + cbor_data = cbor.dumps(NVS_MEMORY) + # Create hex file + if len(cbor_data) > args.size: + raise ValueError("generated CBOR file exceeds declared maximum partition size! {} > {}".format(len(cbor_data), args.size)) + ih = IntelHex() + ih.putsz(args.offset, cbor_data) + ih.write_hex_file(os.sep.join([out_dirs['output'], 'factory_data.hex']), True) + ih.tobinfile(os.sep.join([out_dirs['output'], 'factory_data.bin'])) + + +def generate_json_summary(args, out_dirs, pai_certs, dacs_cert, serial_num: str): + json_dict = dict() + + json_dict['serial_num'] = serial_num + + for key, nvs_value in NVS_MEMORY.items(): + if (not isinstance(nvs_value, bytes) and not isinstance(nvs_value, bytearray)): + json_dict[key] = nvs_value + + with open(os.sep.join([out_dirs['output'], 'pin_disc.csv']), 'r') as csvf: + pin_disc_dict = csv.DictReader(csvf) + row = pin_disc_dict.__next__() + json_dict['passcode'] = row['PIN Code'] + json_dict['spake2_salt'] = row['Salt'] + json_dict['spake2_verifier'] = row['Verifier'] + + with open(os.sep.join([out_dirs['output'], 'onb_codes.csv']), 'r') as csvf: + pin_disc_dict = csv.DictReader(csvf) + row = pin_disc_dict.__next__() + for key, value in row.items(): + json_dict[key] = value + + for key, value in pai_certs.items(): + json_dict[key] = value + + if dacs_cert is not None: + json_dict['dac_cert'] = dacs_cert[0] + json_dict['dac_priv_key'] = dacs_cert[1] + json_dict['dac_pub_key'] = dacs_cert[2] + + json_dict['cert_dclrn'] = args.cert_dclrn + + # Format vid & pid as hex + json_dict['vendor_id'] = hex(json_dict['vendor_id']) + json_dict['product_id'] = hex(json_dict['product_id']) + + with open(os.sep.join([out_dirs['output'], 'summary.json']), 'w') as json_file: + json.dump(json_dict, json_file, indent=4) + + +def add_additional_kv(args, serial_num): + # Device instance information + if args.vendor_id is not None: + nvs_memory_append('vendor_id', args.vendor_id) + if args.vendor_name is not None: + nvs_memory_append('vendor_name', args.vendor_name) + if args.product_id is not None: + nvs_memory_append('product_id', args.product_id) + if args.product_name is not None: + nvs_memory_append('product_name', args.product_name) + if args.hw_ver is not None: + nvs_memory_append('hw_ver', args.hw_ver) + if args.hw_ver_str is not None: + nvs_memory_append('hw_ver_str', args.hw_ver_str) + if args.mfg_date is not None: + nvs_memory_append('date', args.mfg_date) + if args.enable_rotating_device_id: + nvs_memory_append('rd_uid', args.rd_id_uid) + + # Add the serial-num + nvs_memory_append('sn', serial_num) + + nvs_memory_append('version', FACTORY_DATA_VERSION) + + if args.enable_key: + nvs_memory_append('enable_key', args.enable_key) + + # Keys from basic clusters + if args.product_label is not None: + nvs_memory_append('product_label', args.product_label) + if args.product_url is not None: + nvs_memory_append('product_url', args.product_url) + if args.part_number is not None: + nvs_memory_append('part_number', args.part_number) + + +def get_and_validate_args(): + def allow_any_int(i): return int(i, 0) + def base64_str(s): return base64.b64decode(s) + + parser = argparse.ArgumentParser(description='Manufacuring partition generator tool', + formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=50)) + mandatory_args = parser.add_argument_group("Mandatory keys", "These arguments must be provided to generate JSON file") + optional_args = parser.add_argument_group("Optional keys", "These arguments are optional and they depend on the user-purpose") + + # General options + general_args = parser.add_argument_group('General options') + general_args.add_argument('-n', '--count', type=allow_any_int, default=1, + help='The number of manufacturing partition binaries to generate. Default is 1.') + general_args.add_argument("--output", type=str, required=False, default="out", + help="[string] Output path where generated data will be stored.") + general_args.add_argument("--spake2-path", type=str, required=False, + help="[string] Provide Spake2+ tool path") + general_args.add_argument("--chip-tool-path", type=str, required=False, + help="[string] Provide chip-tool path") + general_args.add_argument("--chip-cert-path", type=str, required=False, + help="[string] Provide chip-cert path") + general_args.add_argument("--overwrite", action="store_true", default=False, + help="If output directory exist this argument allows to generate new factory data and overwrite it.") + general_args.add_argument("--in-tree", action="store_true", default=False, + help="Use it only when building factory data from Matter source code.") + general_args.add_argument("--enable-key", type=str, + help="[hex string] [128-bit hex-encoded] The Enable Key is a 128-bit value that triggers manufacturer-specific action while invoking the TestEventTrigger Command." + "This value is used during Certification Tests, and should not be present on production devices.") + # Commissioning options + commissioning_args = parser.add_argument_group('Commisioning options') + commissioning_args.add_argument('--passcode', type=allow_any_int, + help='The passcode for pairing. Randomly generated if not specified.') + commissioning_args.add_argument("--spake2-it", type=allow_any_int, default=1000, + help="[int] Provide Spake2+ iteration count.") + commissioning_args.add_argument('--discriminator', type=allow_any_int, + help='The discriminator for pairing. Randomly generated if not specified.') + commissioning_args.add_argument('-cf', '--commissioning-flow', type=allow_any_int, default=0, + help='Device commissioning flow, 0:Standard, 1:User-Intent, 2:Custom. \ + Default is 0.', choices=[0, 1, 2]) + commissioning_args.add_argument('-dm', '--discovery-mode', type=allow_any_int, default=1, + help='Commissionable device discovery networking technology. \ + 0:WiFi-SoftAP, 1:BLE, 2:On-network. Default is BLE.', choices=[0, 1, 2]) + + # Device insrance information + dev_inst_args = parser.add_argument_group('Device instance information options') + dev_inst_args.add_argument('-v', '--vendor-id', type=allow_any_int, required=False, help='Vendor id') + dev_inst_args.add_argument('--vendor-name', type=str, required=False, help='Vendor name') + dev_inst_args.add_argument('-p', '--product-id', type=allow_any_int, required=False, help='Product id') + dev_inst_args.add_argument('--product-name', type=str, required=False, help='Product name') + dev_inst_args.add_argument('--hw-ver', type=allow_any_int, required=False, help='Hardware version') + dev_inst_args.add_argument('--hw-ver-str', type=str, required=False, help='Hardware version string') + dev_inst_args.add_argument('--mfg-date', type=str, required=False, help='Manufacturing date in format YYYY-MM-DD') + dev_inst_args.add_argument('--serial-num', type=str, required=False, help='Serial number in hex format') + dev_inst_args.add_argument('--enable-rotating-device-id', action='store_true', + help='Enable Rotating device id in the generated binaries') + dev_inst_args.add_argument('--rd-id-uid', type=str, required=False, + help='128-bit unique identifier for generating rotating device identifier, provide 32-byte hex string, e.g. "1234567890abcdef1234567890abcdef"') + + dac_args = parser.add_argument_group('Device attestation credential options') + # If DAC is present then PAI key is not required, so it is marked as not required here + # but, if DAC is not present then PAI key is required and that case is validated in validate_args() + dac_args.add_argument('-c', '--cert', type=str, required=False, help='The input certificate file in PEM format.') + dac_args.add_argument('-k', '--key', type=str, required=False, help='The input key file in PEM format.') + dac_args.add_argument('-cd', '--cert-dclrn', type=str, required=True, help='The certificate declaration file in DER format.') + dac_args.add_argument('--dac-cert', type=str, help='The input DAC certificate file in PEM format.') + dac_args.add_argument('--dac-key', type=str, help='The input DAC private key file in PEM format.') + dac_args.add_argument('-cn', '--cn-prefix', type=str, default='Telink', + help='The common name prefix of the subject of the generated certificate.') + dac_args.add_argument('-lt', '--lifetime', default=4294967295, type=allow_any_int, + help='Lifetime of the generated certificate. Default is 4294967295 if not specified, \ + this indicate that certificate does not have well defined expiration date.') + dac_args.add_argument('-vf', '--valid-from', type=str, + help='The start date for the certificate validity period in format --
[ :: ]. \ + Default is current date.') + input_cert_group = dac_args.add_mutually_exclusive_group(required=False) + input_cert_group.add_argument('--paa', action='store_true', help='Use input certificate as PAA certificate.') + input_cert_group.add_argument('--pai', action='store_true', help='Use input certificate as PAI certificate.') + + basic_args = parser.add_argument_group('Few more Basic clusters options') + basic_args.add_argument('--product-label', type=str, required=False, help='Product label') + basic_args.add_argument('--product-url', type=str, required=False, help='Product URL') + basic_args.add_argument('--part_number', type=str, required=False, help='Provide human-readable product number') + + part_gen_args = parser.add_argument_group('Partition generator options') + part_gen_args.add_argument('--offset', type=allow_any_int, default=0x1F4000, + help='Partition offset - an address in devices NVM memory, where factory data will be stored') + part_gen_args.add_argument('--size', type=allow_any_int, default=0x1000, + help='The maximum partition size') + + args = parser.parse_args() + + # Validate in-tree parameter + if args.count > 1 and args.in_tree: + logger.error('Option --in-tree can not be use together with --count > 1') + sys.exit(1) + + # Validate discriminator and passcode + check_int_range(args.discriminator, 0x0000, 0x0FFF, 'Discriminator') + if args.passcode is not None: + if ((args.passcode < 0x0000001 and args.passcode > 0x5F5E0FE) or (args.passcode in INVALID_PASSCODES)): + logger.error('Invalid passcode' + str(args.passcode)) + sys.exit(1) + + # Validate the device instance information + check_int_range(args.product_id, 0x0000, 0xFFFF, 'Product id') + check_int_range(args.vendor_id, 0x0000, 0xFFFF, 'Vendor id') + check_int_range(args.hw_ver, 0x0000, 0xFFFF, 'Hardware version') + check_int_range(args.spake2_it, 1, 10000, 'Spake2+ iteration count') + check_str_range(args.serial_num, 1, SERIAL_NUMBER_LEN, 'Serial number') + check_str_range(args.vendor_name, 1, 32, 'Vendor name') + check_str_range(args.product_name, 1, 32, 'Product name') + check_str_range(args.hw_ver_str, 1, 64, 'Hardware version string') + check_str_range(args.mfg_date, 8, 16, 'Manufacturing date') + check_str_range(args.rd_id_uid, 32, 32, 'Rotating device Unique id') + + # Validates the attestation related arguments + # DAC key and DAC cert both should be present or none + if (args.dac_key is not None) != (args.dac_cert is not None): + logger.error("dac_key and dac_cert should be both present or none") + sys.exit(1) + else: + # Make sure PAI certificate is present if DAC is present + if (args.dac_key is not None) and (args.pai is False): + logger.error('Please provide PAI certificate along with DAC certificate and DAC key') + sys.exit(1) + + # Validate the input certificate type, if DAC is not present + if args.dac_key is None and args.dac_cert is None: + if args.paa: + logger.info('Input Root certificate type PAA') + elif args.pai: + logger.info('Input Root certificate type PAI') + else: + logger.info('Do not include the device attestation certificates and keys in partition binaries') + + # Check if Key and certificate are present + if (args.paa or args.pai) and (args.key is None or args.cert is None): + logger.error('CA key and certificate are required to generate DAC key and certificate') + sys.exit(1) + + check_str_range(args.product_label, 1, 64, 'Product Label') + check_str_range(args.product_url, 1, 256, 'Product URL') + check_str_range(args.part_number, 1, 32, 'Part Number') + + return args + + +def main(): + logger.basicConfig(format='[%(asctime)s] [%(levelname)7s] - %(message)s', level=logger.INFO) + args = get_and_validate_args() + check_tools_exists(args) + + if os.path.exists(args.output): + if args.overwrite: + logger.info("Output directory already exists. All data will be overwritten.") + shutil.rmtree(args.output) + else: + logger.error("Output directory exists! Please use different or remove existing.") + exit(1) + + # If serial number is not passed, then generate one + if args.serial_num is None: + serial_num_int = int(binascii.b2a_hex(os.urandom(SERIAL_NUMBER_LEN)), 16) + logger.info("Serial number not provided. Using generated one: {}".format(hex(serial_num_int))) + else: + serial_num_int = int(args.serial_num, 16) + + out_dir_top = os.path.realpath(args.output) + os.makedirs(out_dir_top, exist_ok=True) + + dev_sn_file = open(os.sep.join([out_dir_top, "device_sn.csv"]), "w") + dev_sn_file.write(DEV_SN_CSV_HDR) + + for i in range(args.count): + pai_cert = {} + serial_num_str = format(serial_num_int + i, 'x') + logger.info("Generating for {}".format(serial_num_str)) + dev_sn_file.write(serial_num_str + '\n') + out_dirs = setup_out_dir(out_dir_top, args, serial_num_str) + add_additional_kv(args, serial_num_str) + generate_passcode(args, out_dirs) + generate_discriminator(args, out_dirs) + if args.paa or args.pai: + pai_cert = setup_root_certificates(args, out_dirs) + dacs_cert = write_device_unique_data(args, out_dirs, pai_cert) + generate_partition(args, out_dirs) + generate_json_summary(args, out_dirs, pai_cert, dacs_cert, serial_num_str) + + dev_sn_file.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/tools/telink/readme.md b/scripts/tools/telink/readme.md new file mode 100644 index 00000000000000..d3539b590d3591 --- /dev/null +++ b/scripts/tools/telink/readme.md @@ -0,0 +1,212 @@ +# Manufacturing Partition Generator Utility + +This tool is designed to generate factory partitions for mass production. + +## Dependencies + +Please make sure you have had the following tools before using the generator +tool. + +- [CHIP Certificate Tool](https://github.com/project-chip/connectedhomeip/tree/master/src/tools/chip-cert) + +- [SPAKE2P Parameters Tool](https://github.com/project-chip/connectedhomeip/tree/master/src/tools/spake2p) + +- [chip-tool](https://github.com/project-chip/connectedhomeip/tree/master/examples/chip-tool) + +### [Build Matter tools](https://github.com/project-chip/connectedhomeip/blob/master/docs/guides/BUILDING.md#build-for-the-host-os-linux-or-macos) + +1. Using the following commands to generate chip-tool, spake2p and chip-cert at + `path/to/connectedhomeip/build/out/host`. + + ```shell + cd path/to/connectedhomeip + source scripts/activate.sh + gn gen build/out/host + ninja -C build/out/host + ``` + +2. Add the tools path to \$PATH + + ```shell + export PATH="$PATH:path/to/connectedhomeip/build/out/host" + ``` + +### Install python dependencies + +```shell +cd path/to/connectedhomeip/scripts/tools/telink/ +python3 -m pip install -r requirements.txt +``` + +## Usage + +The following commands generate factory partitions using the default testing PAI +keys, certificates, and CD in Matter project. You can make it using yours +instead in real production. + +### Generate a factory partition + +```shell +python3 mfg_tool.py -v 0xFFF2 -p 0x8001 \ +--serial-num AABBCCDDEEFF11223344556677889900 \ +--vendor-name "Telink Semiconductor" \ +--product-name "not-specified" \ +--mfg-date 2022-12-12 \ +--hw-ver 1 \ +--hw-ver-str "prerelase" \ +--pai \ +--key /path/to/connectedhomeip/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Key.pem \ +--cert /path/to/connectedhomeip/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Cert.pem \ +-cd /path/to/connectedhomeip/credentials/test/certification-declaration/Chip-Test-CD-FFF2-8001.der \ +--spake2-path /path/to/spake2p \ +--chip-tool-path /path/to/chip-tool \ +--chip-cert-path /path/to/chip-cert +``` + +### Generate 5 factory partitions [Optional argument : --count] + +```shell +python3 mfg_tool.py --count 5 -v 0xFFF2 -p 0x8001 \ +--serial-num AABBCCDDEEFF11223344556677889900 \ +--vendor-name "Telink Semiconductor" \ +--product-name "not-specified" \ +--mfg-date 2022-02-02 \ +--hw-ver 1 \ +--hw-ver-str "prerelase" \ +--pai \ +--key /path/to/connectedhomeip/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Key.pem \ +--cert /path/to/connectedhomeip/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Cert.pem \ +-cd /path/to/connectedhomeip/credentials/test/certification-declaration/Chip-Test-CD-FFF2-8001.der \ +--spake2-path /path/to/spake2p \ +--chip-tool-path /path/to/chip-tool \ +--chip-cert-path /path/to/chip-cert +``` + +## Output files and directory structure + +``` +out +├── device_sn.csv +└── fff2_8001 + ├── aabbccddeeff11223344556677889900 + │   ├── factory_data.bin + │   ├── factory_data.hex + │   ├── internal + │   │   ├── DAC_cert.der + │   │   ├── DAC_cert.pem + │   │   ├── DAC_key.pem + │   │   ├── DAC_private_key.bin + │   │   ├── DAC_public_key.bin + │   │   └── pai_cert.der + │   ├── onb_codes.csv + │   ├── pin_disc.csv + │   ├── qrcode.png + │   └── summary.json + ├── aabbccddeeff11223344556677889901 + │   ├── factory_data.bin + │   ├── factory_data.hex + │   ├── internal + │   │   ├── DAC_cert.der + │   │   ├── DAC_cert.pem + │   │   ├── DAC_key.pem + │   │   ├── DAC_private_key.bin + │   │   ├── DAC_public_key.bin + │   │   └── pai_cert.der + │   ├── onb_codes.csv + │   ├── pin_disc.csv + │   ├── qrcode.png + │   └── summary.json + ├── aabbccddeeff11223344556677889902 + │   ├── factory_data.bin + │   ├── factory_data.hex + │   ├── internal + │   │   ├── DAC_cert.der + │   │   ├── DAC_cert.pem + │   │   ├── DAC_key.pem + │   │   ├── DAC_private_key.bin + │   │   ├── DAC_public_key.bin + │   │   └── pai_cert.der + │   ├── onb_codes.csv + │   ├── pin_disc.csv + │   ├── qrcode.png + │   └── summary.json + └── aabbccddeeff11223344556677889903 + ├── factory_data.bin + ├── factory_data.hex + ├── internal + │   ├── DAC_cert.der + │   ├── DAC_cert.pem + │   ├── DAC_key.pem + │   ├── DAC_private_key.bin + │   ├── DAC_public_key.bin + │   └── pai_cert.der + ├── onb_codes.csv + ├── pin_disc.csv + ├── qrcode.png + └── summary.json +``` + +Tool generates following output files: + +- Partition Binary : `factory_data.bin` and `factory_data.hex` +- Partition JSON : `summary.json` +- Onboarding codes : `onb_codes.csv` +- QR Code image : `qrcode.png` + +Other intermediate files are stored in `internal/` directory: + +- PAI Certificate : `pai_cert.der` +- DAC Certificates : `DAC_cert.der` and `DAC_cert.pem` +- DAC Private Key : `DAC_private_key.bin` +- DAC Public Key : `DAC_public_key.bin` + +Above files are stored at `out//`. Each device is identified with +an unique SN. + +## Flashing the factory partition FW into Matter App + +You can try one of these factory partition FW on developing stage. + +1. Prepare a Matter App FW with empty factory data partition. + + For example, `lighting-app`. Please generate the FW as below: + + ```shell + cd path/to/connectedhomeip/example/ligting-app/telink/ + west build -- -DCONFIG_CHIP_FACTORY_DATA=y + ``` + + The output FW is stored at `./build/zephyr/zephyr.bin`. + +2. Then flash Matter App FW onto B91 board. + +3. Then flash the `factory_data.bin` generated from the generator tool at + specific address: + + > Note: The offset for Matter + > [v1.0-branch](https://github.com/telink-semi/zephyr/blob/telink_matter_v1.0-branch/boards/riscv/tlsr9518adk80d/tlsr9518adk80d.dts) + > is `0xF4000` and for + > [master branch](https://github.com/telink-semi/zephyr/blob/telink_matter/boards/riscv/tlsr9518adk80d/tlsr9518adk80d.dts) + > is `0x1F4000`. You can check the `factory_partition` reg at + > `tlsr9518adk80d.dts` for details. + + For example, the `factory_data_bin` with serial number + `aabbccddeeff11223344556677889900`. Here is the expected output in logging: + + ```shell + ... + I: 947 [DL]Device Configuration: + I: 951 [DL] Serial Number: aabbccddeeff11223344556677889900 + I: 957 [DL] Vendor Id: 65522 (0xFFF2) + I: 961 [DL] Product Id: 32769 (0x8001) + I: 965 [DL] Hardware Version: 1 + I: 969 [DL] Setup Pin Code (0 for UNKNOWN/ERROR): 93320241 + I: 975 [DL] Setup Discriminator (0xFFFF for UNKNOWN/ERROR): 3008 (0xBC0) + I: 983 [DL] Manufacturing Date: 2022-02-02 + I: 988 [DL] Device Type: 65535 (0xFFFF) + I: 993 [SVR]SetupQRCode: [MT:634J042C00O-KB7Z-10] + I: 999 [SVR]Copy/paste the below URL in a browser to see the QR Code: + I: 1006 [SVR]https://project-chip.github.io/connectedhomeip/qrcode.html?data=MT%3A634J042C00O-KB7Z-10 + I: 1017 [SVR]Manual pairing code: [26251356956] + ... + ``` diff --git a/scripts/tools/telink/requirements.txt b/scripts/tools/telink/requirements.txt new file mode 100644 index 00000000000000..68323409dd2f6c --- /dev/null +++ b/scripts/tools/telink/requirements.txt @@ -0,0 +1,6 @@ +cryptography==36.0.2 +cffi==1.15.0 +future==0.18.2 +pycparser==2.21 +pypng==0.0.21 +PyQRCode==1.2.1 \ No newline at end of file diff --git a/scripts/tools/telink/telink_factory_data.schema b/scripts/tools/telink/telink_factory_data.schema deleted file mode 100644 index 561bf4d5d72682..00000000000000 --- a/scripts/tools/telink/telink_factory_data.schema +++ /dev/null @@ -1,164 +0,0 @@ -{ - "$id": "Telink_Factory_Data_schema", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "A representation of all factory data used in Matter's Telink device", - "type": "object", - "required": [ - "version", - "sn", - "vendor_id", - "product_id", - "vendor_name", - "product_name", - "date", - "hw_ver", - "hw_ver_str", - "dac_cert", - "dac_key", - "pai_cert", - "spake2_it", - "spake2_salt", - "spake2_verifier", - "discriminator" - ], - "properties": { - "version": { - "description": "Current version of the factory data set", - "type": "integer", - "minimum": 0, - "maximum": 255 - }, - "sn": { - "description": "Serial number of device", - "type": "string", - "maxLength": 32 - }, - "vendor_id": { - "description": "Vendor Identifier", - "type": "integer", - "minimum": 0, - "maximum": 65524 - }, - "product_id": { - "description": "Product Identifier", - "type": "integer", - "minimum": 1, - "maximum": 65535 - }, - "vendor_name": { - "description": "human-readable vendor name", - "type": "string", - "maxLength": 32 - }, - "product_name": { - "description": "human-readable product name", - "type": "string", - "maxLength": 32 - }, - "product_label": { - "description": "more user-friendly human-readable product name", - "type": "string", - "maxLength": 64 - }, - "product_url": { - "description": "link to product-specific web page", - "type": "string", - "maxLength": 256 - }, - "part_number": { - "description": "human-readable vendor assigned part number", - "type": "string", - "maxLength": 32 - }, - "date": { - "description": "Manufacturing date according to ISO 8601 in notation YYYY-MM-DD", - "type": "string", - "format": "date", - "minLength": 10, - "maxLength": 10, - "pattern": "^\\d{4}-\\d{2}-\\d{2}$" - }, - "hw_ver": { - "description": "Hardware version - integer", - "type": "integer", - "minimum": 0, - "maximum": 65536 - }, - "hw_ver_str": { - "description": "A string representation of hardware version", - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "rd_uid": { - "description": "A randomly-generated 128-bit or longer octet string. Length has been expanded with 'hex:' prefix", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2}){16,}$", - "minLength": 20, - "minLength": 36 - }, - "dac_cert": { - "description": "DAC certificate in hex-string format", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2})+$", - "minLength": 6, - "maxLength": 1204 - }, - "dac_key": { - "description": "DAC Private Key in hex-string format", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2}){32}$", - "minLength": 68, - "maxLength": 68 - }, - "pai_cert": { - "description": "PAI certificate in hex-string format", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2})+$", - "minLength": 6, - "maxLength": 1204 - }, - "passcode": { - "description": "A default PASE session passcode", - "type": "integer", - "minimum": 1, - "maximum": 99999998 - }, - "spake2_it": { - "description": "An Iteration counter for the Symmetric Password-Authenticated Key Exchange", - "type": "integer", - "minimum": 1000, - "maximum": 100000 - }, - "spake2_salt": { - "description": "A key-derivation function for the Symmetric Password-Authenticated Key Exchange.", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2})+$", - "minLength": 36, - "maxLength": 68 - }, - "spake2_verifier": { - "description": "A verifier for the Symmetric Password-Authenticated Key Exchange", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2})+$", - "minLength": 97 - }, - "discriminator": { - "description": "The Discriminator value helps to further identify potential devices during the setup process.", - "type": "integer", - "minimum": 0, - "maximum": 4095 - }, - "enable_key": { - "description": "The Enable Key is a 128-bit value that triggers manufacturer-specific action while invoking the TestEventTrigger Command", - "type": "string", - "pattern": "^hex:([0-9A-Fa-f]{2}){16}$", - "minLength": 36, - "maxLength": 36 - }, - "user": { - "description": "A user-specific additional data which should be added to factory data. This should be a Json format.", - "type": "object" - } - } -} diff --git a/scripts/tools/telink/telink_generate_partition.py b/scripts/tools/telink/telink_generate_partition.py deleted file mode 100644 index ddd3b63acc4a7f..00000000000000 --- a/scripts/tools/telink/telink_generate_partition.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/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 codecs -import sys -from intelhex import IntelHex -import argparse -import json -import logging as log -import cbor2 as cbor - -HEX_PREFIX = "hex:" - - -class PartitionCreator: - """ - Class to create telink partition containing FactoryData - - :param offset: This is a partition offset where data will be stored in device's flash memory - :param length: This is a maximum partition size - :param input: This is a path to input JSON file - :param output: This is a path to output directory - - """ - - def __init__(self, offset: int, length: int, input: str, output: str) -> None: - self._ih = IntelHex() - self._length = length - self._offset = offset - self._data_ready = False - self._output = output - self._input = input - try: - self.__data_to_save = self._convert_to_dict(self._load_json()) - except IOError: - sys.exit(-1) - - def generate_cbor(self): - """ - Generates .cbor file using cbor2 library. - It generate a CBORTag 55799 which is user-specific tag - - """ - if self.__data_to_save: - # prepare raw data from Json - cbor_data = cbor.dumps(self.__data_to_save) - return cbor_data - - def create_hex(self, data: bytes): - """ - Creates .hex file from CBOR. - This file can be write directly to device. - - """ - if len(data) > self._length: - raise ValueError("generated CBOR file exceeds declared maximum partition size! {} > {}".format(len(data), self._length)) - self._ih.putsz(self._offset, data) - self._ih.write_hex_file(self._output + ".hex", True) - self._data_ready = True - return True - - def create_bin(self): - """ - Creates raw binary data of created previously .hex file - - """ - if not self._data_ready: - log.error("Please create hex file first!") - return False - self._ih.tobinfile(self._output + ".bin") - return True - - @staticmethod - def _convert_to_dict(data): - """ - Converts a list containing tuples ("key_name", "key_value") to a dictionary - - If "key_value" of data entry is a string-type variable and contains a HEX_PREFIX algorithm decodes it - to hex format to be sure that a cbor file will contain proper bytes. - - If "key_value" of data entry is a dictionary, algorithm appends it to the created dictionary. - """ - output_dict = dict() - for entry in data: - if not isinstance(entry, dict): - log.debug("Processing entry {}".format(entry)) - if isinstance(data[entry], str) and data[entry].startswith(HEX_PREFIX): - output_dict[entry] = codecs.decode(data[entry][len(HEX_PREFIX):], "hex") - elif isinstance(data[entry], str): - output_dict[entry] = data[entry].encode("utf-8") - else: - output_dict[entry] = data[entry] - else: - output_dict[entry] = entry - return output_dict - - def _load_json(self): - """ - Loads file containing a JSON data and converts it to JSON format - - :raises IOError: if provided JSON file can not be read out. - """ - try: - with open(self._input, "rb") as json_file: - return json.loads(json_file.read()) - except IOError as e: - log.error("Can not read Json file {}".format(self._input)) - raise e - - -def print_flashing_help(): - print("\nTo flash the generated hex/bin containing factory data, use BDT tool") - - -def main(): - - def allow_any_int(i): return int(i, 0) - - parser = argparse.ArgumentParser(description="Telink Factory Data NVS partition generator tool") - parser.add_argument("-i", "--input", type=str, required=True, - help="Path to input .json file") - parser.add_argument("-o", "--output", type=str, required=True, - help="Prefix for output file paths, e.g. setting dir/output causes creation of the following files: dir/output.hex, and dir/output.bin") - parser.add_argument("--offset", type=allow_any_int, required=True, - help="Partition offset - an address in device's NVM memory, where factory data will be stored") - parser.add_argument("--size", type=allow_any_int, required=True, - help="The maximum partition size") - parser.add_argument("-v", "--verbose", action="store_true", - help="Run this script with DEBUG logging level") - parser.add_argument("-r", "--raw", action="store_true", - help="Do not print flashing help and other logs, only generate a .hex file. It can be useful when the script is used by other script.") - args = parser.parse_args() - - if args.verbose: - log.basicConfig(format='[%(asctime)s][%(levelname)s] %(message)s', level=log.DEBUG) - elif args.raw: - log.basicConfig(format='%(message)s', level=log.ERROR) - else: - log.basicConfig(format='[%(asctime)s] %(message)s', level=log.INFO) - - partition_creator = PartitionCreator(args.offset, args.size, args.input, args.output) - cbor_data = partition_creator.generate_cbor() - try: - if not args.raw: - print("Generating .hex file: {}.hex with offset: {} and size: {}".format(args.output, hex(args.offset), hex(args.size))) - if partition_creator.create_hex(cbor_data) and partition_creator.create_bin(): - if not args.raw: - print_flashing_help() - except ValueError as e: - log.error(e) - sys.exit(-1) - - -if __name__ == "__main__": - main() From 4e63e88509f975792a8a94e97469f1f35d68766d Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 4 Jan 2023 12:03:17 -0500 Subject: [PATCH 10/31] Align naming in Power Source cluster with the spec. (#24240) * Align naming in Power Source cluster with the spec. And enable the Power Source events, which were commented out. * Regenerate generated files. --- .../all-clusters-app.matter | 15 ++ .../all-clusters-minimal-app.matter | 15 ++ examples/lock-app/lock-common/lock-app.matter | 15 ++ .../placeholder/linux/apps/app1/config.matter | 15 ++ .../placeholder/linux/apps/app2/config.matter | 15 ++ examples/window-app/common/window-app.matter | 15 ++ .../data-model/chip/power-source-cluster.xml | 23 ++- .../data_model/controller-clusters.matter | 15 ++ .../CHIPEventTLVValueDecoder.cpp | 173 ++++++++++++++++++ .../devicecontroller/ChipEventStructs.java | 75 ++++++++ .../chip/devicecontroller/ChipIdLookup.java | 9 + .../python/chip/clusters/Objects.py | 64 +++++++ .../CHIP/templates/availability.yaml | 27 +++ .../CHIP/zap-generated/MTRBaseClusters.h | 5 +- .../CHIP/zap-generated/MTRClusterConstants.h | 7 + .../zap-generated/MTREventTLVValueDecoder.mm | 159 ++++++++++++++++ .../CHIP/zap-generated/MTRStructsObjc.h | 39 +++- .../CHIP/zap-generated/MTRStructsObjc.mm | 93 ++++++++++ .../zap-generated/cluster-objects.cpp | 123 +++++++++++++ .../zap-generated/cluster-objects.h | 110 +++++++++++ .../app-common/zap-generated/ids/Events.h | 18 ++ .../zap-generated/cluster/Commands.h | 13 +- .../cluster/logging/DataModelLogger.cpp | 93 ++++++++++ .../cluster/logging/DataModelLogger.h | 6 + .../zap-generated/cluster/Commands.h | 3 + 25 files changed, 1126 insertions(+), 19 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 754985f37dd4f4..2999f27a55bdb4 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -862,6 +862,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 58e0c12b20d3e9..0ea0a312a80a70 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -794,6 +794,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/examples/lock-app/lock-common/lock-app.matter b/examples/lock-app/lock-common/lock-app.matter index 72510069747932..283c91d72fed46 100644 --- a/examples/lock-app/lock-common/lock-app.matter +++ b/examples/lock-app/lock-common/lock-app.matter @@ -455,6 +455,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/examples/placeholder/linux/apps/app1/config.matter b/examples/placeholder/linux/apps/app1/config.matter index 383b1096765494..4ad37a9e6f581b 100644 --- a/examples/placeholder/linux/apps/app1/config.matter +++ b/examples/placeholder/linux/apps/app1/config.matter @@ -627,6 +627,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/examples/placeholder/linux/apps/app2/config.matter b/examples/placeholder/linux/apps/app2/config.matter index 383b1096765494..4ad37a9e6f581b 100644 --- a/examples/placeholder/linux/apps/app2/config.matter +++ b/examples/placeholder/linux/apps/app2/config.matter @@ -627,6 +627,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/examples/window-app/common/window-app.matter b/examples/window-app/common/window-app.matter index 578b658092fabc..cd0a0e789a10de 100644 --- a/examples/window-app/common/window-app.matter +++ b/examples/window-app/common/window-app.matter @@ -617,6 +617,21 @@ server cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml index 28ba55b9f30983..76b350a52bf239 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml @@ -59,22 +59,23 @@ limitations under the License. BatChargingCurrent ActiveBatChargeFaults - @@ -131,7 +132,7 @@ limitations under the License. - + @@ -152,6 +153,8 @@ limitations under the License. + @@ -170,4 +173,4 @@ limitations under the License. - \ No newline at end of file + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index d3ce74301608c7..4de517ed5d514e 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -995,6 +995,21 @@ client cluster PowerSource = 47 { kReplaceable = 0x8; } + info event WiredFaultChange = 0 { + WiredFault current[] = 0; + WiredFault previous[] = 1; + } + + info event BatFaultChange = 1 { + BatFault current[] = 0; + BatFault previous[] = 1; + } + + info event BatChargeFaultChange = 2 { + BatChargeFault current[] = 0; + BatChargeFault previous[] = 1; + } + readonly attribute PowerSourceStatus status = 0; readonly attribute int8u order = 1; readonly attribute char_string<60> description = 2; diff --git a/src/controller/java/zap-generated/CHIPEventTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPEventTLVValueDecoder.cpp index d8b949d64e8a8c..8313fe238777cc 100644 --- a/src/controller/java/zap-generated/CHIPEventTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPEventTLVValueDecoder.cpp @@ -967,6 +967,179 @@ jobject DecodeEventValue(const app::ConcreteEventPath & aPath, TLV::TLVReader & using namespace app::Clusters::PowerSource; switch (aPath.mEventId) { + case Events::WiredFaultChange::Id: { + Events::WiredFaultChange::DecodableType cppValue; + *aError = app::DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) + { + return nullptr; + } + jobject value_current; + chip::JniReferences::GetInstance().CreateArrayList(value_current); + + auto iter_value_current_0 = cppValue.current.begin(); + while (iter_value_current_0.Next()) + { + auto & entry_0 = iter_value_current_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_current, newElement_0); + } + + jobject value_previous; + chip::JniReferences::GetInstance().CreateArrayList(value_previous); + + auto iter_value_previous_0 = cppValue.previous.begin(); + while (iter_value_previous_0.Next()) + { + auto & entry_0 = iter_value_previous_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_previous, newElement_0); + } + + jclass wiredFaultChangeStructClass; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipEventStructs$PowerSourceClusterWiredFaultChangeEvent", wiredFaultChangeStructClass); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipEventStructs$PowerSourceClusterWiredFaultChangeEvent"); + return nullptr; + } + jmethodID wiredFaultChangeStructCtor = + env->GetMethodID(wiredFaultChangeStructClass, "", "(Ljava/util/ArrayList;Ljava/util/ArrayList;)V"); + if (wiredFaultChangeStructCtor == nullptr) + { + ChipLogError(Zcl, "Could not find ChipEventStructs$PowerSourceClusterWiredFaultChangeEvent constructor"); + return nullptr; + } + + jobject value = env->NewObject(wiredFaultChangeStructClass, wiredFaultChangeStructCtor, value_current, value_previous); + + return value; + } + case Events::BatFaultChange::Id: { + Events::BatFaultChange::DecodableType cppValue; + *aError = app::DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) + { + return nullptr; + } + jobject value_current; + chip::JniReferences::GetInstance().CreateArrayList(value_current); + + auto iter_value_current_0 = cppValue.current.begin(); + while (iter_value_current_0.Next()) + { + auto & entry_0 = iter_value_current_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_current, newElement_0); + } + + jobject value_previous; + chip::JniReferences::GetInstance().CreateArrayList(value_previous); + + auto iter_value_previous_0 = cppValue.previous.begin(); + while (iter_value_previous_0.Next()) + { + auto & entry_0 = iter_value_previous_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_previous, newElement_0); + } + + jclass batFaultChangeStructClass; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipEventStructs$PowerSourceClusterBatFaultChangeEvent", batFaultChangeStructClass); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipEventStructs$PowerSourceClusterBatFaultChangeEvent"); + return nullptr; + } + jmethodID batFaultChangeStructCtor = + env->GetMethodID(batFaultChangeStructClass, "", "(Ljava/util/ArrayList;Ljava/util/ArrayList;)V"); + if (batFaultChangeStructCtor == nullptr) + { + ChipLogError(Zcl, "Could not find ChipEventStructs$PowerSourceClusterBatFaultChangeEvent constructor"); + return nullptr; + } + + jobject value = env->NewObject(batFaultChangeStructClass, batFaultChangeStructCtor, value_current, value_previous); + + return value; + } + case Events::BatChargeFaultChange::Id: { + Events::BatChargeFaultChange::DecodableType cppValue; + *aError = app::DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) + { + return nullptr; + } + jobject value_current; + chip::JniReferences::GetInstance().CreateArrayList(value_current); + + auto iter_value_current_0 = cppValue.current.begin(); + while (iter_value_current_0.Next()) + { + auto & entry_0 = iter_value_current_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_current, newElement_0); + } + + jobject value_previous; + chip::JniReferences::GetInstance().CreateArrayList(value_previous); + + auto iter_value_previous_0 = cppValue.previous.begin(); + while (iter_value_previous_0.Next()) + { + auto & entry_0 = iter_value_previous_0.GetValue(); + jobject newElement_0; + std::string newElement_0ClassName = "java/lang/Integer"; + std::string newElement_0CtorSignature = "(I)V"; + chip::JniReferences::GetInstance().CreateBoxedObject( + newElement_0ClassName.c_str(), newElement_0CtorSignature.c_str(), static_cast(entry_0), newElement_0); + chip::JniReferences::GetInstance().AddToList(value_previous, newElement_0); + } + + jclass batChargeFaultChangeStructClass; + err = chip::JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/ChipEventStructs$PowerSourceClusterBatChargeFaultChangeEvent", + batChargeFaultChangeStructClass); + if (err != CHIP_NO_ERROR) + { + ChipLogError(Zcl, "Could not find class ChipEventStructs$PowerSourceClusterBatChargeFaultChangeEvent"); + return nullptr; + } + jmethodID batChargeFaultChangeStructCtor = + env->GetMethodID(batChargeFaultChangeStructClass, "", "(Ljava/util/ArrayList;Ljava/util/ArrayList;)V"); + if (batChargeFaultChangeStructCtor == nullptr) + { + ChipLogError(Zcl, "Could not find ChipEventStructs$PowerSourceClusterBatChargeFaultChangeEvent constructor"); + return nullptr; + } + + jobject value = + env->NewObject(batChargeFaultChangeStructClass, batChargeFaultChangeStructCtor, value_current, value_previous); + + return value; + } default: *aError = CHIP_ERROR_IM_MALFORMED_EVENT_PATH_IB; break; diff --git a/src/controller/java/zap-generated/chip/devicecontroller/ChipEventStructs.java b/src/controller/java/zap-generated/chip/devicecontroller/ChipEventStructs.java index fe77f3667f8c89..2040b030738a89 100644 --- a/src/controller/java/zap-generated/chip/devicecontroller/ChipEventStructs.java +++ b/src/controller/java/zap-generated/chip/devicecontroller/ChipEventStructs.java @@ -347,6 +347,81 @@ public String toString() { } } + public static class PowerSourceClusterWiredFaultChangeEvent { + public ArrayList current; + public ArrayList previous; + + public PowerSourceClusterWiredFaultChangeEvent( + ArrayList current, ArrayList previous) { + this.current = current; + this.previous = previous; + } + + @Override + public String toString() { + StringBuilder output = new StringBuilder(); + output.append("PowerSourceClusterWiredFaultChangeEvent {\n"); + output.append("\tcurrent: "); + output.append(current); + output.append("\n"); + output.append("\tprevious: "); + output.append(previous); + output.append("\n"); + output.append("}\n"); + return output.toString(); + } + } + + public static class PowerSourceClusterBatFaultChangeEvent { + public ArrayList current; + public ArrayList previous; + + public PowerSourceClusterBatFaultChangeEvent( + ArrayList current, ArrayList previous) { + this.current = current; + this.previous = previous; + } + + @Override + public String toString() { + StringBuilder output = new StringBuilder(); + output.append("PowerSourceClusterBatFaultChangeEvent {\n"); + output.append("\tcurrent: "); + output.append(current); + output.append("\n"); + output.append("\tprevious: "); + output.append(previous); + output.append("\n"); + output.append("}\n"); + return output.toString(); + } + } + + public static class PowerSourceClusterBatChargeFaultChangeEvent { + public ArrayList current; + public ArrayList previous; + + public PowerSourceClusterBatChargeFaultChangeEvent( + ArrayList current, ArrayList previous) { + this.current = current; + this.previous = previous; + } + + @Override + public String toString() { + StringBuilder output = new StringBuilder(); + output.append("PowerSourceClusterBatChargeFaultChangeEvent {\n"); + output.append("\tcurrent: "); + output.append(current); + output.append("\n"); + output.append("\tprevious: "); + output.append(previous); + output.append("\n"); + output.append("}\n"); + return output.toString(); + } + } + public static class GeneralDiagnosticsClusterHardwareFaultChangeEvent { public ArrayList current; public ArrayList previous; diff --git a/src/controller/java/zap-generated/chip/devicecontroller/ChipIdLookup.java b/src/controller/java/zap-generated/chip/devicecontroller/ChipIdLookup.java index 0bcad38c702c69..195215f6e8f56d 100644 --- a/src/controller/java/zap-generated/chip/devicecontroller/ChipIdLookup.java +++ b/src/controller/java/zap-generated/chip/devicecontroller/ChipIdLookup.java @@ -3183,6 +3183,15 @@ public static String eventIdToName(long clusterId, long eventId) { return ""; } if (clusterId == 47L) { + if (eventId == 0L) { + return "WiredFaultChange"; + } + if (eventId == 1L) { + return "BatFaultChange"; + } + if (eventId == 2L) { + return "BatChargeFaultChange"; + } return ""; } if (clusterId == 48L) { diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index a72378c2f393b3..6dea0ef9539d5d 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -6171,6 +6171,70 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: 'uint' = 0 + class Events: + @dataclass + class WiredFaultChange(ClusterEvent): + @ChipUtility.classproperty + def cluster_id(cls) -> int: + return 0x002F + + @ChipUtility.classproperty + def event_id(cls) -> int: + return 0x00000000 + + @ChipUtility.classproperty + def descriptor(cls) -> ClusterObjectDescriptor: + return ClusterObjectDescriptor( + Fields = [ + ClusterObjectFieldDescriptor(Label="current", Tag=0, Type=typing.List[PowerSource.Enums.WiredFault]), + ClusterObjectFieldDescriptor(Label="previous", Tag=1, Type=typing.List[PowerSource.Enums.WiredFault]), + ]) + + current: 'typing.List[PowerSource.Enums.WiredFault]' = field(default_factory=lambda: []) + previous: 'typing.List[PowerSource.Enums.WiredFault]' = field(default_factory=lambda: []) + + @dataclass + class BatFaultChange(ClusterEvent): + @ChipUtility.classproperty + def cluster_id(cls) -> int: + return 0x002F + + @ChipUtility.classproperty + def event_id(cls) -> int: + return 0x00000001 + + @ChipUtility.classproperty + def descriptor(cls) -> ClusterObjectDescriptor: + return ClusterObjectDescriptor( + Fields = [ + ClusterObjectFieldDescriptor(Label="current", Tag=0, Type=typing.List[PowerSource.Enums.BatFault]), + ClusterObjectFieldDescriptor(Label="previous", Tag=1, Type=typing.List[PowerSource.Enums.BatFault]), + ]) + + current: 'typing.List[PowerSource.Enums.BatFault]' = field(default_factory=lambda: []) + previous: 'typing.List[PowerSource.Enums.BatFault]' = field(default_factory=lambda: []) + + @dataclass + class BatChargeFaultChange(ClusterEvent): + @ChipUtility.classproperty + def cluster_id(cls) -> int: + return 0x002F + + @ChipUtility.classproperty + def event_id(cls) -> int: + return 0x00000002 + + @ChipUtility.classproperty + def descriptor(cls) -> ClusterObjectDescriptor: + return ClusterObjectDescriptor( + Fields = [ + ClusterObjectFieldDescriptor(Label="current", Tag=0, Type=typing.List[PowerSource.Enums.BatChargeFault]), + ClusterObjectFieldDescriptor(Label="previous", Tag=1, Type=typing.List[PowerSource.Enums.BatChargeFault]), + ]) + + current: 'typing.List[PowerSource.Enums.BatChargeFault]' = field(default_factory=lambda: []) + previous: 'typing.List[PowerSource.Enums.BatChargeFault]' = field(default_factory=lambda: []) + @dataclass class GeneralCommissioning(Cluster): diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index 010bddd35779d5..bc301ada0ea09e 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -5043,6 +5043,10 @@ - ShutDown - Leave - ReachableChanged + PowerSource: + - WiredFaultChange + - BatFaultChange + - BatChargeFaultChange event fields: Switch: MultiPressComplete: @@ -5078,6 +5082,16 @@ - fabricIndex ReachableChanged: - reachableNewValue + PowerSource: + WiredFaultChange: + - current + - previous + BatFaultChange: + - current + - previous + BatChargeFaultChange: + - current + - previous enums: OTASoftwareUpdateProvider: - OTAApplyUpdateAction @@ -5149,6 +5163,9 @@ - PASE - CASE - Group + PowerSource: + BatChargeLevel: + - OK bitmaps: UnitTesting: - Bitmap8MaskMap @@ -5229,6 +5246,10 @@ AccessControl: - AccessControlEntry - ExtensionEntry + PowerSource: + - WiredFaultChangeType + - BatFaultChangeType + - BatChargeFaultChangeType struct fields: Descriptor: DeviceTypeStruct: @@ -5245,6 +5266,9 @@ GeneralCommissioning: CommissioningError: - Ok + PowerSource: + BatChargeLevel: + - Ok apis: - Timed Invoke for server to client commands - Deprecated global attribute names @@ -5320,3 +5344,6 @@ GeneralCommissioning: CommissioningError: OK: Ok + PowerSource: + BatChargeLevel: + OK: Ok diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index c433a209131c12..7999ed99518178 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -17416,7 +17416,10 @@ typedef NS_ENUM(uint8_t, MTRPowerSourceBatChargeFault) { } API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRPowerSourceBatChargeLevel) { - MTRPowerSourceBatChargeLevelOk API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, + MTRPowerSourceBatChargeLevelOK MTR_NEWLY_AVAILABLE = 0x00, + MTRPowerSourceBatChargeLevelOk API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceBatChargeLevelOK") + = 0x00, MTRPowerSourceBatChargeLevelWarning API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, MTRPowerSourceBatChargeLevelCritical API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x02, } API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h index 53942f6a40012c..bdc6ae0152ada0 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h @@ -6821,6 +6821,13 @@ typedef NS_ENUM(uint32_t, MTREventIDType) { MTREventIDTypeClusterOTASoftwareUpdateRequestorEventVersionAppliedID MTR_NEWLY_AVAILABLE = 0x00000001, MTREventIDTypeClusterOTASoftwareUpdateRequestorEventDownloadErrorID MTR_NEWLY_AVAILABLE = 0x00000002, + // Cluster PowerSource deprecated event names + + // Cluster PowerSource events + MTREventIDTypeClusterPowerSourceEventWiredFaultChangeID MTR_NEWLY_AVAILABLE = 0x00000000, + MTREventIDTypeClusterPowerSourceEventBatFaultChangeID MTR_NEWLY_AVAILABLE = 0x00000001, + MTREventIDTypeClusterPowerSourceEventBatChargeFaultChangeID MTR_NEWLY_AVAILABLE = 0x00000002, + // Cluster GeneralDiagnostics deprecated event names MTRClusterGeneralDiagnosticsEventHardwareFaultChangeID API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) MTR_NEWLY_DEPRECATED("Please use MTREventIDTypeClusterGeneralDiagnosticsEventHardwareFaultChangeID") diff --git a/src/darwin/Framework/CHIP/zap-generated/MTREventTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTREventTLVValueDecoder.mm index 8e5f792ae28582..a2fa781704a557 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTREventTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTREventTLVValueDecoder.mm @@ -610,6 +610,165 @@ id MTRDecodeEventPayload(const ConcreteEventPath & aPath, TLV::TLVReader & aRead using namespace Clusters::PowerSource; switch (aPath.mEventId) { + case Events::WiredFaultChange::Id: { + Events::WiredFaultChange::DecodableType cppValue; + *aError = DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) { + return nil; + } + + __auto_type * value = [MTRPowerSourceClusterWiredFaultChangeEvent new]; + + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.current.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.current = memberValue; + } while (0); + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.previous.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.previous = memberValue; + } while (0); + + return value; + } + + case Events::BatFaultChange::Id: { + Events::BatFaultChange::DecodableType cppValue; + *aError = DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) { + return nil; + } + + __auto_type * value = [MTRPowerSourceClusterBatFaultChangeEvent new]; + + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.current.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.current = memberValue; + } while (0); + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.previous.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.previous = memberValue; + } while (0); + + return value; + } + + case Events::BatChargeFaultChange::Id: { + Events::BatChargeFaultChange::DecodableType cppValue; + *aError = DataModel::Decode(aReader, cppValue); + if (*aError != CHIP_NO_ERROR) { + return nil; + } + + __auto_type * value = [MTRPowerSourceClusterBatChargeFaultChangeEvent new]; + + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.current.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.current = memberValue; + } while (0); + do { + NSArray * _Nonnull memberValue; + { // Scope for our temporary variables + auto * array_0 = [NSMutableArray new]; + auto iter_0 = cppValue.previous.begin(); + while (iter_0.Next()) { + auto & entry_0 = iter_0.GetValue(); + NSNumber * newElement_0; + newElement_0 = [NSNumber numberWithUnsignedChar:chip::to_underlying(entry_0)]; + [array_0 addObject:newElement_0]; + } + CHIP_ERROR err = iter_0.GetStatus(); + if (err != CHIP_NO_ERROR) { + *aError = err; + return nil; + } + memberValue = array_0; + } + value.previous = memberValue; + } while (0); + + return value; + } + default: *aError = CHIP_ERROR_IM_MALFORMED_EVENT_PATH_IB; break; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h index e67a9749c7bda0..9c5aa2ee441931 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.h @@ -239,21 +239,48 @@ MTR_NEWLY_DEPRECATED("Please use MTROTASoftwareUpdateRequestorClusterDownloadErr @end API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) +MTR_NEWLY_DEPRECATED("This struct is unused and will be removed") @interface MTRPowerSourceClusterBatChargeFaultChangeType : NSObject -@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); -@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterBatChargeFaultChangeType"); +@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterBatChargeFaultChangeType"); @end API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) +MTR_NEWLY_DEPRECATED("This struct is unused and will be removed") @interface MTRPowerSourceClusterBatFaultChangeType : NSObject -@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); -@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterBatFaultChangeType"); +@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterBatFaultChangeType"); @end API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) +MTR_NEWLY_DEPRECATED("This struct is unused and will be removed") @interface MTRPowerSourceClusterWiredFaultChangeType : NSObject -@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); -@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); +@property (nonatomic, copy) NSArray * _Nonnull current API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterWiredFaultChangeType"); +@property (nonatomic, copy) NSArray * _Nonnull previous API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRPowerSourceClusterWiredFaultChangeType"); +@end + +MTR_NEWLY_AVAILABLE +@interface MTRPowerSourceClusterWiredFaultChangeEvent : NSObject +@property (nonatomic, copy) NSArray * _Nonnull current MTR_NEWLY_AVAILABLE; +@property (nonatomic, copy) NSArray * _Nonnull previous MTR_NEWLY_AVAILABLE; +@end + +MTR_NEWLY_AVAILABLE +@interface MTRPowerSourceClusterBatFaultChangeEvent : NSObject +@property (nonatomic, copy) NSArray * _Nonnull current MTR_NEWLY_AVAILABLE; +@property (nonatomic, copy) NSArray * _Nonnull previous MTR_NEWLY_AVAILABLE; +@end + +MTR_NEWLY_AVAILABLE +@interface MTRPowerSourceClusterBatChargeFaultChangeEvent : NSObject +@property (nonatomic, copy) NSArray * _Nonnull current MTR_NEWLY_AVAILABLE; +@property (nonatomic, copy) NSArray * _Nonnull previous MTR_NEWLY_AVAILABLE; @end API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm index 178783a5a2d40e..bdb39bf37da445 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRStructsObjc.mm @@ -910,6 +910,99 @@ - (NSString *)description @end +@implementation MTRPowerSourceClusterWiredFaultChangeEvent +- (instancetype)init +{ + if (self = [super init]) { + + _current = [NSArray array]; + + _previous = [NSArray array]; + } + return self; +} + +- (id)copyWithZone:(NSZone * _Nullable)zone +{ + auto other = [[MTRPowerSourceClusterWiredFaultChangeEvent alloc] init]; + + other.current = self.current; + other.previous = self.previous; + + return other; +} + +- (NSString *)description +{ + NSString * descriptionString = + [NSString stringWithFormat:@"<%@: current:%@; previous:%@; >", NSStringFromClass([self class]), _current, _previous]; + return descriptionString; +} + +@end + +@implementation MTRPowerSourceClusterBatFaultChangeEvent +- (instancetype)init +{ + if (self = [super init]) { + + _current = [NSArray array]; + + _previous = [NSArray array]; + } + return self; +} + +- (id)copyWithZone:(NSZone * _Nullable)zone +{ + auto other = [[MTRPowerSourceClusterBatFaultChangeEvent alloc] init]; + + other.current = self.current; + other.previous = self.previous; + + return other; +} + +- (NSString *)description +{ + NSString * descriptionString = + [NSString stringWithFormat:@"<%@: current:%@; previous:%@; >", NSStringFromClass([self class]), _current, _previous]; + return descriptionString; +} + +@end + +@implementation MTRPowerSourceClusterBatChargeFaultChangeEvent +- (instancetype)init +{ + if (self = [super init]) { + + _current = [NSArray array]; + + _previous = [NSArray array]; + } + return self; +} + +- (id)copyWithZone:(NSZone * _Nullable)zone +{ + auto other = [[MTRPowerSourceClusterBatChargeFaultChangeEvent alloc] init]; + + other.current = self.current; + other.previous = self.previous; + + return other; +} + +- (NSString *)description +{ + NSString * descriptionString = + [NSString stringWithFormat:@"<%@: current:%@; previous:%@; >", NSStringFromClass([self class]), _current, _previous]; + return descriptionString; +} + +@end + @implementation MTRGeneralCommissioningClusterBasicCommissioningInfo - (instancetype)init { diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 448310efafe87c..2d1476bdf79ff7 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -5241,6 +5241,129 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre } // namespace Attributes namespace Events { +namespace WiredFaultChange { +CHIP_ERROR Type::Encode(TLV::TLVWriter & writer, TLV::Tag tag) const +{ + TLV::TLVType outer; + ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outer)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kCurrent)), current)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kPrevious)), previous)); + ReturnErrorOnFailure(writer.EndContainer(outer)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + TLV::TLVType outer; + VerifyOrReturnError(TLV::kTLVType_Structure == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE); + ReturnErrorOnFailure(reader.EnterContainer(outer)); + while ((err = reader.Next()) == CHIP_NO_ERROR) + { + if (!TLV::IsContextTag(reader.GetTag())) + { + continue; + } + switch (TLV::TagNumFromTag(reader.GetTag())) + { + case to_underlying(Fields::kCurrent): + ReturnErrorOnFailure(DataModel::Decode(reader, current)); + break; + case to_underlying(Fields::kPrevious): + ReturnErrorOnFailure(DataModel::Decode(reader, previous)); + break; + default: + break; + } + } + + VerifyOrReturnError(err == CHIP_END_OF_TLV, err); + ReturnErrorOnFailure(reader.ExitContainer(outer)); + return CHIP_NO_ERROR; +} +} // namespace WiredFaultChange. +namespace BatFaultChange { +CHIP_ERROR Type::Encode(TLV::TLVWriter & writer, TLV::Tag tag) const +{ + TLV::TLVType outer; + ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outer)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kCurrent)), current)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kPrevious)), previous)); + ReturnErrorOnFailure(writer.EndContainer(outer)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + TLV::TLVType outer; + VerifyOrReturnError(TLV::kTLVType_Structure == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE); + ReturnErrorOnFailure(reader.EnterContainer(outer)); + while ((err = reader.Next()) == CHIP_NO_ERROR) + { + if (!TLV::IsContextTag(reader.GetTag())) + { + continue; + } + switch (TLV::TagNumFromTag(reader.GetTag())) + { + case to_underlying(Fields::kCurrent): + ReturnErrorOnFailure(DataModel::Decode(reader, current)); + break; + case to_underlying(Fields::kPrevious): + ReturnErrorOnFailure(DataModel::Decode(reader, previous)); + break; + default: + break; + } + } + + VerifyOrReturnError(err == CHIP_END_OF_TLV, err); + ReturnErrorOnFailure(reader.ExitContainer(outer)); + return CHIP_NO_ERROR; +} +} // namespace BatFaultChange. +namespace BatChargeFaultChange { +CHIP_ERROR Type::Encode(TLV::TLVWriter & writer, TLV::Tag tag) const +{ + TLV::TLVType outer; + ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outer)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kCurrent)), current)); + ReturnErrorOnFailure(DataModel::Encode(writer, TLV::ContextTag(to_underlying(Fields::kPrevious)), previous)); + ReturnErrorOnFailure(writer.EndContainer(outer)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + TLV::TLVType outer; + VerifyOrReturnError(TLV::kTLVType_Structure == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE); + ReturnErrorOnFailure(reader.EnterContainer(outer)); + while ((err = reader.Next()) == CHIP_NO_ERROR) + { + if (!TLV::IsContextTag(reader.GetTag())) + { + continue; + } + switch (TLV::TagNumFromTag(reader.GetTag())) + { + case to_underlying(Fields::kCurrent): + ReturnErrorOnFailure(DataModel::Decode(reader, current)); + break; + case to_underlying(Fields::kPrevious): + ReturnErrorOnFailure(DataModel::Decode(reader, previous)); + break; + default: + break; + } + } + + VerifyOrReturnError(err == CHIP_END_OF_TLV, err); + ReturnErrorOnFailure(reader.ExitContainer(outer)); + return CHIP_NO_ERROR; +} +} // namespace BatChargeFaultChange. } // namespace Events } // namespace PowerSource diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h index f6707991e0dfed..d9a23bfe1012e6 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h @@ -6375,6 +6375,116 @@ struct TypeInfo }; }; } // namespace Attributes +namespace Events { +namespace WiredFaultChange { +static constexpr PriorityLevel kPriorityLevel = PriorityLevel::Info; + +enum class Fields +{ + kCurrent = 0, + kPrevious = 1, +}; + +struct Type +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::WiredFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + static constexpr bool kIsFabricScoped = false; + + DataModel::List current; + DataModel::List previous; + + CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag) const; +}; + +struct DecodableType +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::WiredFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + + DataModel::DecodableList current; + DataModel::DecodableList previous; + + CHIP_ERROR Decode(TLV::TLVReader & reader); +}; +} // namespace WiredFaultChange +namespace BatFaultChange { +static constexpr PriorityLevel kPriorityLevel = PriorityLevel::Info; + +enum class Fields +{ + kCurrent = 0, + kPrevious = 1, +}; + +struct Type +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::BatFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + static constexpr bool kIsFabricScoped = false; + + DataModel::List current; + DataModel::List previous; + + CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag) const; +}; + +struct DecodableType +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::BatFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + + DataModel::DecodableList current; + DataModel::DecodableList previous; + + CHIP_ERROR Decode(TLV::TLVReader & reader); +}; +} // namespace BatFaultChange +namespace BatChargeFaultChange { +static constexpr PriorityLevel kPriorityLevel = PriorityLevel::Info; + +enum class Fields +{ + kCurrent = 0, + kPrevious = 1, +}; + +struct Type +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::BatChargeFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + static constexpr bool kIsFabricScoped = false; + + DataModel::List current; + DataModel::List previous; + + CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag) const; +}; + +struct DecodableType +{ +public: + static constexpr PriorityLevel GetPriorityLevel() { return kPriorityLevel; } + static constexpr EventId GetEventId() { return Events::BatChargeFaultChange::Id; } + static constexpr ClusterId GetClusterId() { return Clusters::PowerSource::Id; } + + DataModel::DecodableList current; + DataModel::DecodableList previous; + + CHIP_ERROR Decode(TLV::TLVReader & reader); +}; +} // namespace BatChargeFaultChange +} // namespace Events } // namespace PowerSource namespace GeneralCommissioning { namespace Structs { diff --git a/zzz_generated/app-common/app-common/zap-generated/ids/Events.h b/zzz_generated/app-common/app-common/zap-generated/ids/Events.h index 8dbc9ea7a323fb..e885f58360f248 100644 --- a/zzz_generated/app-common/app-common/zap-generated/ids/Events.h +++ b/zzz_generated/app-common/app-common/zap-generated/ids/Events.h @@ -93,6 +93,24 @@ static constexpr EventId Id = 0x00000002; } // namespace Events } // namespace OtaSoftwareUpdateRequestor +namespace PowerSource { +namespace Events { + +namespace WiredFaultChange { +static constexpr EventId Id = 0x00000000; +} // namespace WiredFaultChange + +namespace BatFaultChange { +static constexpr EventId Id = 0x00000001; +} // namespace BatFaultChange + +namespace BatChargeFaultChange { +static constexpr EventId Id = 0x00000002; +} // namespace BatChargeFaultChange + +} // namespace Events +} // namespace PowerSource + namespace GeneralDiagnostics { namespace Events { diff --git a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h index 845ea56ff454f9..8fbfa60a3baa13 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h @@ -2175,6 +2175,9 @@ class OtaSoftwareUpdateRequestorAnnounceOTAProvider : public ClusterCommand | * ClusterRevision | 0xFFFD | |------------------------------------------------------------------------------| | Events: | | +| * WiredFaultChange | 0x0000 | +| * BatFaultChange | 0x0001 | +| * BatChargeFaultChange | 0x0002 | \*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*\ @@ -9402,8 +9405,14 @@ void registerClusterPowerSource(Commands & commands, CredentialIssuerCommands * // // Events // - make_unique(Id, credsIssuerConfig), // - make_unique(Id, credsIssuerConfig), // + make_unique(Id, credsIssuerConfig), // + make_unique(Id, "wired-fault-change", Events::WiredFaultChange::Id, credsIssuerConfig), // + make_unique(Id, "bat-fault-change", Events::BatFaultChange::Id, credsIssuerConfig), // + make_unique(Id, "bat-charge-fault-change", Events::BatChargeFaultChange::Id, credsIssuerConfig), // + make_unique(Id, credsIssuerConfig), // + make_unique(Id, "wired-fault-change", Events::WiredFaultChange::Id, credsIssuerConfig), // + make_unique(Id, "bat-fault-change", Events::BatFaultChange::Id, credsIssuerConfig), // + make_unique(Id, "bat-charge-fault-change", Events::BatChargeFaultChange::Id, credsIssuerConfig), // }; commands.Register(clusterName, clusterCommands); diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp index 15e1dc60dc5ba4..5e4ec741353506 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -2771,6 +2771,78 @@ CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, return CHIP_NO_ERROR; } +CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, + const PowerSource::Events::WiredFaultChange::DecodableType & value) +{ + DataModelLogger::LogString(label, indent, "{"); + { + CHIP_ERROR err = DataModelLogger::LogValue("Current", indent + 1, value.current); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Current'"); + return err; + } + } + { + CHIP_ERROR err = DataModelLogger::LogValue("Previous", indent + 1, value.previous); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Previous'"); + return err; + } + } + DataModelLogger::LogString(indent, "}"); + + return CHIP_NO_ERROR; +} +CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, + const PowerSource::Events::BatFaultChange::DecodableType & value) +{ + DataModelLogger::LogString(label, indent, "{"); + { + CHIP_ERROR err = DataModelLogger::LogValue("Current", indent + 1, value.current); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Current'"); + return err; + } + } + { + CHIP_ERROR err = DataModelLogger::LogValue("Previous", indent + 1, value.previous); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Previous'"); + return err; + } + } + DataModelLogger::LogString(indent, "}"); + + return CHIP_NO_ERROR; +} +CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, + const PowerSource::Events::BatChargeFaultChange::DecodableType & value) +{ + DataModelLogger::LogString(label, indent, "{"); + { + CHIP_ERROR err = DataModelLogger::LogValue("Current", indent + 1, value.current); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Current'"); + return err; + } + } + { + CHIP_ERROR err = DataModelLogger::LogValue("Previous", indent + 1, value.previous); + if (err != CHIP_NO_ERROR) + { + DataModelLogger::LogString(indent + 1, "Event truncated due to invalid value for 'Previous'"); + return err; + } + } + DataModelLogger::LogString(indent, "}"); + + return CHIP_NO_ERROR; +} CHIP_ERROR DataModelLogger::LogValue(const char * label, size_t indent, const GeneralDiagnostics::Events::HardwareFaultChange::DecodableType & value) { @@ -10571,6 +10643,27 @@ CHIP_ERROR DataModelLogger::LogEvent(const chip::app::EventHeader & header, chip } break; } + case PowerSource::Id: { + switch (header.mPath.mEventId) + { + case PowerSource::Events::WiredFaultChange::Id: { + chip::app::Clusters::PowerSource::Events::WiredFaultChange::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("WiredFaultChange", 1, value); + } + case PowerSource::Events::BatFaultChange::Id: { + chip::app::Clusters::PowerSource::Events::BatFaultChange::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("BatFaultChange", 1, value); + } + case PowerSource::Events::BatChargeFaultChange::Id: { + chip::app::Clusters::PowerSource::Events::BatChargeFaultChange::DecodableType value; + ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); + return DataModelLogger::LogValue("BatChargeFaultChange", 1, value); + } + } + break; + } case GeneralDiagnostics::Id: { switch (header.mPath.mEventId) { diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h index 1683e2255b9d41..a3a71f6bc63a46 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.h @@ -165,6 +165,12 @@ static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::OtaSoftwareUpdateRequestor::Events::VersionApplied::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::OtaSoftwareUpdateRequestor::Events::DownloadError::DecodableType & value); +static CHIP_ERROR LogValue(const char * label, size_t indent, + const chip::app::Clusters::PowerSource::Events::WiredFaultChange::DecodableType & value); +static CHIP_ERROR LogValue(const char * label, size_t indent, + const chip::app::Clusters::PowerSource::Events::BatFaultChange::DecodableType & value); +static CHIP_ERROR LogValue(const char * label, size_t indent, + const chip::app::Clusters::PowerSource::Events::BatChargeFaultChange::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, const chip::app::Clusters::GeneralDiagnostics::Events::HardwareFaultChange::DecodableType & value); static CHIP_ERROR LogValue(const char * label, size_t indent, diff --git a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h index 7bb0ef4746c056..bbe21891c6e607 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h @@ -16338,6 +16338,9 @@ class SubscribeAttributePowerSourceConfigurationClusterRevision : public Subscri | * ClusterRevision | 0xFFFD | |------------------------------------------------------------------------------| | Events: | | +| * WiredFaultChange | 0x0000 | +| * BatFaultChange | 0x0001 | +| * BatChargeFaultChange | 0x0002 | \*----------------------------------------------------------------------------*/ /* From 459908944b475de4c0f24451fe9a88df4be9f2d5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Jan 2023 17:16:54 +0000 Subject: [PATCH 11/31] Bump third_party/pigweed/repo from `ead209d` to `39f7220` (#24226) Bumps [third_party/pigweed/repo](https://github.com/google/pigweed) from `ead209d` to `39f7220`. - [Release notes](https://github.com/google/pigweed/releases) - [Commits](https://github.com/google/pigweed/compare/ead209d3aa09821aa7549fbc8665ae68fe88d16f...39f72204df9c95c23d1ad4ee34274a116e6aedd7) --- updated-dependencies: - dependency-name: third_party/pigweed/repo dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third_party/pigweed/repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/pigweed/repo b/third_party/pigweed/repo index ead209d3aa0982..39f72204df9c95 160000 --- a/third_party/pigweed/repo +++ b/third_party/pigweed/repo @@ -1 +1 @@ -Subproject commit ead209d3aa09821aa7549fbc8665ae68fe88d16f +Subproject commit 39f72204df9c95c23d1ad4ee34274a116e6aedd7 From bf6575127637eda365f75e94aaf82c40522f235e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arkadiusz=20Ba=C5=82ys?= Date: Wed, 4 Jan 2023 18:23:28 +0100 Subject: [PATCH 12/31] [nrfconnect] Added support for user data in Factory Data parser (#24088) * [nrfconnect] Added support for user data in Factory Data parser Factory data parser did not contain methods to obtain user data. - Added two methods: GetUserData to obtain raw user data and GetUserKey to obtain a single key. - Improved the FactoryDataParser to read and manage the user data field. - Improved documentation. * Restyled by prettier-markdown Co-authored-by: Restyled.io --- .../nrfconnect_factory_data_configuration.md | 87 ++++++++++++++++++- .../tests/test_generate_factory_data.py | 20 +++++ src/platform/nrfconnect/FactoryDataParser.c | 75 +++++++++++++++- src/platform/nrfconnect/FactoryDataParser.h | 14 +++ .../nrfconnect/FactoryDataProvider.cpp | 26 ++++++ src/platform/nrfconnect/FactoryDataProvider.h | 22 +++++ 6 files changed, 242 insertions(+), 2 deletions(-) diff --git a/docs/guides/nrfconnect_factory_data_configuration.md b/docs/guides/nrfconnect_factory_data_configuration.md index c05b5a61ebaa16..7826fd6b9d15a8 100644 --- a/docs/guides/nrfconnect_factory_data_configuration.md +++ b/docs/guides/nrfconnect_factory_data_configuration.md @@ -41,6 +41,8 @@ data secure by applying hardware write protection. - [Enabling factory data support](#enabling-factory-data-support) - [Generating factory data](#generating-factory-data) - [Creating factory data JSON file with the first script](#creating-factory-data-json-file-with-the-first-script) + - [How to set user data](#how-to-set-user-data) + - [How to handle user data](#how-to-handle-user-data) - [Verifying using the JSON Schema tool](#verifying-using-the-json-schema-tool) - [Option 1: Using the php-json-schema tool](#option-1-using-the-php-json-schema-tool) - [Option 2: Using a website validator](#option-2-using-a-website-validator) @@ -110,7 +112,7 @@ The following table lists the parameters of a factory data set: | `spake2_verifier` | SPAKE2+ verifier | 97 B | byte string | mandatory | The SPAKE2+ verifier generated using SPAKE2+ salt, iteration counter, and passcode. | | `discriminator` | Discriminator | 2 B | uint16 | mandatory | A 12-bit value matching the field of the same name in the setup code. The discriminator is used during the discovery process. | | `passcode` | SPAKE passcode | 4 B | uint32 | optional | A pairing passcode is a 27-bit unsigned integer which serves as a proof of possession during the commissioning. Its value must be restricted to the values from `0x0000001` to `0x5F5E0FE` (`00000001` to `99999998` in decimal), excluding the following invalid passcode values: `00000000`, `11111111`, `22222222`, `33333333`, `44444444`, `55555555`, `66666666`, `77777777`, `88888888`, `99999999`, `12345678`, `87654321`. | -| `user` | User data | variable | JSON string | max 1024 B | The user data is provided in the JSON format. This parameter is optional and depends on user's or manufacturer's purpose (or both). It is provided as a string from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. | +| `user` | User data | variable | JSON string | max 1024 B | The user data is provided in the JSON format. This parameter is optional and depends on device manufacturer's purpose. It is provided as a CBOR map type from persistent storage and should be parsed in the user application. This data is not used by the Matter stack. To learn how to work with user data, see [How to set user data](#how-to-set-user-data) section. | ### Factory data format @@ -345,6 +347,89 @@ If the script finishes successfully, go to the location you provided with the > location as an existing file. To allow overwriting, add the `--overwrite` > option to the argument list of the Python script. +### How to set user data + +The user data is an optional field provided in the factory data JSON file and +depends on the manufacturer's purpose. The `user` field in a JSON factory data +file is represented by a flat JSON map and it can consist of `string` or `int32` +data types only. On the device side, the `user` data will be available as a CBOR +map containing all defined `string` and `int32` fields. + +To add user data as an argument to the +[generate_nrfconnect_chip_factory_data.py](../../scripts/tools/nrfconnect/generate_nrfconnect_chip_factory_data.py) +script, add the following line to the argument list: + +``` +--user-data {user data JSON} +``` + +As `user data JSON`, provide a flat JSON map with a value file that consists of +`string` or `int32` types. For example, you can use a JSON file that looks like +follows: + +``` +{ + "name": "product_name", + "version": 123, + "revision": "0x123" +} +``` + +When added to the argument line, the final result would look like follows: + +``` +--user-data '{"name": "product_name", "version": 123, "revision": "0x123"}' +``` + +#### How to handle user data + +The user data is not handled anywhere in the Matter stack, so you must handle it +in your application. To do this, you can use the +[Factory Data Provider](../../src/platform/nrfconnect/FactoryDataProvider.h) and +apply one of the following methods: + +- `GetUserData` method to obtain raw data in the CBOR format as a + `MutableByteSpan`. + +- `GetUserKey` method that lets you search along the user data list using a + specific key, and if the key exists in the user data, the method returns its + value. + +If you opt for `GetUserKey`, complete the following steps to set up the search: + +1. Add the `GetUserKey` method to your code. + +2. Given that all integer fields of the `user` Factory Data field are `int32`, + provide a buffer that has a size of at least `4B` or an `int32_t` variable to + `GetUserKey`. To read a string field from user data, the buffer should have a + size of at least the length of the expected string. + +3. Set it up to read all user data fields. + +Only after this setup is complete, can you use all variables in your code and +cast the result to your own purpose. + +The code example of how to read all fields from the JSON example one by one can +look like follows: + + ``` + chip::DeviceLayer::FactoryDataProvider factoryDataProvider; + + factoryDataProvider.Init(); + + uint8_t user_name[12]; + size_t name_len = sizeof(user_name); + factoryDataProvider.GetUserKey("name", user_name, name_len); + + int32_t version; + size_t version_len = sizeof(version); + factoryDataProvider.GetUserKey("version", &version, version_len); + + uint8_t revision[5]; + size_t revision_len = sizeof(revision); + factoryDataProvider.GetUserKey("revision", revision, revision_len); + ``` + ### Verifying using the JSON Schema tool The JSON file that contains factory data can be verified using the diff --git a/scripts/tools/nrfconnect/tests/test_generate_factory_data.py b/scripts/tools/nrfconnect/tests/test_generate_factory_data.py index ea6ccc445f733f..d3fd86f69bf3e5 100755 --- a/scripts/tools/nrfconnect/tests/test_generate_factory_data.py +++ b/scripts/tools/nrfconnect/tests/test_generate_factory_data.py @@ -171,6 +171,7 @@ def test_generate_factory_data_all_specified(self): '--discriminator', '0xFED', '--rd_uid', '91a9c12a7c80700a31ddcfa7fce63e44', '--enable_key', '00112233445566778899aabbccddeeff', + '--user', '{"name": "product_name", "version": 123, "revision": "0x123"}', '-o', os.path.join(outdir, 'fd.json') ]) @@ -199,6 +200,15 @@ def test_generate_factory_data_all_specified(self): self.assertEqual(factory_data.get('passcode'), 13243546) self.assertEqual(factory_data.get('rd_uid'), 'hex:91a9c12a7c80700a31ddcfa7fce63e44') self.assertEqual(factory_data.get('enable_key'), 'hex:00112233445566778899aabbccddeeff') + self.assertEqual(factory_data.get('user'), {'name': 'product_name', 'version': 123, 'revision': '0x123'}) + + subprocess.check_call(['python3', os.path.join(TOOLS_DIR, 'nrfconnect_generate_partition.py'), + '-i', os.path.join(outdir, 'fd.json'), + '-o', os.path.join(outdir, 'fd'), + '--offset', "0xfb000", + '--size', "0x1000", + '--raw' + ]) def test_generate_spake2p_verifier_default(self): with tempfile.TemporaryDirectory() as outdir: @@ -223,6 +233,7 @@ def test_generate_spake2p_verifier_default(self): '--spake2_salt', 'U1BBS0UyUCBLZXkgU2FsdA==', '--passcode', '20202021', '--discriminator', '0xFED', + '--user', '{"name": "product_name", "version": 123, "revision": "0x123"}', '-o', os.path.join(outdir, 'fd.json') ]) @@ -234,6 +245,15 @@ def test_generate_spake2p_verifier_default(self): self.assertEqual(factory_data.get('spake2_it'), 1000) self.assertEqual(factory_data.get('spake2_verifier'), base64_to_json( 'uWFwqugDNGiEck/po7KHwwMwwqZgN10XuyBajPGuyzUEV/iree4lOrao5GuwnlQ65CJzbeUB49s31EH+NEkg0JVI5MGCQGMMT/SRPFNRODm3wH/MBiehuFc6FJ/NH6Rmzw==')) + self.assertEqual(factory_data.get('user'), {'name': 'product_name', 'version': 123, 'revision': '0x123'}) + + subprocess.check_call(['python3', os.path.join(TOOLS_DIR, 'nrfconnect_generate_partition.py'), + '-i', os.path.join(outdir, 'fd.json'), + '-o', os.path.join(outdir, 'fd'), + '--offset', "0xfb000", + '--size', "0x1000", + '--raw' + ]) if __name__ == '__main__': diff --git a/src/platform/nrfconnect/FactoryDataParser.c b/src/platform/nrfconnect/FactoryDataParser.c index 64f412e7562bcd..19601887175bd6 100644 --- a/src/platform/nrfconnect/FactoryDataParser.c +++ b/src/platform/nrfconnect/FactoryDataParser.c @@ -40,6 +40,77 @@ static inline bool uint16_decode(zcbor_state_t * states, uint16_t * value) return false; } +static bool DecodeEntry(zcbor_state_t * states, void * buffer, size_t bufferSize, size_t * outlen) +{ + struct zcbor_string tempString; + int32_t tempInt = 0; + + // Try to decode entry as string + bool res = zcbor_tstr_decode(states, &tempString); + if (res) + { + if (bufferSize < tempString.len) + { + return false; + } + memcpy(buffer, tempString.value, tempString.len); + *outlen = tempString.len; + return res; + } + + // Try to decode entry as int32 + res = zcbor_int32_decode(states, &tempInt); + if (res) + { + if (bufferSize < sizeof(tempInt)) + { + return false; + } + memcpy(buffer, &tempInt, sizeof(tempInt)); + *outlen = sizeof(tempInt); + return res; + } + + return res; +} + +bool FindUserDataEntry(struct FactoryData * factoryData, const char * entry, void * buffer, size_t bufferSize, size_t * outlen) +{ + if ((!factoryData) || (!factoryData->user.data) || (!buffer) || (!outlen)) + { + return false; + } + + ZCBOR_STATE_D(states, MAX_FACTORY_DATA_NESTING_LEVEL - 1, factoryData->user.data, factoryData->user.len, 1); + + bool res = zcbor_map_start_decode(states); + bool keyFound = false; + struct zcbor_string currentString; + + while (res) + { + res = zcbor_tstr_decode(states, ¤tString); + + if (!res) + { + break; + } + + if (strncmp(entry, (const char *) currentString.value, currentString.len) == 0) + { + res = DecodeEntry(states, buffer, bufferSize, outlen); + keyFound = true; + break; + } + else + { + res = res && zcbor_any_skip(states, NULL); + } + } + + return res && keyFound && zcbor_list_map_end_force_decode(states); +} + bool ParseFactoryData(uint8_t * buffer, uint16_t bufferSize, struct FactoryData * factoryData) { memset(factoryData, 0, sizeof(*factoryData)); @@ -167,7 +238,9 @@ bool ParseFactoryData(uint8_t * buffer, uint16_t bufferSize, struct FactoryData } else if (strncmp("user", (const char *) currentString.value, currentString.len) == 0) { - res = res && zcbor_bstr_decode(states, (struct zcbor_string *) &factoryData->user); + factoryData->user.data = (void *) states->payload; + res = res && zcbor_any_skip(states, NULL); + factoryData->user.len = (void *) states->payload - factoryData->user.data; } else { diff --git a/src/platform/nrfconnect/FactoryDataParser.h b/src/platform/nrfconnect/FactoryDataParser.h index 9c87589560d469..b600371dde96ee 100644 --- a/src/platform/nrfconnect/FactoryDataParser.h +++ b/src/platform/nrfconnect/FactoryDataParser.h @@ -76,6 +76,20 @@ struct FactoryData */ bool ParseFactoryData(uint8_t * buffer, uint16_t bufferSize, struct FactoryData * factoryData); +/** + * @brief Tries to find an entry within the given factory data user data field. + * The parser parses only the uint32 type of ints. To read int-related objects the buffer size must be aligned to uint32. + * That means, to obtain uint8 or uint16 value users should provide the buffer with size at least sizeof(uint32_t). + * + * @param factoryData An address of object of factory data that contains user field filled. + * @param entry An entry name to be find out. + * @param buffer Output buffer to store found key value. + * @param bufferSize Size of buffer. That size should have size at least equal to expected key value. + * @param outlen Actual size of found user data field. + * @return true on success, false otherwise + */ +bool FindUserDataEntry(struct FactoryData * factoryData, const char * entry, void * buffer, size_t bufferSize, size_t * outlen); + #ifdef __cplusplus } #endif diff --git a/src/platform/nrfconnect/FactoryDataProvider.cpp b/src/platform/nrfconnect/FactoryDataProvider.cpp index ed3fd939bb3f22..cd52046c6de4f8 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.cpp +++ b/src/platform/nrfconnect/FactoryDataProvider.cpp @@ -339,6 +339,32 @@ CHIP_ERROR FactoryDataProvider::GetEnableKey(MutableByteSpan & return CHIP_NO_ERROR; } +template +CHIP_ERROR FactoryDataProvider::GetUserData(MutableByteSpan & userData) +{ + ReturnErrorCodeIf(!mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + ReturnErrorCodeIf(userData.size() < mFactoryData.user.len, CHIP_ERROR_BUFFER_TOO_SMALL); + + memcpy(userData.data(), mFactoryData.user.data, mFactoryData.user.len); + + userData.reduce_size(mFactoryData.user.len); + + return CHIP_NO_ERROR; +} + +template +CHIP_ERROR FactoryDataProvider::GetUserKey(const char * userKey, void * buf, size_t & len) +{ + ReturnErrorCodeIf(!mFactoryData.user.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + ReturnErrorCodeIf(!buf, CHIP_ERROR_BUFFER_TOO_SMALL); + + bool success = FindUserDataEntry(&mFactoryData, userKey, buf, len, &len); + + ReturnErrorCodeIf(!success, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + + return CHIP_NO_ERROR; +} + // Fully instantiate the template class in whatever compilation unit includes this file. template class FactoryDataProvider; template class FactoryDataProvider; diff --git a/src/platform/nrfconnect/FactoryDataProvider.h b/src/platform/nrfconnect/FactoryDataProvider.h index a7111acf66ee27..3d46076a5a3669 100644 --- a/src/platform/nrfconnect/FactoryDataProvider.h +++ b/src/platform/nrfconnect/FactoryDataProvider.h @@ -111,6 +111,28 @@ class FactoryDataProvider : public chip::Credentials::DeviceAttestationCredentia // ===== Members functions that are platform-specific CHIP_ERROR GetEnableKey(MutableByteSpan & enableKey); + /** + * @brief Get the user data in CBOR format as MutableByteSpan + * + * @param userData MutableByteSpan object to obtain all user data in CBOR format + * @returns + * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user field, or the value cannot be read out. + * CHIP_ERROR_BUFFER_TOO_SMALL if provided MutableByteSpan is too small + */ + CHIP_ERROR GetUserData(MutableByteSpan & userData); + + /** + * @brief Try to find user data key and return its value + * + * @param userKey A key name to be found + * @param buf Buffer to store value of found key + * @param len Length of the buffer. This value will be updated to the actual value if the key is read. + * @returns + * CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND if factory data does not contain user field, or the value cannot be read out. + * CHIP_ERROR_BUFFER_TOO_SMALL if provided buffer length is too small + */ + CHIP_ERROR GetUserKey(const char * userKey, void * buf, size_t & len); + private: static constexpr uint16_t kFactoryDataPartitionSize = PM_FACTORY_DATA_SIZE; static constexpr uint32_t kFactoryDataPartitionAddress = PM_FACTORY_DATA_ADDRESS; From 926fefe0150d4227e65dfcbaa44f8efed6139bac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Jan 2023 12:24:47 -0500 Subject: [PATCH 13/31] Bump third_party/openthread/repo from `98e644d` to `f2c02df` (#24225) Bumps [third_party/openthread/repo](https://github.com/openthread/openthread) from `98e644d` to `f2c02df`. - [Release notes](https://github.com/openthread/openthread/releases) - [Commits](https://github.com/openthread/openthread/compare/98e644d538ff2c57e96c54bdd6e13df31c7d19ba...f2c02dfd180df84dd8f4f02260cc5e12339ea563) --- updated-dependencies: - dependency-name: third_party/openthread/repo dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third_party/openthread/repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/openthread/repo b/third_party/openthread/repo index 98e644d538ff2c..f2c02dfd180df8 160000 --- a/third_party/openthread/repo +++ b/third_party/openthread/repo @@ -1 +1 @@ -Subproject commit 98e644d538ff2c57e96c54bdd6e13df31c7d19ba +Subproject commit f2c02dfd180df84dd8f4f02260cc5e12339ea563 From cf330aefefe6afd1fecb0ef8874adb8bc32f7d75 Mon Sep 17 00:00:00 2001 From: abiradarti <104591549+abiradarti@users.noreply.github.com> Date: Wed, 4 Jan 2023 12:41:59 -0600 Subject: [PATCH 14/31] [TI] Factory Reset updates for CC13X2_26X2 (#23963) * factory reset updates * Restyled by whitespace * Restyled by clang-format * CI fixes * Restyled by clang-format * Restyled by gn * updated 3 keys from factory to counters itemID * Restyled by whitespace * Restyled by clang-format * PR feedback * Restyled by clang-format * removed extern C and log function in DAC file * Restyled by clang-format Co-authored-by: Restyled.io --- examples/platform/cc13x2_26x2/BUILD.gn | 21 +- .../CC13X2_26X2DeviceAttestationCreds.cpp | 258 ++++++++++++++++++ .../CC13X2_26X2DeviceAttestationCreds.h | 36 +++ examples/pump-app/cc13x2x7_26x2x7/BUILD.gn | 1 + .../pump-app/cc13x2x7_26x2x7/main/AppTask.cpp | 12 +- .../cc13x2_26x2/CC13X2_26X2Config.cpp | 175 +++++++----- src/platform/cc13x2_26x2/CC13X2_26X2Config.h | 19 +- .../cc13x2_26x2/ConfigurationManagerImpl.cpp | 4 +- 8 files changed, 447 insertions(+), 79 deletions(-) create mode 100644 examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp create mode 100644 examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.h diff --git a/examples/platform/cc13x2_26x2/BUILD.gn b/examples/platform/cc13x2_26x2/BUILD.gn index a886bd6ee48c63..619ecdfa446dc5 100644 --- a/examples/platform/cc13x2_26x2/BUILD.gn +++ b/examples/platform/cc13x2_26x2/BUILD.gn @@ -14,11 +14,22 @@ import("//build_overrides/chip.gni") -config("chip_examples_project_config") { - include_dirs = [ "project_include" ] +config("attestation-credentials-config") { + include_dirs = [ "${chip_root}" ] + + defines = [ "CC13X2_26X2_ATTESTATION_CREDENTIALS" ] } -source_set("openthread_core_config_cc13x2_26x2_chip_examples") { - sources = [ "project_include/OpenThreadConfig.h" ] - public_configs = [ ":chip_examples_project_config" ] +source_set("cc13x2_26x2-attestation-credentials") { + sources = [ + "CC13X2_26X2DeviceAttestationCreds.cpp", + "CC13X2_26X2DeviceAttestationCreds.h", + ] + + public_deps = [ + "${chip_root}/src/credentials", + "${chip_root}/src/platform:platform_base", + ] + + public_configs = [ ":attestation-credentials-config" ] } diff --git a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp new file mode 100644 index 00000000000000..9e39a54c263668 --- /dev/null +++ b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.cpp @@ -0,0 +1,258 @@ +/* + * + * 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 "CC13X2_26X2DeviceAttestationCreds.h" +#include +#include +#include +#include +#include +#include + +extern uint32_t __attestation_credentials_base; + +namespace chip { +namespace Credentials { +namespace CC13X2_26X2 { + +namespace { + +typedef struct +{ + const uint32_t len; + uint8_t const * data; +} data_ptr; + +typedef struct +{ + data_ptr dac_priv_key; + data_ptr dac_pub_key; + data_ptr dac_cert; + data_ptr pai_cert; +} factoryData; + +const uint8_t gDacPrivKey[] = { + 0x50, 0x5a, 0x21, 0x1d, 0xbd, 0xa8, 0x71, 0x33, 0x0d, 0x63, 0x5d, 0xa3, 0xb0, 0x7e, 0xb1, 0xc5, + 0x08, 0x8a, 0x8f, 0xc7, 0x01, 0x24, 0xfb, 0xb3, 0x3e, 0x93, 0xd5, 0x06, 0x05, 0x82, 0xc7, 0xc5, +}; +const uint8_t gDacPubKey[] = { + 0x04, 0xc5, 0x65, 0xfd, 0xad, 0xfd, 0x16, 0xdd, 0x62, 0xe4, 0x3f, 0x19, 0x60, 0xb9, 0x93, 0xbb, 0x57, + 0x2c, 0xfd, 0xd8, 0x1f, 0x6d, 0x71, 0x67, 0x67, 0x1b, 0x77, 0x45, 0xdc, 0xbe, 0x6f, 0x65, 0xaf, 0x66, + 0x5a, 0x1d, 0x93, 0x1c, 0x05, 0xb9, 0xf9, 0xa3, 0xe9, 0x45, 0x66, 0x85, 0x60, 0x2c, 0x05, 0xc6, 0x96, + 0x46, 0xb8, 0xf7, 0x59, 0x98, 0xdb, 0xaa, 0x68, 0x7a, 0x5c, 0x56, 0x49, 0x02, 0xda, +}; +const uint8_t gDacCert[] = { + 0x30, 0x82, 0x01, 0xf7, 0x30, 0x82, 0x01, 0x9d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x46, 0x88, 0xeb, 0x94, 0xad, 0x32, + 0xb2, 0xe4, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x4d, 0x31, 0x1f, 0x30, 0x1d, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, + 0x65, 0x6e, 0x74, 0x20, 0x50, 0x41, 0x49, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, + 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, + 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x36, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, + 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, + 0x5a, 0x30, 0x52, 0x31, 0x24, 0x30, 0x22, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1b, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, + 0x44, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x44, 0x41, 0x43, 0x20, 0x30, 0x30, 0x30, 0x30, 0x31, + 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, + 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, + 0x36, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, + 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc5, 0x65, 0xfd, 0xad, 0xfd, 0x16, 0xdd, 0x62, 0xe4, 0x3f, 0x19, 0x60, 0xb9, 0x93, + 0xbb, 0x57, 0x2c, 0xfd, 0xd8, 0x1f, 0x6d, 0x71, 0x67, 0x67, 0x1b, 0x77, 0x45, 0xdc, 0xbe, 0x6f, 0x65, 0xaf, 0x66, 0x5a, 0x1d, + 0x93, 0x1c, 0x05, 0xb9, 0xf9, 0xa3, 0xe9, 0x45, 0x66, 0x85, 0x60, 0x2c, 0x05, 0xc6, 0x96, 0x46, 0xb8, 0xf7, 0x59, 0x98, 0xdb, + 0xaa, 0x68, 0x7a, 0x5c, 0x56, 0x49, 0x02, 0xda, 0xa3, 0x60, 0x30, 0x5e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, + 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x07, 0x80, + 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x9b, 0x40, 0x60, 0x6f, 0x9e, 0x04, 0x7f, 0xb8, 0x60, 0x78, + 0x8e, 0x3d, 0xc1, 0x12, 0xd7, 0x5e, 0x87, 0x95, 0x77, 0x68, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, + 0x80, 0x14, 0x43, 0x34, 0x57, 0x12, 0xba, 0x2c, 0x87, 0xef, 0x25, 0x49, 0x7b, 0x11, 0xd7, 0x98, 0x58, 0x9b, 0x84, 0x35, 0x7f, + 0x88, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, + 0xb9, 0x28, 0xf9, 0x3e, 0xe3, 0x87, 0xef, 0x3e, 0x00, 0x72, 0x88, 0x22, 0x84, 0xbd, 0x8a, 0xdd, 0x5c, 0xd6, 0xd0, 0x55, 0x81, + 0xbf, 0xcc, 0x55, 0x17, 0xcf, 0x9e, 0x9b, 0xcd, 0xd4, 0x37, 0xda, 0x02, 0x20, 0x10, 0x07, 0x9c, 0xcf, 0x7f, 0x1f, 0x2d, 0xda, + 0x46, 0xac, 0xe9, 0x67, 0xae, 0x5b, 0xe9, 0x66, 0xe7, 0xf2, 0x8a, 0xdf, 0xa0, 0x28, 0xb8, 0xf8, 0x7f, 0x93, 0x9e, 0xd4, 0x15, + 0x8d, 0xc0, 0xf8, +}; + +const uint8_t gPaiCert[] = { + 0x30, 0x82, 0x01, 0xdc, 0x30, 0x82, 0x01, 0x81, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x7f, 0x7e, 0xf3, 0xdb, 0x08, 0xa3, + 0x8f, 0x68, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x30, 0x31, 0x18, 0x30, 0x16, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, + 0x31, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, + 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x4d, 0x31, 0x1f, 0x30, 0x1d, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x44, 0x65, 0x76, 0x65, 0x6c, 0x6f, 0x70, 0x6d, + 0x65, 0x6e, 0x74, 0x20, 0x50, 0x41, 0x49, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, + 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x31, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, + 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x36, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, + 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x42, 0x93, 0x55, 0x77, 0x35, 0x35, + 0x15, 0xce, 0xfa, 0x8f, 0x0e, 0x30, 0xe2, 0x34, 0x7e, 0x90, 0xee, 0xd6, 0xfd, 0x51, 0x5b, 0xe8, 0x82, 0xd1, 0xbc, 0xba, 0x74, + 0x83, 0xd7, 0xff, 0x6e, 0xf4, 0xde, 0xdf, 0x98, 0xf7, 0xf7, 0x4f, 0x17, 0x42, 0x1d, 0xe5, 0x45, 0x0c, 0xff, 0xfb, 0x3e, 0x7f, + 0x6d, 0x4f, 0x62, 0x28, 0x53, 0x41, 0x14, 0xfb, 0xb8, 0x5c, 0x2d, 0x52, 0xd1, 0x82, 0xb6, 0x6a, 0xa3, 0x66, 0x30, 0x64, 0x30, + 0x12, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, + 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, + 0x04, 0x16, 0x04, 0x14, 0x43, 0x34, 0x57, 0x12, 0xba, 0x2c, 0x87, 0xef, 0x25, 0x49, 0x7b, 0x11, 0xd7, 0x98, 0x58, 0x9b, 0x84, + 0x35, 0x7f, 0x88, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x6a, 0xfd, 0x22, 0x77, 0x1f, + 0x51, 0x1f, 0xec, 0xbf, 0x16, 0x41, 0x97, 0x67, 0x10, 0xdc, 0xdc, 0x31, 0xa1, 0x71, 0x7e, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, + 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x49, 0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0xff, 0x25, 0xf1, 0xd1, 0x54, 0xc3, 0x13, + 0x7e, 0x0e, 0x08, 0x6d, 0x82, 0xab, 0x0b, 0x11, 0xb5, 0x66, 0x18, 0x39, 0xb7, 0x12, 0xb1, 0x34, 0x2c, 0x6c, 0xde, 0x94, 0xfb, + 0xe3, 0x18, 0xa9, 0x2b, 0x02, 0x21, 0x00, 0x92, 0xe2, 0x81, 0xf9, 0x8a, 0x2f, 0xcc, 0x14, 0xcd, 0xf4, 0x07, 0x50, 0xd2, 0x80, + 0xd7, 0xdf, 0xea, 0x3f, 0x4d, 0xa4, 0x6f, 0x35, 0x7a, 0xfe, 0xac, 0xb8, 0x9b, 0x26, 0x77, 0x06, 0xd2, 0x8a, +}; + +const factoryData gFactoryData = { + .dac_priv_key = { + .len = sizeof(gDacPrivKey), + .data = gDacPrivKey, + }, + .dac_pub_key = { + .len = sizeof(gDacPubKey), + .data = gDacPubKey, + }, + .dac_cert = { + .len = sizeof(gDacCert), + .data = gDacCert, + }, + .pai_cert = { + .len = sizeof(gPaiCert), + .data = gPaiCert, + }, +}; + +CHIP_ERROR LoadKeypairFromRaw(ByteSpan private_key, ByteSpan public_key, Crypto::P256Keypair & keypair) +{ + Crypto::P256SerializedKeypair serialized_keypair; + ReturnErrorOnFailure(serialized_keypair.SetLength(private_key.size() + public_key.size())); + memcpy(serialized_keypair.Bytes(), public_key.data(), public_key.size()); + memcpy(serialized_keypair.Bytes() + public_key.size(), private_key.data(), private_key.size()); + return keypair.Deserialize(serialized_keypair); +} + +class DeviceAttestationCredsCC13X2_26X2 : public DeviceAttestationCredentialsProvider +{ + +public: + CHIP_ERROR GetCertificationDeclaration(MutableByteSpan & out_buffer) override; + CHIP_ERROR GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) override; + CHIP_ERROR GetDeviceAttestationCert(MutableByteSpan & out_buffer) override; + CHIP_ERROR GetProductAttestationIntermediateCert(MutableByteSpan & out_buffer) override; + CHIP_ERROR SignWithDeviceAttestationKey(const ByteSpan & message_to_sign, MutableByteSpan & out_buffer) override; + +private: + factoryData const * mFactoryData = &gFactoryData; +}; + +CHIP_ERROR DeviceAttestationCredsCC13X2_26X2::GetCertificationDeclaration(MutableByteSpan & out_buffer) +{ + //-> format_version = 1 + //-> vendor_id = 0xFFF1 + //-> product_id_array = [ 0x8000, 0x8001, 0x8002, 0x8003, 0x8004, 0x8005, 0x8006, 0x8007, 0x8008, 0x8009, 0x800A, 0x800B, + // 0x800C, 0x800D, 0x800E, 0x800F, 0x8010, 0x8011, 0x8012, 0x8013, 0x8014, 0x8015, 0x8016, 0x8017, 0x8018, 0x8019, 0x801A, + // 0x801B, 0x801C, 0x801D, 0x801E, 0x801F, 0x8020, 0x8021, 0x8022, 0x8023, 0x8024, 0x8025, 0x8026, 0x8027, 0x8028, 0x8029, + // 0x802A, 0x802B, 0x802C, 0x802D, 0x802E, 0x802F, 0x8030, 0x8031, 0x8032, 0x8033, 0x8034, 0x8035, 0x8036, 0x8037, 0x8038, + // 0x8039, 0x803A, 0x803B, 0x803C, 0x803D, 0x803E, 0x803F, 0x8040, 0x8041, 0x8042, 0x8043, 0x8044, 0x8045, 0x8046, 0x8047, + // 0x8048, 0x8049, 0x804A, 0x804B, 0x804C, 0x804D, 0x804E, 0x804F, 0x8050, 0x8051, 0x8052, 0x8053, 0x8054, 0x8055, 0x8056, + // 0x8057, 0x8058, 0x8059, 0x805A, 0x805B, 0x805C, 0x805D, 0x805E, 0x805F, 0x8060, 0x8061, 0x8062, 0x8063 ] + //-> device_type_id = 0x0016 + //-> certificate_id = "ZIG20142ZB330003-24" + //-> security_level = 0 + //-> security_information = 0 + //-> version_number = 0x2694 + //-> certification_type = 0 + //-> dac_origin_vendor_id is not present + //-> dac_origin_product_id is not present + static const uint8_t kCdForAllExamples[] = { + 0x30, 0x82, 0x02, 0x19, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, 0xa0, 0x82, 0x02, 0x0a, 0x30, + 0x82, 0x02, 0x06, 0x02, 0x01, 0x03, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x01, 0x30, 0x82, 0x01, 0x71, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x82, 0x01, 0x62, + 0x04, 0x82, 0x01, 0x5e, 0x15, 0x24, 0x00, 0x01, 0x25, 0x01, 0xf1, 0xff, 0x36, 0x02, 0x05, 0x00, 0x80, 0x05, 0x01, 0x80, + 0x05, 0x02, 0x80, 0x05, 0x03, 0x80, 0x05, 0x04, 0x80, 0x05, 0x05, 0x80, 0x05, 0x06, 0x80, 0x05, 0x07, 0x80, 0x05, 0x08, + 0x80, 0x05, 0x09, 0x80, 0x05, 0x0a, 0x80, 0x05, 0x0b, 0x80, 0x05, 0x0c, 0x80, 0x05, 0x0d, 0x80, 0x05, 0x0e, 0x80, 0x05, + 0x0f, 0x80, 0x05, 0x10, 0x80, 0x05, 0x11, 0x80, 0x05, 0x12, 0x80, 0x05, 0x13, 0x80, 0x05, 0x14, 0x80, 0x05, 0x15, 0x80, + 0x05, 0x16, 0x80, 0x05, 0x17, 0x80, 0x05, 0x18, 0x80, 0x05, 0x19, 0x80, 0x05, 0x1a, 0x80, 0x05, 0x1b, 0x80, 0x05, 0x1c, + 0x80, 0x05, 0x1d, 0x80, 0x05, 0x1e, 0x80, 0x05, 0x1f, 0x80, 0x05, 0x20, 0x80, 0x05, 0x21, 0x80, 0x05, 0x22, 0x80, 0x05, + 0x23, 0x80, 0x05, 0x24, 0x80, 0x05, 0x25, 0x80, 0x05, 0x26, 0x80, 0x05, 0x27, 0x80, 0x05, 0x28, 0x80, 0x05, 0x29, 0x80, + 0x05, 0x2a, 0x80, 0x05, 0x2b, 0x80, 0x05, 0x2c, 0x80, 0x05, 0x2d, 0x80, 0x05, 0x2e, 0x80, 0x05, 0x2f, 0x80, 0x05, 0x30, + 0x80, 0x05, 0x31, 0x80, 0x05, 0x32, 0x80, 0x05, 0x33, 0x80, 0x05, 0x34, 0x80, 0x05, 0x35, 0x80, 0x05, 0x36, 0x80, 0x05, + 0x37, 0x80, 0x05, 0x38, 0x80, 0x05, 0x39, 0x80, 0x05, 0x3a, 0x80, 0x05, 0x3b, 0x80, 0x05, 0x3c, 0x80, 0x05, 0x3d, 0x80, + 0x05, 0x3e, 0x80, 0x05, 0x3f, 0x80, 0x05, 0x40, 0x80, 0x05, 0x41, 0x80, 0x05, 0x42, 0x80, 0x05, 0x43, 0x80, 0x05, 0x44, + 0x80, 0x05, 0x45, 0x80, 0x05, 0x46, 0x80, 0x05, 0x47, 0x80, 0x05, 0x48, 0x80, 0x05, 0x49, 0x80, 0x05, 0x4a, 0x80, 0x05, + 0x4b, 0x80, 0x05, 0x4c, 0x80, 0x05, 0x4d, 0x80, 0x05, 0x4e, 0x80, 0x05, 0x4f, 0x80, 0x05, 0x50, 0x80, 0x05, 0x51, 0x80, + 0x05, 0x52, 0x80, 0x05, 0x53, 0x80, 0x05, 0x54, 0x80, 0x05, 0x55, 0x80, 0x05, 0x56, 0x80, 0x05, 0x57, 0x80, 0x05, 0x58, + 0x80, 0x05, 0x59, 0x80, 0x05, 0x5a, 0x80, 0x05, 0x5b, 0x80, 0x05, 0x5c, 0x80, 0x05, 0x5d, 0x80, 0x05, 0x5e, 0x80, 0x05, + 0x5f, 0x80, 0x05, 0x60, 0x80, 0x05, 0x61, 0x80, 0x05, 0x62, 0x80, 0x05, 0x63, 0x80, 0x18, 0x24, 0x03, 0x16, 0x2c, 0x04, + 0x13, 0x5a, 0x49, 0x47, 0x32, 0x30, 0x31, 0x34, 0x32, 0x5a, 0x42, 0x33, 0x33, 0x30, 0x30, 0x30, 0x33, 0x2d, 0x32, 0x34, + 0x24, 0x05, 0x00, 0x24, 0x06, 0x00, 0x25, 0x07, 0x94, 0x26, 0x24, 0x08, 0x00, 0x18, 0x31, 0x7d, 0x30, 0x7b, 0x02, 0x01, + 0x03, 0x80, 0x14, 0x62, 0xfa, 0x82, 0x33, 0x59, 0xac, 0xfa, 0xa9, 0x96, 0x3e, 0x1c, 0xfa, 0x14, 0x0a, 0xdd, 0xf5, 0x04, + 0xf3, 0x71, 0x60, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x0a, 0x06, 0x08, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x04, 0x47, 0x30, 0x45, 0x02, 0x20, 0x24, 0xe5, 0xd1, 0xf4, 0x7a, 0x7d, + 0x7b, 0x0d, 0x20, 0x6a, 0x26, 0xef, 0x69, 0x9b, 0x7c, 0x97, 0x57, 0xb7, 0x2d, 0x46, 0x90, 0x89, 0xde, 0x31, 0x92, 0xe6, + 0x78, 0xc7, 0x45, 0xe7, 0xf6, 0x0c, 0x02, 0x21, 0x00, 0xf8, 0xaa, 0x2f, 0xa7, 0x11, 0xfc, 0xb7, 0x9b, 0x97, 0xe3, 0x97, + 0xce, 0xda, 0x66, 0x7b, 0xae, 0x46, 0x4e, 0x2b, 0xd3, 0xff, 0xdf, 0xc3, 0xcc, 0xed, 0x7a, 0xa8, 0xca, 0x5f, 0x4c, 0x1a, + 0x7c, + }; + + return CopySpanToMutableSpan(ByteSpan{ kCdForAllExamples }, out_buffer); +} + +CHIP_ERROR DeviceAttestationCredsCC13X2_26X2::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) +{ + out_firmware_info_buffer.reduce_size(0); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceAttestationCredsCC13X2_26X2::GetDeviceAttestationCert(MutableByteSpan & out_buffer) +{ + ReturnErrorCodeIf(out_buffer.size() < mFactoryData->dac_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + ReturnErrorCodeIf(!mFactoryData->dac_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + + return CopySpanToMutableSpan(ByteSpan{ mFactoryData->dac_cert.data, mFactoryData->dac_cert.len }, out_buffer); +} + +CHIP_ERROR DeviceAttestationCredsCC13X2_26X2::GetProductAttestationIntermediateCert(MutableByteSpan & out_buffer) +{ + ReturnErrorCodeIf(out_buffer.size() < mFactoryData->pai_cert.len, CHIP_ERROR_BUFFER_TOO_SMALL); + ReturnErrorCodeIf(!mFactoryData->pai_cert.data, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + + return CopySpanToMutableSpan(ByteSpan{ mFactoryData->pai_cert.data, mFactoryData->pai_cert.len }, out_buffer); +} + +CHIP_ERROR DeviceAttestationCredsCC13X2_26X2::SignWithDeviceAttestationKey(const ByteSpan & message_to_sign, + MutableByteSpan & out_buffer) +{ + Crypto::P256ECDSASignature signature; + Crypto::P256Keypair keypair; + + VerifyOrReturnError(IsSpanUsable(out_buffer), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(IsSpanUsable(message_to_sign), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(out_buffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); + + // In a non-exemplary implementation, the public key is not needed here. It is used here merely because + // Crypto::P256Keypair is only (currently) constructable from raw keys if both private/public keys are present. + ReturnErrorOnFailure(LoadKeypairFromRaw(ByteSpan(mFactoryData->dac_priv_key.data, mFactoryData->dac_priv_key.len), + ByteSpan(mFactoryData->dac_pub_key.data, mFactoryData->dac_pub_key.len), keypair)); + ReturnErrorOnFailure(keypair.ECDSA_sign_msg(message_to_sign.data(), message_to_sign.size(), signature)); + + return CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, out_buffer); +} + +} // namespace + +DeviceAttestationCredentialsProvider * GetCC13X2_26X2DacProvider() +{ + static DeviceAttestationCredsCC13X2_26X2 dac_provider; + return &dac_provider; +} + +} // namespace CC13X2_26X2 +} // namespace Credentials +} // namespace chip diff --git a/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.h b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.h new file mode 100644 index 00000000000000..37edd157a228ce --- /dev/null +++ b/examples/platform/cc13x2_26x2/CC13X2_26X2DeviceAttestationCreds.h @@ -0,0 +1,36 @@ +/* + * + * 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. + */ +#pragma once + +#include + +namespace chip { +namespace Credentials { +namespace CC13X2_26X2 { + +/** + * @brief Get implementation of a sample DAC provider to validate device + * attestation procedure. + * + * @returns a singleton DeviceAttestationCredentialsProvider that relies on no + * storage abstractions. + */ +DeviceAttestationCredentialsProvider * GetCC13X2_26X2DacProvider(); + +} // namespace CC13X2_26X2 +} // namespace Credentials +} // namespace chip diff --git a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn index 00bd404700ccba..7eadbc73e8c4a9 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn +++ b/examples/pump-app/cc13x2x7_26x2x7/BUILD.gn @@ -85,6 +85,7 @@ ti_simplelink_executable("pump_app") { deps = [ ":sdk", ":sysconfig", + "${chip_root}/examples/platform/cc13x2_26x2:cc13x2_26x2-attestation-credentials", "${chip_root}/examples/pump-app/pump-common", "${chip_root}/src/lib", ] diff --git a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp index ec04f66a5216f1..62a5e436a58310 100644 --- a/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp +++ b/examples/pump-app/cc13x2x7_26x2x7/main/AppTask.cpp @@ -26,12 +26,12 @@ #include #include "FreeRTOS.h" -#include -#include - #include #include #include +#include +#include +#include #if defined(CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR) #include @@ -221,8 +221,12 @@ int AppTask::Init() (void) initParams.InitializeStaticResourcesBeforeServerInit(); chip::Server::GetInstance().Init(initParams); - // Initialize device attestation config +// Initialize device attestation config +#ifdef CC13X2_26X2_ATTESTATION_CREDENTIALS + SetDeviceAttestationCredentialsProvider(CC13X2_26X2::GetCC13X2_26X2DacProvider()); +#else SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider()); +#endif ConfigurationMgr().LogDeviceConfig(); diff --git a/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp b/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp index 9a9ea2dcd1268a..70abc0fc6f6812 100644 --- a/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp +++ b/src/platform/cc13x2_26x2/CC13X2_26X2Config.cpp @@ -44,61 +44,89 @@ namespace Internal { /* itemID and subID are limited to 10 bits, even though their types are uint16_t */ // Keys stored in the Chip-factory namespace -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SerialNum = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0001 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceId = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0002 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceCert = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0003 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceICACerts = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0004 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDevicePrivateKey = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0005 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_HardwareVersion = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0006 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ManufacturingDate = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0007 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupPinCode = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0008 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupDiscriminator = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x0009 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pIterationCount = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x000a } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pSalt = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x000b } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pVerifier = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x000c } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_BootCount = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x000d } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_TotalOperationalHours = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x000f } }; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SerialNum = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0001 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceId = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0002 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceCert = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0003 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDeviceICACerts = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0004 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_MfrDevicePrivateKey = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0005 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_HardwareVersion = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0006 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ManufacturingDate = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0007 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupPinCode = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0008 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_SetupDiscriminator = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0009 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pIterationCount = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000a } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pSalt = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000b } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_Spake2pVerifier = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x000c } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_LifeTimeCounter = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipFactory, .subID = 0x0010 } +}; + +// Keys stored in the Chip-counters namespace +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_BootCount = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipCounters, .subID = 0x000d } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_TotalOperationalHours = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipCounters, .subID = 0x000f } +}; // Keys stored in the Chip-config namespace -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceConfig = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0012 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_PairedAccountId = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0013 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceId = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0014 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_LastUsedEpochKeyId = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0017 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_FailSafeArmed = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0018 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_WiFiStationSecType = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x0019 } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_RegulatoryLocation = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x001a } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_CountryCode = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x001b } }; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceConfig = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0012 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_PairedAccountId = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0013 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_ServiceId = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0014 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_LastUsedEpochKeyId = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00017 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_FailSafeArmed = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00018 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_WiFiStationSecType = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x00019 } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_RegulatoryLocation = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001a } +}; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_CountryCode = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001b } +}; // itemID 0x001c is unused (used to be breadcrumb). -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_UniqueId = { { .systemID = kCC13X2_26X2ChipConfig_Sysid, - .itemID = 0x001d } }; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_UniqueId = { + { .systemID = kCC13X2_26X2Matter_SysID, .itemID = kCC13X2_26X2Matter_ItemID_ChipConfig, .subID = 0x0001d } +}; /* Internal for the KVS interface. */ -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_key = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x001d } }; -const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_value = { { .systemID = kCC13X2_26X2ChipFactory_Sysid, - .itemID = 0x001e } }; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_key = { { .systemID = kCC13X2_26X2Matter_SysID, + .itemID = kCC13X2_26X2Matter_ItemID_ChipKVS_key } }; +const CC13X2_26X2Config::Key CC13X2_26X2Config::kConfigKey_KVS_value = { { .systemID = kCC13X2_26X2Matter_SysID, + .itemID = kCC13X2_26X2Matter_ItemID_ChipKVS_value } }; /* Static local variables */ static NVINTF_nvFuncts_t sNvoctpFps = { 0 }; @@ -389,43 +417,62 @@ CHIP_ERROR CC13X2_26X2Config::FactoryResetConfig(void) NVINTF_nvProxy_t nvProxy = { 0 }; uint8_t status = NVINTF_SUCCESS; + // Delete items with the config, counter, kvs_key and kvs_value itemIDs. Items with the factory + // itemIDs are not deleted. + intptr_t key = sNvoctpFps.lockNV(); /* Setup doNext call */ - nvProxy.sysid = kCC13X2_26X2ChipConfig_Sysid; - nvProxy.flag = NVINTF_DOSTART | NVINTF_DOSYSID | NVINTF_DODELETE; + nvProxy.sysid = kCC13X2_26X2Matter_SysID; + nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipConfig; + nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; - /* Lock and wipe all items with sysid TIOP */ + /* Lock and wipe all items with config itemid */ do { status = sNvoctpFps.doNext(&nvProxy); } while (NVINTF_SUCCESS == status); /* check we ran out of elements */ - VerifyOrExit(status != NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); - /* Setup doNext call. Sysid is the same here, but it doesn't necessarily have to be. Matching POSIX impl */ - nvProxy.sysid = kCC13X2_26X2ChipFactory_Sysid; - nvProxy.flag = NVINTF_DOSTART | NVINTF_DOSYSID | NVINTF_DODELETE; + /* Setup doNext call */ + nvProxy.sysid = kCC13X2_26X2Matter_SysID; + nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipCounters; + nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; - /* Lock and wipe all items with sysid TIOP */ + /* Lock and wipe all items with counters itemid */ do { status = sNvoctpFps.doNext(&nvProxy); } while (NVINTF_SUCCESS == status); /* check we ran out of elements */ - VerifyOrExit(status != NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + /* Setup doNext call */ + nvProxy.sysid = kCC13X2_26X2Matter_SysID; + nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipKVS_key; + nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; - /* Setup doNext call. Sysid is the same here, but it doesn't necessarily have to be. Matching POSIX impl */ - nvProxy.sysid = kCC13X2_26X2ChipCounters_Sysid; - nvProxy.flag = NVINTF_DOSTART | NVINTF_DOSYSID | NVINTF_DODELETE; + /* Lock and wipe all items with kvs_key itemid */ + do + { + status = sNvoctpFps.doNext(&nvProxy); + } while (NVINTF_SUCCESS == status); + /* check we ran out of elements */ + VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + + /* Setup doNext call */ + nvProxy.sysid = kCC13X2_26X2Matter_SysID; + nvProxy.itemid = kCC13X2_26X2Matter_ItemID_ChipKVS_value; + nvProxy.flag = NVINTF_DOSTART | NVINTF_DOITMID | NVINTF_DODELETE; - /* Lock and wipe all items with sysid TIOP */ + /* Lock and wipe all items with key_value itemid */ do { status = sNvoctpFps.doNext(&nvProxy); } while (NVINTF_SUCCESS == status); /* check we ran out of elements */ - VerifyOrExit(status != NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); + VerifyOrExit(status == NVINTF_NOTFOUND, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); exit: sNvoctpFps.unlockNV(key); diff --git a/src/platform/cc13x2_26x2/CC13X2_26X2Config.h b/src/platform/cc13x2_26x2/CC13X2_26X2Config.h index 1c4bbfd5059256..f3e8191aeca011 100644 --- a/src/platform/cc13x2_26x2/CC13X2_26X2Config.h +++ b/src/platform/cc13x2_26x2/CC13X2_26X2Config.h @@ -38,11 +38,21 @@ class CC13X2_26X2Config struct Key; // TODO: Define a proper system ID in upstream driver - static constexpr uint16_t kNvinf_sysid_chip = (13); + static constexpr uint16_t kNvinf_sysid_chip = 13; - static const uint16_t kCC13X2_26X2ChipConfig_Sysid = kNvinf_sysid_chip; - static const uint16_t kCC13X2_26X2ChipFactory_Sysid = kNvinf_sysid_chip; - static const uint16_t kCC13X2_26X2ChipCounters_Sysid = kNvinf_sysid_chip; + static constexpr uint16_t kNVinf_itemid_chipConfig = 1; + static constexpr uint16_t kNVinf_itemid_chipFactory = 2; + static constexpr uint16_t kNVinf_itemid_chipCounters = 3; + static constexpr uint16_t kNVinf_itemid_chipKVS_key = 4; + static constexpr uint16_t kNVinf_itemid_chipKVS_value = 5; + + static const uint16_t kCC13X2_26X2Matter_SysID = kNvinf_sysid_chip; + + static const uint16_t kCC13X2_26X2Matter_ItemID_ChipConfig = kNVinf_itemid_chipConfig; + static const uint16_t kCC13X2_26X2Matter_ItemID_ChipFactory = kNVinf_itemid_chipFactory; + static const uint16_t kCC13X2_26X2Matter_ItemID_ChipCounters = kNVinf_itemid_chipCounters; + static const uint16_t kCC13X2_26X2Matter_ItemID_ChipKVS_key = kNVinf_itemid_chipKVS_key; + static const uint16_t kCC13X2_26X2Matter_ItemID_ChipKVS_value = kNVinf_itemid_chipKVS_value; // Key definitions for well-known keys. static const Key kConfigKey_SerialNum; @@ -70,6 +80,7 @@ class CC13X2_26X2Config static const Key kConfigKey_Spake2pVerifier; static const Key kConfigKey_BootCount; static const Key kConfigKey_TotalOperationalHours; + static const Key kConfigKey_LifeTimeCounter; static CHIP_ERROR Init(void); diff --git a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp b/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp index 91b6e42f4d4991..7d420bab1c93e2 100644 --- a/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp +++ b/src/platform/cc13x2_26x2/ConfigurationManagerImpl.cpp @@ -126,7 +126,7 @@ CHIP_ERROR ConfigurationManagerImpl::StoreTotalOperationalHours(uint32_t totalOp CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) { - CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2ChipCounters_Sysid, key } }; + CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2Matter_SysID, key } }; CHIP_ERROR err = ReadConfigValue(configKey, value); if (err == CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND) @@ -138,7 +138,7 @@ CHIP_ERROR ConfigurationManagerImpl::ReadPersistedStorageValue(::chip::Platform: CHIP_ERROR ConfigurationManagerImpl::WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) { - CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2ChipCounters_Sysid, key } }; + CC13X2_26X2Config::Key configKey{ { CC13X2_26X2Config::kCC13X2_26X2Matter_SysID, key } }; return WriteConfigValue(configKey, value); } From 1dd65205d98ea99b39f8cf09bd7162e00b959fd3 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 4 Jan 2023 19:50:03 +0100 Subject: [PATCH 15/31] [chip-tool] Add delay commands module to chip-tool with busy-wait command (#24063) Co-authored-by: Andrei Litvin --- examples/chip-tool/BUILD.gn | 1 + examples/chip-tool/commands/delay/Commands.h | 32 +++++++++++ .../chip-tool/commands/delay/SleepCommand.cpp | 28 ++++++++++ .../chip-tool/commands/delay/SleepCommand.h | 54 +++++++++++++++++++ examples/chip-tool/main.cpp | 2 + 5 files changed, 117 insertions(+) create mode 100644 examples/chip-tool/commands/delay/Commands.h create mode 100644 examples/chip-tool/commands/delay/SleepCommand.cpp create mode 100644 examples/chip-tool/commands/delay/SleepCommand.h diff --git a/examples/chip-tool/BUILD.gn b/examples/chip-tool/BUILD.gn index 86e003a69201c4..4b2a0cee169cb6 100644 --- a/examples/chip-tool/BUILD.gn +++ b/examples/chip-tool/BUILD.gn @@ -59,6 +59,7 @@ static_library("chip-tool-utils") { "commands/common/Commands.h", "commands/common/CredentialIssuerCommands.h", "commands/common/HexConversion.h", + "commands/delay/SleepCommand.cpp", "commands/discover/DiscoverCommand.cpp", "commands/discover/DiscoverCommissionablesCommand.cpp", "commands/discover/DiscoverCommissionersCommand.cpp", diff --git a/examples/chip-tool/commands/delay/Commands.h b/examples/chip-tool/commands/delay/Commands.h new file mode 100644 index 00000000000000..337de3b14d217a --- /dev/null +++ b/examples/chip-tool/commands/delay/Commands.h @@ -0,0 +1,32 @@ +/* + * 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. + * + */ + +#pragma once + +#include "commands/common/Commands.h" +#include "commands/delay/SleepCommand.h" + +void registerCommandsDelay(Commands & commands, CredentialIssuerCommands * credsIssuerConfig) +{ + const char * clusterName = "Delay"; + commands_list clusterCommands = { + make_unique(credsIssuerConfig), // + }; + + commands.Register(clusterName, clusterCommands); +} diff --git a/examples/chip-tool/commands/delay/SleepCommand.cpp b/examples/chip-tool/commands/delay/SleepCommand.cpp new file mode 100644 index 00000000000000..de1db49b4b3f5f --- /dev/null +++ b/examples/chip-tool/commands/delay/SleepCommand.cpp @@ -0,0 +1,28 @@ +/* + * 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 "SleepCommand.h" +#include +#include + +CHIP_ERROR SleepCommand::RunCommand() +{ + std::this_thread::sleep_for(std::chrono::milliseconds(mDurationInMs)); + SetCommandExitStatus(CHIP_NO_ERROR); + return CHIP_NO_ERROR; +} diff --git a/examples/chip-tool/commands/delay/SleepCommand.h b/examples/chip-tool/commands/delay/SleepCommand.h new file mode 100644 index 00000000000000..aa1cddcbf94be8 --- /dev/null +++ b/examples/chip-tool/commands/delay/SleepCommand.h @@ -0,0 +1,54 @@ +/* + * 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. + * + */ + +#pragma once + +#include "../common/CHIPCommand.h" + +/** + * This command blocks the event loop processing for a given amount of time. + * + * For example when the event loop is blocked the messages coming-in will not be acked, + * forcing a retransmission on the other side. + * + */ + +class SleepCommand : public CHIPCommand +{ +public: + SleepCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("sleep", credIssuerCommands) + { + AddArgument("duration-in-ms", 0, UINT32_MAX, &mDurationInMs, + "Block the event loop processing for duration-in-ms milliseconds."); + } + + /////////// CHIPCommand Interface ///////// + CHIP_ERROR RunCommand() override; + chip::System::Clock::Timeout GetWaitDuration() const override + { + // The allowed duration of this method is at least as long as the time specified for blocking the + // event loop. In order to not fail on some small delays in processing some extra time before + // failing is added. + constexpr uint16_t mExtraTimeForFailure = 1000; + + return chip::System::Clock::Milliseconds32(mDurationInMs + mExtraTimeForFailure); + } + +private: + uint32_t mDurationInMs; +}; diff --git a/examples/chip-tool/main.cpp b/examples/chip-tool/main.cpp index c9a391b25e5f98..0ca5b243c9243e 100644 --- a/examples/chip-tool/main.cpp +++ b/examples/chip-tool/main.cpp @@ -19,6 +19,7 @@ #include "commands/common/Commands.h" #include "commands/example/ExampleCredentialIssuerCommands.h" +#include "commands/delay/Commands.h" #include "commands/discover/Commands.h" #include "commands/group/Commands.h" #include "commands/interactive/Commands.h" @@ -36,6 +37,7 @@ int main(int argc, char * argv[]) { ExampleCredentialIssuerCommands credIssuerCommands; Commands commands; + registerCommandsDelay(commands, &credIssuerCommands); registerCommandsDiscover(commands, &credIssuerCommands); registerCommandsInteractive(commands, &credIssuerCommands); registerCommandsPayload(commands); From b921798bc8b791047b418dfe3061dec9f2c8b00a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 4 Jan 2023 15:08:58 -0500 Subject: [PATCH 16/31] Bump third_party/mbedtls/repo from `0e0793f` to `a6ad7f4` (#24204) Bumps [third_party/mbedtls/repo](https://github.com/ARMmbed/mbedtls) from `0e0793f` to `a6ad7f4`. - [Release notes](https://github.com/ARMmbed/mbedtls/releases) - [Commits](https://github.com/ARMmbed/mbedtls/compare/0e0793f4acffee35bbb2764fa58f63d9e2693e4e...a6ad7f47023b235fc8d02c3f2bbb5d5277c2f20f) --- updated-dependencies: - dependency-name: third_party/mbedtls/repo dependency-type: direct:production ... Signed-off-by: dependabot[bot] Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- third_party/mbedtls/repo | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/mbedtls/repo b/third_party/mbedtls/repo index 0e0793f4acffee..a6ad7f47023b23 160000 --- a/third_party/mbedtls/repo +++ b/third_party/mbedtls/repo @@ -1 +1 @@ -Subproject commit 0e0793f4acffee35bbb2764fa58f63d9e2693e4e +Subproject commit a6ad7f47023b235fc8d02c3f2bbb5d5277c2f20f From 715a2bc64bf6491005c775ab0a12ee6511a5a18a Mon Sep 17 00:00:00 2001 From: C Freeman Date: Wed, 4 Jan 2023 16:16:07 -0500 Subject: [PATCH 17/31] Remove GroupKeyMap entries for removed KeySet (#23864) * Remove GroupKeyMap entries for removed KeySet Per Core spec 11.2.9.4, If there exist any entries for the accessing fabric within the GroupKeyMap attribute that refer to the GroupKeySetID just removed, then these entries SHALL be removed from that list. Fixes #23862 * Restyled by clang-format * Restyled by prettier-yaml * Update src/credentials/GroupDataProviderImpl.cpp Co-authored-by: Boris Zbarsky Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky --- .../suites/TestGroupKeyManagementCluster.yaml | 74 +++++ src/credentials/GroupDataProviderImpl.cpp | 51 +++- .../chip-tool/zap-generated/test/Commands.h | 174 ++++++++++- .../zap-generated/test/Commands.h | 286 +++++++++++++++++- 4 files changed, 582 insertions(+), 3 deletions(-) diff --git a/src/app/tests/suites/TestGroupKeyManagementCluster.yaml b/src/app/tests/suites/TestGroupKeyManagementCluster.yaml index f388434370cb6a..62fbfe4e1cb7c4 100644 --- a/src/app/tests/suites/TestGroupKeyManagementCluster.yaml +++ b/src/app/tests/suites/TestGroupKeyManagementCluster.yaml @@ -295,3 +295,77 @@ tests: value: 0x01a2 response: error: NOT_FOUND + + - label: "KeySet Write 1" + command: "KeySetWrite" + arguments: + values: + - name: "GroupKeySet" + value: + { + GroupKeySetID: 0x01a1, + GroupKeySecurityPolicy: 0, + EpochKey0: "\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf", + EpochStartTime0: 1110000, + EpochKey1: "\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf", + EpochStartTime1: 1110001, + EpochKey2: "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf", + EpochStartTime2: 1110002, + } + + - label: "KeySet Write 2" + command: "KeySetWrite" + arguments: + values: + - name: "GroupKeySet" + value: + { + GroupKeySetID: 0x01a2, + GroupKeySecurityPolicy: 1, + EpochKey0: "\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf", + EpochStartTime0: 2110000, + EpochKey1: "\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef", + EpochStartTime1: 2110001, + EpochKey2: "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", + EpochStartTime2: 2110002, + } + + - label: "Map Group 1 and Group 2 to KeySet 1 and group 2 to KeySet 2" + command: "writeAttribute" + attribute: "GroupKeyMap" + arguments: + value: + [ + { FabricIndex: 1, GroupId: 0x0101, GroupKeySetID: 0x01a1 }, + { FabricIndex: 1, GroupId: 0x0102, GroupKeySetID: 0x01a2 }, + { FabricIndex: 1, GroupId: 0x0102, GroupKeySetID: 0x01a1 }, + ] + + - label: "Remove keyset 1" + command: "KeySetRemove" + arguments: + values: + - name: "GroupKeySetID" + value: 0x01a1 + + - label: "TH verifies GroupKeyMap entries for KeySet 1 have been removed" + cluster: "Group Key Management" + endpoint: 0 + command: "readAttribute" + attribute: "GroupKeyMap" + response: + value: [{ FabricIndex: 1, GroupId: 0x0102, GroupKeySetID: 0x01a2 }] + - label: "Remove keyset 2" + command: "KeySetRemove" + arguments: + values: + - name: "GroupKeySetID" + value: 0x01a2 + + - label: "TH verifies GroupKeyMap entries for KeySet 2 have been removed" + cluster: "Group Key Management" + endpoint: 0 + command: "readAttribute" + attribute: "GroupKeyMap" + response: + value: [] diff --git a/src/credentials/GroupDataProviderImpl.cpp b/src/credentials/GroupDataProviderImpl.cpp index 95764967dab051..fde6cec2343ad8 100644 --- a/src/credentials/GroupDataProviderImpl.cpp +++ b/src/credentials/GroupDataProviderImpl.cpp @@ -503,6 +503,37 @@ struct KeyMapData : public GroupDataProvider::GroupKey, LinkedData id = static_cast(max_id + 1); return false; } + + // returns index if the find_id is found, otherwise std::numeric_limits::max + size_t Find(PersistentStorageDelegate * storage, const FabricData & fabric, const KeysetId find_id) + { + fabric_index = fabric.fabric_index; + id = fabric.first_map; + max_id = 0; + index = 0; + first = true; + + while (index < fabric.map_count) + { + if (CHIP_NO_ERROR != Load(storage)) + { + break; + } + if (keyset_id == find_id) + { + // Match found + return index; + } + max_id = std::max(id, max_id); + first = false; + prev = id; + id = next; + index++; + } + + id = static_cast(max_id + 1); + return std::numeric_limits::max(); + } }; struct EndpointData : GroupDataProvider::GroupEndpoint, PersistentData @@ -1574,7 +1605,25 @@ CHIP_ERROR GroupDataProviderImpl::RemoveKeySet(chip::FabricIndex fabric_index, u fabric.keyset_count--; } // Update fabric info - return fabric.Save(mStorage); + ReturnErrorOnFailure(fabric.Save(mStorage)); + + // Removing a key set also removes the associated group mappings + KeyMapData map; + uint16_t original_count = fabric.map_count; + for (uint16_t i = 0; i < original_count; ++i) + { + fabric.Load(mStorage); + size_t idx = map.Find(mStorage, fabric, target_id); + if (idx == std::numeric_limits::max()) + { + break; + } + // NOTE: It's unclear what should happen here if we have removed the key set + // and possibly some mappings before failing. For now, ignoring errors, but + // open to suggestsions for the correct behavior. + RemoveGroupKeyAt(fabric_index, idx); + } + return CHIP_NO_ERROR; } GroupDataProvider::KeySetIterator * GroupDataProviderImpl::IterateKeySets(chip::FabricIndex fabric_index) diff --git a/zzz_generated/chip-tool/zap-generated/test/Commands.h b/zzz_generated/chip-tool/zap-generated/test/Commands.h index d6f7eef25da072..a4c3223b511588 100644 --- a/zzz_generated/chip-tool/zap-generated/test/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/test/Commands.h @@ -78695,7 +78695,7 @@ class TestGroupKeyManagementClusterSuite : public TestCommand { public: TestGroupKeyManagementClusterSuite(CredentialIssuerCommands * credsIssuerConfig) : - TestCommand("TestGroupKeyManagementCluster", 22, credsIssuerConfig) + TestCommand("TestGroupKeyManagementCluster", 29, credsIssuerConfig) { AddArgument("nodeId", 0, UINT64_MAX, &mNodeId); AddArgument("cluster", &mCluster); @@ -78929,6 +78929,51 @@ class TestGroupKeyManagementClusterSuite : public TestCommand case 21: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), EMBER_ZCL_STATUS_NOT_FOUND)); break; + case 22: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 23: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 24: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 25: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 26: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::app::DataModel::DecodableList< + chip::app::Clusters::GroupKeyManagement::Structs::GroupKeyMapStruct::DecodableType> + value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + { + auto iter_0 = value.begin(); + VerifyOrReturn(CheckNextListItemDecodes("groupKeyMap", iter_0, 0)); + VerifyOrReturn(CheckValue("groupKeyMap[0].groupId", iter_0.GetValue().groupId, 258U)); + VerifyOrReturn(CheckValue("groupKeyMap[0].groupKeySetID", iter_0.GetValue().groupKeySetID, 418U)); + VerifyOrReturn(CheckValue("groupKeyMap[0].fabricIndex", iter_0.GetValue().fabricIndex, 1U)); + VerifyOrReturn(CheckNoMoreListItems("groupKeyMap", iter_0, 1)); + } + } + break; + case 27: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 28: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + { + chip::app::DataModel::DecodableList< + chip::app::Clusters::GroupKeyManagement::Structs::GroupKeyMapStruct::DecodableType> + value; + VerifyOrReturn(CheckDecodeValue(chip::app::DataModel::Decode(*data, value))); + { + auto iter_0 = value.begin(); + VerifyOrReturn(CheckNoMoreListItems("groupKeyMap", iter_0, 0)); + } + } + break; default: LogErrorOnFailure(ContinueOnChipMainThread(CHIP_ERROR_INVALID_ARGUMENT)); } @@ -79227,6 +79272,133 @@ class TestGroupKeyManagementClusterSuite : public TestCommand ); } + case 22: { + LogStep(22, "KeySet Write 1"); + ListFreer listFreer; + chip::app::Clusters::GroupKeyManagement::Commands::KeySetWrite::Type value; + + value.groupKeySet.groupKeySetID = 417U; + value.groupKeySet.groupKeySecurityPolicy = + static_cast(0); + value.groupKeySet.epochKey0.SetNonNull(); + value.groupKeySet.epochKey0.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime0.SetNonNull(); + value.groupKeySet.epochStartTime0.Value() = 1110000ULL; + value.groupKeySet.epochKey1.SetNonNull(); + value.groupKeySet.epochKey1.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime1.SetNonNull(); + value.groupKeySet.epochStartTime1.Value() = 1110001ULL; + value.groupKeySet.epochKey2.SetNonNull(); + value.groupKeySet.epochKey2.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime2.SetNonNull(); + value.groupKeySet.epochStartTime2.Value() = 1110002ULL; + + return SendCommand(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Commands::KeySetWrite::Id, value, chip::NullOptional + + ); + } + case 23: { + LogStep(23, "KeySet Write 2"); + ListFreer listFreer; + chip::app::Clusters::GroupKeyManagement::Commands::KeySetWrite::Type value; + + value.groupKeySet.groupKeySetID = 418U; + value.groupKeySet.groupKeySecurityPolicy = + static_cast(1); + value.groupKeySet.epochKey0.SetNonNull(); + value.groupKeySet.epochKey0.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime0.SetNonNull(); + value.groupKeySet.epochStartTime0.Value() = 2110000ULL; + value.groupKeySet.epochKey1.SetNonNull(); + value.groupKeySet.epochKey1.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime1.SetNonNull(); + value.groupKeySet.epochStartTime1.Value() = 2110001ULL; + value.groupKeySet.epochKey2.SetNonNull(); + value.groupKeySet.epochKey2.Value() = chip::ByteSpan( + chip::Uint8::from_const_char( + "\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377garbage: not in length on purpose"), + 16); + value.groupKeySet.epochStartTime2.SetNonNull(); + value.groupKeySet.epochStartTime2.Value() = 2110002ULL; + + return SendCommand(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Commands::KeySetWrite::Id, value, chip::NullOptional + + ); + } + case 24: { + LogStep(24, "Map Group 1 and Group 2 to KeySet 1 and group 2 to KeySet 2"); + ListFreer listFreer; + chip::app::DataModel::List value; + + { + auto * listHolder_0 = new ListHolder(3); + listFreer.add(listHolder_0); + + listHolder_0->mList[0].groupId = 257U; + listHolder_0->mList[0].groupKeySetID = 417U; + listHolder_0->mList[0].fabricIndex = 1U; + + listHolder_0->mList[1].groupId = 258U; + listHolder_0->mList[1].groupKeySetID = 418U; + listHolder_0->mList[1].fabricIndex = 1U; + + listHolder_0->mList[2].groupId = 258U; + listHolder_0->mList[2].groupKeySetID = 417U; + listHolder_0->mList[2].fabricIndex = 1U; + + value = chip::app::DataModel::List( + listHolder_0->mList, 3); + } + return WriteAttribute(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Attributes::GroupKeyMap::Id, value, chip::NullOptional, chip::NullOptional); + } + case 25: { + LogStep(25, "Remove keyset 1"); + ListFreer listFreer; + chip::app::Clusters::GroupKeyManagement::Commands::KeySetRemove::Type value; + value.groupKeySetID = 417U; + return SendCommand(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Commands::KeySetRemove::Id, value, chip::NullOptional + + ); + } + case 26: { + LogStep(26, "TH verifies GroupKeyMap entries for KeySet 1 have been removed"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Attributes::GroupKeyMap::Id, true, chip::NullOptional); + } + case 27: { + LogStep(27, "Remove keyset 2"); + ListFreer listFreer; + chip::app::Clusters::GroupKeyManagement::Commands::KeySetRemove::Type value; + value.groupKeySetID = 418U; + return SendCommand(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Commands::KeySetRemove::Id, value, chip::NullOptional + + ); + } + case 28: { + LogStep(28, "TH verifies GroupKeyMap entries for KeySet 2 have been removed"); + return ReadAttribute(kIdentityAlpha, GetEndpoint(0), GroupKeyManagement::Id, + GroupKeyManagement::Attributes::GroupKeyMap::Id, true, chip::NullOptional); + } } return CHIP_NO_ERROR; } diff --git a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h index 6e5987315647ea..896ae2a97537f1 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/test/Commands.h @@ -127760,6 +127760,34 @@ class TestGroupKeyManagementCluster : public TestCommandBridge { ChipLogProgress(chipTool, " ***** Test Step 21 : KeySet Read (also removed)\n"); err = TestKeySetReadAlsoRemoved_21(); break; + case 22: + ChipLogProgress(chipTool, " ***** Test Step 22 : KeySet Write 1\n"); + err = TestKeySetWrite1_22(); + break; + case 23: + ChipLogProgress(chipTool, " ***** Test Step 23 : KeySet Write 2\n"); + err = TestKeySetWrite2_23(); + break; + case 24: + ChipLogProgress(chipTool, " ***** Test Step 24 : Map Group 1 and Group 2 to KeySet 1 and group 2 to KeySet 2\n"); + err = TestMapGroup1AndGroup2ToKeySet1AndGroup2ToKeySet2_24(); + break; + case 25: + ChipLogProgress(chipTool, " ***** Test Step 25 : Remove keyset 1\n"); + err = TestRemoveKeyset1_25(); + break; + case 26: + ChipLogProgress(chipTool, " ***** Test Step 26 : TH verifies GroupKeyMap entries for KeySet 1 have been removed\n"); + err = TestThVerifiesGroupKeyMapEntriesForKeySet1HaveBeenRemoved_26(); + break; + case 27: + ChipLogProgress(chipTool, " ***** Test Step 27 : Remove keyset 2\n"); + err = TestRemoveKeyset2_27(); + break; + case 28: + ChipLogProgress(chipTool, " ***** Test Step 28 : TH verifies GroupKeyMap entries for KeySet 2 have been removed\n"); + err = TestThVerifiesGroupKeyMapEntriesForKeySet2HaveBeenRemoved_28(); + break; } if (CHIP_NO_ERROR != err) { @@ -127837,6 +127865,27 @@ class TestGroupKeyManagementCluster : public TestCommandBridge { case 21: VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), EMBER_ZCL_STATUS_NOT_FOUND)); break; + case 22: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 23: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 24: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 25: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 26: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 27: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; + case 28: + VerifyOrReturn(CheckValue("status", chip::to_underlying(status.mStatus), 0)); + break; } // Go on to the next test. @@ -127850,7 +127899,7 @@ class TestGroupKeyManagementCluster : public TestCommandBridge { private: std::atomic_uint16_t mTestIndex; - const uint16_t mTestCount = 22; + const uint16_t mTestCount = 29; chip::Optional mNodeId; chip::Optional mCluster; @@ -128594,6 +128643,241 @@ class TestGroupKeyManagementCluster : public TestCommandBridge { return CHIP_NO_ERROR; } + + CHIP_ERROR TestKeySetWrite1_22() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRGroupKeyManagementClusterKeySetWriteParams alloc] init]; + params.groupKeySet = [[MTRGroupKeyManagementClusterGroupKeySetStruct alloc] init]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).groupKeySetID = + [NSNumber numberWithUnsignedShort:417U]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).groupKeySecurityPolicy = + [NSNumber numberWithUnsignedChar:0U]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey0 = + [[NSData alloc] initWithBytes:"\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime0 = + [NSNumber numberWithUnsignedLongLong:1110000ULL]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey1 = + [[NSData alloc] initWithBytes:"\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime1 = + [NSNumber numberWithUnsignedLongLong:1110001ULL]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey2 = + [[NSData alloc] initWithBytes:"\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime2 = + [NSNumber numberWithUnsignedLongLong:1110002ULL]; + + [cluster keySetWriteWithParams:params + completion:^(NSError * _Nullable err) { + NSLog(@"KeySet Write 1 Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestKeySetWrite2_23() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRGroupKeyManagementClusterKeySetWriteParams alloc] init]; + params.groupKeySet = [[MTRGroupKeyManagementClusterGroupKeySetStruct alloc] init]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).groupKeySetID = + [NSNumber numberWithUnsignedShort:418U]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).groupKeySecurityPolicy = + [NSNumber numberWithUnsignedChar:1U]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey0 = + [[NSData alloc] initWithBytes:"\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime0 = + [NSNumber numberWithUnsignedLongLong:2110000ULL]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey1 = + [[NSData alloc] initWithBytes:"\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime1 = + [NSNumber numberWithUnsignedLongLong:2110001ULL]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochKey2 = + [[NSData alloc] initWithBytes:"\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377" length:16]; + ((MTRGroupKeyManagementClusterGroupKeySetStruct *) params.groupKeySet).epochStartTime2 = + [NSNumber numberWithUnsignedLongLong:2110002ULL]; + + [cluster keySetWriteWithParams:params + completion:^(NSError * _Nullable err) { + NSLog(@"KeySet Write 2 Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestMapGroup1AndGroup2ToKeySet1AndGroup2ToKeySet2_24() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + id groupKeyMapArgument; + { + NSMutableArray * temp_0 = [[NSMutableArray alloc] init]; + temp_0[0] = [[MTRGroupKeyManagementClusterGroupKeyMapStruct alloc] init]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[0]).groupId = [NSNumber numberWithUnsignedShort:257U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[0]).groupKeySetID = [NSNumber numberWithUnsignedShort:417U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[0]).fabricIndex = [NSNumber numberWithUnsignedChar:1U]; + + temp_0[1] = [[MTRGroupKeyManagementClusterGroupKeyMapStruct alloc] init]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[1]).groupId = [NSNumber numberWithUnsignedShort:258U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[1]).groupKeySetID = [NSNumber numberWithUnsignedShort:418U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[1]).fabricIndex = [NSNumber numberWithUnsignedChar:1U]; + + temp_0[2] = [[MTRGroupKeyManagementClusterGroupKeyMapStruct alloc] init]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[2]).groupId = [NSNumber numberWithUnsignedShort:258U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[2]).groupKeySetID = [NSNumber numberWithUnsignedShort:417U]; + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) temp_0[2]).fabricIndex = [NSNumber numberWithUnsignedChar:1U]; + + groupKeyMapArgument = temp_0; + } + [cluster writeAttributeGroupKeyMapWithValue:groupKeyMapArgument + completion:^(NSError * _Nullable err) { + NSLog(@"Map Group 1 and Group 2 to KeySet 1 and group 2 to KeySet 2 Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestRemoveKeyset1_25() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRGroupKeyManagementClusterKeySetRemoveParams alloc] init]; + params.groupKeySetID = [NSNumber numberWithUnsignedShort:417U]; + [cluster keySetRemoveWithParams:params + completion:^(NSError * _Nullable err) { + NSLog(@"Remove keyset 1 Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestThVerifiesGroupKeyMapEntriesForKeySet1HaveBeenRemoved_26() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRReadParams alloc] init]; + params.filterByFabric = true; + [cluster + readAttributeGroupKeyMapWithParams:params + completion:^(NSArray * _Nullable value, NSError * _Nullable err) { + NSLog(@"TH verifies GroupKeyMap entries for KeySet 1 have been removed Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + { + id actualValue = value; + VerifyOrReturn( + CheckValue("GroupKeyMap", [actualValue count], static_cast(1))); + VerifyOrReturn(CheckValue("GroupId", + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) actualValue[0]).groupId, 258U)); + VerifyOrReturn(CheckValue("GroupKeySetID", + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) actualValue[0]).groupKeySetID, + 418U)); + VerifyOrReturn(CheckValue("FabricIndex", + ((MTRGroupKeyManagementClusterGroupKeyMapStruct *) actualValue[0]).fabricIndex, + 1U)); + } + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestRemoveKeyset2_27() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRGroupKeyManagementClusterKeySetRemoveParams alloc] init]; + params.groupKeySetID = [NSNumber numberWithUnsignedShort:418U]; + [cluster keySetRemoveWithParams:params + completion:^(NSError * _Nullable err) { + NSLog(@"Remove keyset 2 Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } + + CHIP_ERROR TestThVerifiesGroupKeyMapEntriesForKeySet2HaveBeenRemoved_28() + { + + MTRBaseDevice * device = GetDevice("alpha"); + __auto_type * cluster = [[MTRBaseClusterGroupKeyManagement alloc] initWithDevice:device + endpointID:@(0) + queue:mCallbackQueue]; + VerifyOrReturnError(cluster != nil, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * params = [[MTRReadParams alloc] init]; + params.filterByFabric = true; + [cluster + readAttributeGroupKeyMapWithParams:params + completion:^(NSArray * _Nullable value, NSError * _Nullable err) { + NSLog(@"TH verifies GroupKeyMap entries for KeySet 2 have been removed Error: %@", err); + + VerifyOrReturn(CheckValue("status", err ? err.code : 0, 0)); + + { + id actualValue = value; + VerifyOrReturn( + CheckValue("GroupKeyMap", [actualValue count], static_cast(0))); + } + + NextTest(); + }]; + + return CHIP_NO_ERROR; + } }; class Test_TC_G_1_1 : public TestCommandBridge { From 5f3dda9473be2cfec9248006c50a61d4812de754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Kr=C3=B3lik?= <66667989+Damian-Nordic@users.noreply.github.com> Date: Wed, 4 Jan 2023 22:44:20 +0100 Subject: [PATCH 18/31] [tlv] Optimize code size of processing context tags (#24224) * [tlv] Encapsulate Tag encoding Make the internal representation of Tag private so that it is easier and safer to change it. Signed-off-by: Damian Krolik * [tlv] Optimize code size of processing context tags TLV tag is represented as uint64_t that encodes the following components: - 16-bit vendor ID - 16-bit profile number - 32-bit tag number Context tags, which account for vast majority of tag usage in the SDK, are encoded as having both vendor ID and profile number equal to 0xFFFF. Anonymous tags are encoded in the same way, but using 0xFFFFFFFF tag number. This is correct because vendor IDs higher than 0xFFF0 shall not be assigned to real manufacturers, but constructing 0xFF... constants in hundreds of places adds non-negligible overhead to the flash usage. Encode profile ID in the negated form internally to optimize the code size when using special tags. * Fix build * Code review Signed-off-by: Damian Krolik --- src/darwin/Framework/CHIP/MTRBaseDevice.mm | 7 +- src/lib/core/CHIPTLVReader.cpp | 6 +- src/lib/core/CHIPTLVTags.h | 152 +++++++++++++-------- src/lib/core/CHIPTLVWriter.cpp | 2 +- 4 files changed, 105 insertions(+), 62 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRBaseDevice.mm b/src/darwin/Framework/CHIP/MTRBaseDevice.mm index 7725c9ab6e1f1b..e8211845e91cae 100644 --- a/src/darwin/Framework/CHIP/MTRBaseDevice.mm +++ b/src/darwin/Framework/CHIP/MTRBaseDevice.mm @@ -1437,7 +1437,7 @@ + (id)CHIPEncodeAndDecodeNSObject:(id)object uint8_t buffer[1024]; writer.Init(buffer, sizeof(buffer)); - CHIP_ERROR error = originalData.Encode(writer, chip::TLV::Tag(1)); + CHIP_ERROR error = originalData.Encode(writer, chip::TLV::CommonTag(1)); if (error != CHIP_NO_ERROR) { MTR_LOG_ERROR("Error: Data encoding failed: %s", error.AsString()); return nil; @@ -1456,8 +1456,9 @@ + (id)CHIPEncodeAndDecodeNSObject:(id)object return nil; } __auto_type tag = reader.GetTag(); - if (tag != chip::TLV::Tag(1)) { - MTR_LOG_ERROR("Error: TLV reader did not read the tag correctly: %llu", tag.mVal); + if (tag != chip::TLV::CommonTag(1)) { + MTR_LOG_ERROR("Error: TLV reader did not read the tag correctly: %x.%u", chip::TLV::ProfileIdFromTag(tag), + chip::TLV::TagNumFromTag(tag)); return nil; } MTRDataValueDictionaryDecodableType decodedData; diff --git a/src/lib/core/CHIPTLVReader.cpp b/src/lib/core/CHIPTLVReader.cpp index 9a95a42779e9dc..5d175eb35b7108 100644 --- a/src/lib/core/CHIPTLVReader.cpp +++ b/src/lib/core/CHIPTLVReader.cpp @@ -749,7 +749,7 @@ CHIP_ERROR TLVReader::VerifyElement() } else { - if (mElemTag == UnknownImplicitTag) + if (mElemTag == UnknownImplicitTag()) return CHIP_ERROR_UNKNOWN_IMPLICIT_TLV_TAG; switch (mContainerType) { @@ -806,11 +806,11 @@ Tag TLVReader::ReadTag(TLVTagControl tagControl, const uint8_t *& p) const return CommonTag(LittleEndian::Read32(p)); case TLVTagControl::ImplicitProfile_2Bytes: if (ImplicitProfileId == kProfileIdNotSpecified) - return UnknownImplicitTag; + return UnknownImplicitTag(); return ProfileTag(ImplicitProfileId, LittleEndian::Read16(p)); case TLVTagControl::ImplicitProfile_4Bytes: if (ImplicitProfileId == kProfileIdNotSpecified) - return UnknownImplicitTag; + return UnknownImplicitTag(); return ProfileTag(ImplicitProfileId, LittleEndian::Read32(p)); case TLVTagControl::FullyQualified_6Bytes: vendorId = LittleEndian::Read16(p); diff --git a/src/lib/core/CHIPTLVTags.h b/src/lib/core/CHIPTLVTags.h index 12de1d9e3ef2e1..da8f91006fae48 100644 --- a/src/lib/core/CHIPTLVTags.h +++ b/src/lib/core/CHIPTLVTags.h @@ -29,12 +29,59 @@ namespace chip { namespace TLV { -struct Tag +class Tag { - explicit constexpr Tag(uint64_t val) : mVal(val) {} - Tag() {} +public: + enum SpecialTagNumber : uint32_t + { + kContextTagMaxNum = UINT8_MAX, + kAnonymousTagNum, + kUnknownImplicitTagNum + }; + + Tag() = default; + constexpr bool operator==(const Tag & other) const { return mVal == other.mVal; } constexpr bool operator!=(const Tag & other) const { return mVal != other.mVal; } + +private: + explicit constexpr Tag(uint64_t val) : mVal(val) {} + + friend constexpr Tag ProfileTag(uint32_t profileId, uint32_t tagNum); + friend constexpr Tag ProfileTag(uint16_t vendorId, uint16_t profileNum, uint32_t tagNum); + friend constexpr Tag ContextTag(uint8_t tagNum); + friend constexpr Tag CommonTag(uint32_t tagNum); + friend constexpr Tag AnonymousTag(); + friend constexpr Tag UnknownImplicitTag(); + + // The following friend functions could be Tag class methods, but it turns out in some cases + // they may not be inlined and then passing the tag by argument/value results in smaller code + // than passing it by 'this' pointer. This can be worked around by applying 'always_inline' + // function attribute, but friend functions are likely a more portable solution. + + friend constexpr uint32_t ProfileIdFromTag(Tag tag); + friend constexpr uint16_t VendorIdFromTag(Tag tag); + friend constexpr uint16_t ProfileNumFromTag(Tag tag); + friend constexpr uint32_t TagNumFromTag(Tag tag); + + friend constexpr bool IsProfileTag(Tag tag); + friend constexpr bool IsContextTag(Tag tag); + friend constexpr bool IsSpecialTag(Tag tag); + + static constexpr uint32_t kProfileIdShift = 32; + static constexpr uint32_t kVendorIdShift = 48; + static constexpr uint32_t kProfileNumShift = 32; + static constexpr uint32_t kSpecialTagProfileId = 0xFFFFFFFF; + + // The storage of the tag value uses the following encoding: + // + // 63 47 31 + // +-------------------------------+-------------------------------+----------------------------------------------+ + // | Vendor id (bitwise-negated) | Profile num (bitwise-negated) | Tag number | + // +-------------------------------+-------------------------------+----------------------------------------------+ + // + // Vendor id and profile number are bitwise-negated in order to optimize the code size when + // using context tags, the most commonly used tags in the SDK. uint64_t mVal; }; @@ -50,20 +97,6 @@ enum TLVCommonProfiles kCommonProfileId = 0 }; -// TODO: Move to private namespace -enum TLVTagFields -{ - kProfileIdMask = 0xFFFFFFFF00000000ULL, - kProfileNumMask = 0x0000FFFF00000000ULL, - kVendorIdMask = 0xFFFF000000000000ULL, - kProfileIdShift = 32, - kVendorIdShift = 48, - kProfileNumShift = 32, - kTagNumMask = 0x00000000FFFFFFFFULL, - kSpecialTagMarker = 0xFFFFFFFF00000000ULL, - kContextTagMaxNum = UINT8_MAX -}; - // TODO: Move to private namespace enum class TLVTagControl : uint8_t { @@ -99,9 +132,9 @@ enum * @param[in] tagNum The profile-specific tag number assigned to the tag. * @return A 64-bit integer representing the tag. */ -inline constexpr Tag ProfileTag(uint32_t profileId, uint32_t tagNum) +constexpr Tag ProfileTag(uint32_t profileId, uint32_t tagNum) { - return Tag(((static_cast(profileId)) << kProfileIdShift) | tagNum); + return Tag((static_cast(~profileId) << Tag::kProfileIdShift) | tagNum); } /** @@ -112,21 +145,22 @@ inline constexpr Tag ProfileTag(uint32_t profileId, uint32_t tagNum) * @param[in] tagNum The profile-specific tag number assigned to the tag. * @return A 64-bit integer representing the tag. */ -inline constexpr Tag ProfileTag(uint16_t vendorId, uint16_t profileNum, uint32_t tagNum) +constexpr Tag ProfileTag(uint16_t vendorId, uint16_t profileNum, uint32_t tagNum) { - return Tag(((static_cast(vendorId)) << kVendorIdShift) | ((static_cast(profileNum)) << kProfileNumShift) | - tagNum); + constexpr uint32_t kVendorIdShift = Tag::kVendorIdShift - Tag::kProfileIdShift; + + return ProfileTag((static_cast(vendorId) << kVendorIdShift) | profileNum, tagNum); } /** - * Generates the API representation for of context-specific TLV tag + * Generates the API representation of a context-specific TLV tag * * @param[in] tagNum The context-specific tag number assigned to the tag. * @return A 64-bit integer representing the tag. */ -inline constexpr Tag ContextTag(uint8_t tagNum) +constexpr Tag ContextTag(uint8_t tagNum) { - return Tag(kSpecialTagMarker | tagNum); + return ProfileTag(Tag::kSpecialTagProfileId, tagNum); } /** @@ -135,7 +169,7 @@ inline constexpr Tag ContextTag(uint8_t tagNum) * @param[in] tagNum The common profile tag number assigned to the tag. * @return A 64-bit integer representing the tag. */ -inline constexpr Tag CommonTag(uint32_t tagNum) +constexpr Tag CommonTag(uint32_t tagNum) { return ProfileTag(kCommonProfileId, tagNum); } @@ -143,12 +177,18 @@ inline constexpr Tag CommonTag(uint32_t tagNum) /** * A value signifying a TLV element that has no tag (i.e. an anonymous element). */ -inline constexpr Tag AnonymousTag() +constexpr Tag AnonymousTag() { - return Tag(kSpecialTagMarker | 0x00000000FFFFFFFFULL); + return ProfileTag(Tag::kSpecialTagProfileId, Tag::kAnonymousTagNum); +} + +/** + * An invalid tag that represents a TLV element decoding error due to unknown implicit profile id. + */ +constexpr Tag UnknownImplicitTag() +{ + return ProfileTag(Tag::kSpecialTagProfileId, Tag::kUnknownImplicitTagNum); } -// TODO: Move to private namespace -static constexpr Tag UnknownImplicitTag(kSpecialTagMarker | 0x00000000FFFFFFFEULL); /** * Returns the profile id from a TLV tag @@ -158,9 +198,24 @@ static constexpr Tag UnknownImplicitTag(kSpecialTagMarker | 0x00000000FFFFFFFEUL * @param[in] tag The API representation of a profile-specific TLV tag. * @return The profile id. */ -inline constexpr uint32_t ProfileIdFromTag(Tag tag) +constexpr uint32_t ProfileIdFromTag(Tag tag) +{ + return ~static_cast(tag.mVal >> Tag::kProfileIdShift); +} + +/** + * Returns the vendor id from a TLV tag + * + * @note The behavior of this function is undefined if the supplied tag is not a profile-specific tag. + * + * @param[in] tag The API representation of a profile-specific TLV tag. + * @return The associated vendor id. + */ +constexpr uint16_t VendorIdFromTag(Tag tag) { - return static_cast((tag.mVal & kProfileIdMask) >> kProfileIdShift); + constexpr uint32_t kVendorIdShift = Tag::kVendorIdShift - Tag::kProfileIdShift; + + return static_cast(ProfileIdFromTag(tag) >> kVendorIdShift); } /** @@ -171,9 +226,9 @@ inline constexpr uint32_t ProfileIdFromTag(Tag tag) * @param[in] tag The API representation of a profile-specific TLV tag. * @return The associated profile number. */ -inline constexpr uint16_t ProfileNumFromTag(Tag tag) +constexpr uint16_t ProfileNumFromTag(Tag tag) { - return static_cast((tag.mVal & kProfileNumMask) >> kProfileNumShift); + return static_cast(ProfileIdFromTag(tag)); } /** @@ -187,44 +242,31 @@ inline constexpr uint16_t ProfileNumFromTag(Tag tag) * @param[in] tag The API representation of a profile-specific or context-specific TLV tag. * @return The associated tag number. */ -inline constexpr uint32_t TagNumFromTag(Tag tag) -{ - return static_cast(tag.mVal & kTagNumMask); -} - -/** - * Returns the vendor id from a TLV tag - * - * @note The behavior of this function is undefined if the supplied tag is not a profile-specific tag. - * - * @param[in] tag The API representation of a profile-specific TLV tag. - * @return The associated vendor id. - */ -inline constexpr uint16_t VendorIdFromTag(Tag tag) +constexpr uint32_t TagNumFromTag(Tag tag) { - return static_cast((tag.mVal & kVendorIdMask) >> kVendorIdShift); + return static_cast(tag.mVal); } /** * Returns true of the supplied tag is a profile-specific tag. */ -inline constexpr bool IsProfileTag(Tag tag) +constexpr bool IsProfileTag(Tag tag) { - return (tag.mVal & kProfileIdMask) != kSpecialTagMarker; + return ProfileIdFromTag(tag) != Tag::kSpecialTagProfileId; } /** * Returns true if the supplied tag is a context-specific tag. */ -inline constexpr bool IsContextTag(Tag tag) +constexpr bool IsContextTag(Tag tag) { - return (tag.mVal & kProfileIdMask) == kSpecialTagMarker && TagNumFromTag(tag) <= kContextTagMaxNum; + return ProfileIdFromTag(tag) == Tag::kSpecialTagProfileId && TagNumFromTag(tag) <= Tag::kContextTagMaxNum; } // TODO: move to private namespace -inline constexpr bool IsSpecialTag(Tag tag) +constexpr bool IsSpecialTag(Tag tag) { - return (tag.mVal & kProfileIdMask) == kSpecialTagMarker; + return ProfileIdFromTag(tag) == Tag::kSpecialTagProfileId; } } // namespace TLV diff --git a/src/lib/core/CHIPTLVWriter.cpp b/src/lib/core/CHIPTLVWriter.cpp index 3f9743e23464f4..8a1eb7021edb66 100644 --- a/src/lib/core/CHIPTLVWriter.cpp +++ b/src/lib/core/CHIPTLVWriter.cpp @@ -631,7 +631,7 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ if (IsSpecialTag(tag)) { - if (tagNum <= kContextTagMaxNum) + if (tagNum <= Tag::kContextTagMaxNum) { if (mContainerType != kTLVType_Structure && mContainerType != kTLVType_List) return CHIP_ERROR_INVALID_TLV_TAG; From 191b0b5c701d5f691986b873264be7284f3a1b60 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 5 Jan 2023 07:26:37 -0500 Subject: [PATCH 19/31] Move weakly typed enum list back into Matter repository. (#24270) Instead of hardcoding this list in the helper (in the ZAP repository), it should be data in the Matter repository. Then we can remove things from the list without having to synchronize with ZAP changes. This change on its own does not make ZAP use this YAML instead of the hardcoded list; that will need to be a separate ZAP change after this merges. --- src/app/common/templates/templates.json | 3 ++ src/app/common/templates/weak-enum-list.yaml | 39 ++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/app/common/templates/weak-enum-list.yaml diff --git a/src/app/common/templates/templates.json b/src/app/common/templates/templates.json index 03327d0469b013..400511cce6ff86 100644 --- a/src/app/common/templates/templates.json +++ b/src/app/common/templates/templates.json @@ -8,6 +8,9 @@ "templates/app/helper.js", "templates/chip/helper.js" ], + "resources": { + "weak-enum-list": "weak-enum-list.yaml" + }, "override": "../../zap-templates/common/override.js", "partials": [ { diff --git a/src/app/common/templates/weak-enum-list.yaml b/src/app/common/templates/weak-enum-list.yaml new file mode 100644 index 00000000000000..24e3fc3b89de4a --- /dev/null +++ b/src/app/common/templates/weak-enum-list.yaml @@ -0,0 +1,39 @@ +# Allow-list of enums that we generate as enums, not enum classes. The goal is +# to drive this down to 0. +- AttributeWritePermission +- BarrierControlBarrierPosition +- BarrierControlMovingState +- ColorControlOptions +- ColorLoopAction +- ColorLoopDirection +- ColorMode +- ContentLaunchStatus +- ContentLaunchStreamingType +- EnhancedColorMode +- HardwareFaultType +- HueDirection +- HueMoveMode +- HueStepMode +- IdentifyEffectIdentifier +- IdentifyEffectVariant +- IdentifyIdentifyType +- InterfaceType +- KeypadLockout +- LevelControlOptions +- MoveMode +- NetworkFaultType +- OnOffDelayedAllOffEffectVariant +- OnOffDyingLightEffectVariant +- OnOffEffectIdentifier +- PHYRateType +- RadioFaultType +- RoutingRole +- SaturationMoveMode +- SaturationStepMode +- SecurityType +- SetpointAdjustMode +- StartUpOnOffValue +- StatusCode +- StepMode +- TemperatureDisplayMode +- WiFiVersionType From b1b899465918c5cf1b7157ba485adada5b4b413c Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 5 Jan 2023 15:14:00 +0100 Subject: [PATCH 20/31] [chip-tool] Add busyWaitMs optional argument to chip-tool to lock the main thread and the reception of messages for a given duration once a message is sent (#23886) --- .../commands/clusters/ClusterCommand.h | 2 + .../commands/clusters/WriteAttributeCommand.h | 2 + .../interaction_model/InteractionModel.cpp | 15 +++++++ .../interaction_model/InteractionModel.h | 44 +++++++++++++++++++ 4 files changed, 63 insertions(+) diff --git a/examples/chip-tool/commands/clusters/ClusterCommand.h b/examples/chip-tool/commands/clusters/ClusterCommand.h index f6cb307021ac5d..c2562843e024a8 100644 --- a/examples/chip-tool/commands/clusters/ClusterCommand.h +++ b/examples/chip-tool/commands/clusters/ClusterCommand.h @@ -173,6 +173,8 @@ class ClusterCommand : public InteractionModelCommands, public ModelCommand, pub AddArgument("timedInteractionTimeoutMs", 0, UINT16_MAX, &mTimedInteractionTimeoutMs, "If provided, do a timed invoke with the given timed interaction timeout. See \"7.6.10. Timed Interaction\" in " "the Matter specification."); + AddArgument("busyWaitForMs", 0, UINT16_MAX, &mBusyWaitForMs, + "If provided, block the main thread processing for the given time right after sending a command."); AddArgument("suppressResponse", 0, 1, &mSuppressResponse); AddArgument("repeat-count", 1, UINT16_MAX, &mRepeatCount); AddArgument("repeat-delay-ms", 0, UINT16_MAX, &mRepeatDelayInMs); diff --git a/examples/chip-tool/commands/clusters/WriteAttributeCommand.h b/examples/chip-tool/commands/clusters/WriteAttributeCommand.h index 56363cb481721d..9b5e8f3ef70728 100644 --- a/examples/chip-tool/commands/clusters/WriteAttributeCommand.h +++ b/examples/chip-tool/commands/clusters/WriteAttributeCommand.h @@ -228,6 +228,8 @@ class WriteAttribute : public InteractionModelWriter, public ModelCommand, publi AddArgument("timedInteractionTimeoutMs", 0, UINT16_MAX, &mTimedInteractionTimeoutMs, "If provided, do a timed write with the given timed interaction timeout. See \"7.6.10. Timed Interaction\" in " "the Matter specification."); + AddArgument("busyWaitForMs", 0, UINT16_MAX, &mBusyWaitForMs, + "If provided, block the main thread processing for the given time right after sending a command."); AddArgument("data-version", 0, UINT32_MAX, &mDataVersions, "Comma-separated list of data versions for the clusters being written."); AddArgument("suppressResponse", 0, 1, &mSuppressResponse); diff --git a/src/app/tests/suites/commands/interaction_model/InteractionModel.cpp b/src/app/tests/suites/commands/interaction_model/InteractionModel.cpp index ad4bf1603a258d..542f4ffd29368f 100644 --- a/src/app/tests/suites/commands/interaction_model/InteractionModel.cpp +++ b/src/app/tests/suites/commands/interaction_model/InteractionModel.cpp @@ -21,6 +21,21 @@ using namespace chip; using namespace chip::app; +namespace chip { +namespace test_utils { +void BusyWaitMillis(uint16_t busyWaitForMs) +{ + auto & clock = chip::System::SystemClock(); + auto start = clock.GetMonotonicTimestamp(); + chip::System::Clock::Milliseconds32 durationInMs(busyWaitForMs); + while (clock.GetMonotonicTimestamp() - start < durationInMs) + { + // nothing to do. + }; +} +} // namespace test_utils +} // namespace chip + CHIP_ERROR InteractionModel::ReadAttribute(const char * identity, EndpointId endpointId, ClusterId clusterId, AttributeId attributeId, bool fabricFiltered, const Optional & dataVersion) { diff --git a/src/app/tests/suites/commands/interaction_model/InteractionModel.h b/src/app/tests/suites/commands/interaction_model/InteractionModel.h index 83a0d6fff769b6..1d3e2eb735e116 100644 --- a/src/app/tests/suites/commands/interaction_model/InteractionModel.h +++ b/src/app/tests/suites/commands/interaction_model/InteractionModel.h @@ -30,6 +30,12 @@ constexpr uint8_t kMaxAllowedPaths = 10; +namespace chip { +namespace test_utils { +void BusyWaitMillis(uint16_t busyWaitForMs); +} // namespace test_utils +} // namespace chip + class InteractionModelConfig { public: @@ -237,6 +243,11 @@ class InteractionModelCommands ReturnErrorOnFailure(commandSender->SendCommandRequest(device->GetSecureSession().Value())); mCommandSender.push_back(std::move(commandSender)); + if (mBusyWaitForMs.HasValue()) + { + chip::test_utils::BusyWaitMillis(mBusyWaitForMs.Value()); + } + if (mRepeatDelayInMs.HasValue()) { chip::test_utils::SleepMillis(mRepeatDelayInMs.Value()); @@ -321,18 +332,32 @@ class InteractionModelCommands return *this; } + InteractionModelCommands & SetBusyWaitForMs(uint16_t busyWaitForMs) + { + mBusyWaitForMs.SetValue(busyWaitForMs); + return *this; + } + + InteractionModelCommands & SetBusyWaitForMs(const chip::Optional & busyWaitForMs) + { + mBusyWaitForMs = busyWaitForMs; + return *this; + } + void ResetOptions() { mTimedInteractionTimeoutMs = chip::NullOptional; mSuppressResponse = chip::NullOptional; mRepeatCount = chip::NullOptional; mRepeatDelayInMs = chip::NullOptional; + mBusyWaitForMs = chip::NullOptional; } chip::Optional mTimedInteractionTimeoutMs; chip::Optional mSuppressResponse; chip::Optional mRepeatCount; chip::Optional mRepeatDelayInMs; + chip::Optional mBusyWaitForMs; }; class InteractionModelWriter @@ -370,6 +395,11 @@ class InteractionModelWriter ReturnErrorOnFailure(mWriteClient->SendWriteRequest(device->GetSecureSession().Value())); + if (mBusyWaitForMs.HasValue()) + { + chip::test_utils::BusyWaitMillis(mBusyWaitForMs.Value()); + } + if (mRepeatDelayInMs.HasValue()) { chip::test_utils::SleepMillis(mRepeatDelayInMs.Value()); @@ -487,6 +517,18 @@ class InteractionModelWriter return *this; } + InteractionModelWriter & SetBusyWaitForMs(uint16_t busyWaitForMs) + { + mBusyWaitForMs.SetValue(busyWaitForMs); + return *this; + } + + InteractionModelWriter & SetBusyWaitForMs(const chip::Optional & busyWaitForMs) + { + mBusyWaitForMs = busyWaitForMs; + return *this; + } + void ResetOptions() { mTimedInteractionTimeoutMs = chip::NullOptional; @@ -494,6 +536,7 @@ class InteractionModelWriter mDataVersions = chip::NullOptional; mRepeatCount = chip::NullOptional; mRepeatDelayInMs = chip::NullOptional; + mBusyWaitForMs = chip::NullOptional; } chip::Optional mTimedInteractionTimeoutMs; @@ -501,6 +544,7 @@ class InteractionModelWriter chip::Optional mSuppressResponse; chip::Optional mRepeatCount; chip::Optional mRepeatDelayInMs; + chip::Optional mBusyWaitForMs; private: template From c3a4bc9ab3d8bbd4f05c765e79775a99a73a5b00 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 5 Jan 2023 09:20:11 -0500 Subject: [PATCH 21/31] Align naming in Network Commissioning cluster XML with the spec. (#24264) * Align naming in Network Commissioning cluster XML with the spec. * Regenerate generated files. --- .../all-clusters-common/all-clusters-app.matter | 2 +- .../all-clusters-minimal-app.matter | 2 +- examples/bridge-app/bridge-common/bridge-app.matter | 2 +- .../rootnode_colortemperaturelight_hbUnzYVeyn.matter | 2 +- .../devices/rootnode_contactsensor_lFAGG1bfRO.matter | 2 +- .../devices/rootnode_dimmablelight_bCwGYSDpoe.matter | 2 +- .../chef/devices/rootnode_doorlock_aNKYAreMXE.matter | 2 +- .../rootnode_extendedcolorlight_8lcaaYJVAa.matter | 2 +- examples/chef/devices/rootnode_fan_7N2TobIlOX.matter | 2 +- .../devices/rootnode_flowsensor_1zVxHedlaV.matter | 2 +- .../rootnode_heatingcoolingunit_ncdGai1E5a.matter | 2 +- .../devices/rootnode_humiditysensor_Xyj4gda6Hb.matter | 2 +- .../devices/rootnode_lightsensor_lZQycTFcJK.matter | 2 +- .../rootnode_occupancysensor_iHyVgifZuo.matter | 2 +- .../devices/rootnode_onofflight_bbs1b7IaOV.matter | 2 +- .../rootnode_onofflightswitch_FsPlMr090Q.matter | 2 +- .../rootnode_onoffpluginunit_Wtf8ss5EBY.matter | 2 +- .../devices/rootnode_pressuresensor_s0qC9wLH4k.matter | 2 +- .../chef/devices/rootnode_speaker_RpzeXdimqA.matter | 2 +- .../rootnode_temperaturesensor_Qy1zkNW7c3.matter | 2 +- .../devices/rootnode_thermostat_bm3fb8dhYi.matter | 2 +- .../devices/rootnode_windowcovering_RLCxaGi9Yx.matter | 2 +- .../contact-sensor-common/contact-sensor-app.matter | 2 +- .../bridge-common/bridge-app.matter | 2 +- .../light-switch-common/light-switch-app.matter | 2 +- .../lighting-app/lighting-common/lighting-app.matter | 2 +- examples/lighting-app/nxp/zap/lighting-on-off.matter | 2 +- examples/lock-app/lock-common/lock-app.matter | 2 +- .../log-source-common/log-source-app.matter | 2 +- .../ota-provider-common/ota-provider-app.matter | 2 +- .../ota-requestor-common/ota-requestor-app.matter | 2 +- examples/placeholder/linux/apps/app1/config.matter | 2 +- examples/placeholder/linux/apps/app2/config.matter | 2 +- examples/pump-app/pump-common/pump-app.matter | 2 +- .../pump-controller-common/pump-controller-app.matter | 2 +- .../esp32/main/temperature-measurement.matter | 2 +- .../thermostat/thermostat-common/thermostat.matter | 2 +- examples/tv-app/tv-common/tv-app.matter | 4 ++-- .../tv-casting-common/tv-casting-app.matter | 2 +- examples/window-app/common/window-app.matter | 2 +- .../data-model/chip/network-commissioning-cluster.xml | 8 ++++---- src/controller/data_model/controller-clusters.matter | 2 +- .../Framework/CHIP/templates/MTRBaseClusters.zapt | 2 +- src/darwin/Framework/CHIP/templates/availability.yaml | 11 +++++++++++ .../Framework/CHIP/zap-generated/MTRBaseClusters.h | 5 ++++- .../Darwin/WiFi/NetworkCommissioningWiFiDriver.mm | 2 +- .../silabs/NetworkCommissioningWiFiDriver.cpp | 2 +- .../app-common/zap-generated/cluster-enums.h | 2 +- .../app-common/app-common/zap-generated/enums.h | 4 ++-- 49 files changed, 67 insertions(+), 53 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter index 2999f27a55bdb4..d3c4b3c21e166e 100644 --- a/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter +++ b/examples/all-clusters-app/all-clusters-common/all-clusters-app.matter @@ -979,7 +979,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter index 0ea0a312a80a70..78a720bf22610c 100644 --- a/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter +++ b/examples/all-clusters-minimal-app/all-clusters-common/all-clusters-minimal-app.matter @@ -908,7 +908,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/bridge-app/bridge-common/bridge-app.matter b/examples/bridge-app/bridge-common/bridge-app.matter index bc512081ede0c3..9e196b071bb2df 100644 --- a/examples/bridge-app/bridge-common/bridge-app.matter +++ b/examples/bridge-app/bridge-common/bridge-app.matter @@ -654,7 +654,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter index b581d736f30482..64f4e158311dc2 100644 --- a/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter +++ b/examples/chef/devices/rootnode_colortemperaturelight_hbUnzYVeyn.matter @@ -624,7 +624,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_contactsensor_lFAGG1bfRO.matter b/examples/chef/devices/rootnode_contactsensor_lFAGG1bfRO.matter index cfaef808114702..92c6d0e9a303bd 100644 --- a/examples/chef/devices/rootnode_contactsensor_lFAGG1bfRO.matter +++ b/examples/chef/devices/rootnode_contactsensor_lFAGG1bfRO.matter @@ -497,7 +497,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter b/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter index 7c314a9211d015..5d9520811f7de6 100644 --- a/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter +++ b/examples/chef/devices/rootnode_dimmablelight_bCwGYSDpoe.matter @@ -646,7 +646,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_doorlock_aNKYAreMXE.matter b/examples/chef/devices/rootnode_doorlock_aNKYAreMXE.matter index 472e9477262e0a..d60f528e15b86f 100644 --- a/examples/chef/devices/rootnode_doorlock_aNKYAreMXE.matter +++ b/examples/chef/devices/rootnode_doorlock_aNKYAreMXE.matter @@ -497,7 +497,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter index dff1a98eed5aa3..9657afc4259cea 100644 --- a/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter +++ b/examples/chef/devices/rootnode_extendedcolorlight_8lcaaYJVAa.matter @@ -646,7 +646,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter b/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter index 15e0a1034d897c..0da03778068ce3 100644 --- a/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter +++ b/examples/chef/devices/rootnode_fan_7N2TobIlOX.matter @@ -499,7 +499,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_flowsensor_1zVxHedlaV.matter b/examples/chef/devices/rootnode_flowsensor_1zVxHedlaV.matter index 7c6446e1e8cc9b..f1551f204ef330 100644 --- a/examples/chef/devices/rootnode_flowsensor_1zVxHedlaV.matter +++ b/examples/chef/devices/rootnode_flowsensor_1zVxHedlaV.matter @@ -510,7 +510,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter index 3b36f2ae987519..ee51f83d2e671b 100644 --- a/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter +++ b/examples/chef/devices/rootnode_heatingcoolingunit_ncdGai1E5a.matter @@ -639,7 +639,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_humiditysensor_Xyj4gda6Hb.matter b/examples/chef/devices/rootnode_humiditysensor_Xyj4gda6Hb.matter index 39ad6dd5f3013c..b8d3088688c159 100644 --- a/examples/chef/devices/rootnode_humiditysensor_Xyj4gda6Hb.matter +++ b/examples/chef/devices/rootnode_humiditysensor_Xyj4gda6Hb.matter @@ -510,7 +510,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_lightsensor_lZQycTFcJK.matter b/examples/chef/devices/rootnode_lightsensor_lZQycTFcJK.matter index a0a6b310a10319..3c337b37201a94 100644 --- a/examples/chef/devices/rootnode_lightsensor_lZQycTFcJK.matter +++ b/examples/chef/devices/rootnode_lightsensor_lZQycTFcJK.matter @@ -510,7 +510,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_occupancysensor_iHyVgifZuo.matter b/examples/chef/devices/rootnode_occupancysensor_iHyVgifZuo.matter index 770f2495594654..dbe0949d0bef74 100644 --- a/examples/chef/devices/rootnode_occupancysensor_iHyVgifZuo.matter +++ b/examples/chef/devices/rootnode_occupancysensor_iHyVgifZuo.matter @@ -510,7 +510,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter b/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter index f3f026c679f961..736958cc69273b 100644 --- a/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter +++ b/examples/chef/devices/rootnode_onofflight_bbs1b7IaOV.matter @@ -646,7 +646,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter b/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter index 647f5be459e9da..2d3dab4480ef7b 100644 --- a/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter +++ b/examples/chef/devices/rootnode_onofflightswitch_FsPlMr090Q.matter @@ -589,7 +589,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter b/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter index e5a1c171203196..9c6d87a08b45a2 100644 --- a/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter +++ b/examples/chef/devices/rootnode_onoffpluginunit_Wtf8ss5EBY.matter @@ -547,7 +547,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter index efb2f5ebbb9e58..a05ec34df74a70 100644 --- a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter +++ b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter @@ -515,7 +515,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter b/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter index 0a3f54e975dfb5..b22236fb5eaad6 100644 --- a/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter +++ b/examples/chef/devices/rootnode_speaker_RpzeXdimqA.matter @@ -637,7 +637,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_temperaturesensor_Qy1zkNW7c3.matter b/examples/chef/devices/rootnode_temperaturesensor_Qy1zkNW7c3.matter index 4ca3f3231e275f..956938cf4a91a1 100644 --- a/examples/chef/devices/rootnode_temperaturesensor_Qy1zkNW7c3.matter +++ b/examples/chef/devices/rootnode_temperaturesensor_Qy1zkNW7c3.matter @@ -510,7 +510,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter index 35202e6eb9c2e6..c15a487a642a67 100644 --- a/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter +++ b/examples/chef/devices/rootnode_thermostat_bm3fb8dhYi.matter @@ -497,7 +497,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/chef/devices/rootnode_windowcovering_RLCxaGi9Yx.matter b/examples/chef/devices/rootnode_windowcovering_RLCxaGi9Yx.matter index 455c6dc74ddb73..729ceff4fe6636 100644 --- a/examples/chef/devices/rootnode_windowcovering_RLCxaGi9Yx.matter +++ b/examples/chef/devices/rootnode_windowcovering_RLCxaGi9Yx.matter @@ -497,7 +497,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter b/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter index 108218687f5598..0696014926b2f5 100644 --- a/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter +++ b/examples/contact-sensor-app/contact-sensor-common/contact-sensor-app.matter @@ -500,7 +500,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/dynamic-bridge-app/bridge-common/bridge-app.matter b/examples/dynamic-bridge-app/bridge-common/bridge-app.matter index bc512081ede0c3..9e196b071bb2df 100644 --- a/examples/dynamic-bridge-app/bridge-common/bridge-app.matter +++ b/examples/dynamic-bridge-app/bridge-common/bridge-app.matter @@ -654,7 +654,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/light-switch-app/light-switch-common/light-switch-app.matter b/examples/light-switch-app/light-switch-common/light-switch-app.matter index 60163b655d90a8..af2fc54a7ec4ee 100644 --- a/examples/light-switch-app/light-switch-common/light-switch-app.matter +++ b/examples/light-switch-app/light-switch-common/light-switch-app.matter @@ -702,7 +702,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/lighting-app/lighting-common/lighting-app.matter b/examples/lighting-app/lighting-common/lighting-app.matter index 7b2c429fd448c4..34d79e80f4df80 100644 --- a/examples/lighting-app/lighting-common/lighting-app.matter +++ b/examples/lighting-app/lighting-common/lighting-app.matter @@ -658,7 +658,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/lighting-app/nxp/zap/lighting-on-off.matter b/examples/lighting-app/nxp/zap/lighting-on-off.matter index 35d6253d4f3e75..ce768f1eda4bbe 100644 --- a/examples/lighting-app/nxp/zap/lighting-on-off.matter +++ b/examples/lighting-app/nxp/zap/lighting-on-off.matter @@ -612,7 +612,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/lock-app/lock-common/lock-app.matter b/examples/lock-app/lock-common/lock-app.matter index 283c91d72fed46..2e7ff08d46cbaa 100644 --- a/examples/lock-app/lock-common/lock-app.matter +++ b/examples/lock-app/lock-common/lock-app.matter @@ -574,7 +574,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/log-source-app/log-source-common/log-source-app.matter b/examples/log-source-app/log-source-common/log-source-app.matter index 28341bb99c23f0..e00f69ca61edc0 100644 --- a/examples/log-source-app/log-source-common/log-source-app.matter +++ b/examples/log-source-app/log-source-common/log-source-app.matter @@ -157,7 +157,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/ota-provider-app/ota-provider-common/ota-provider-app.matter b/examples/ota-provider-app/ota-provider-common/ota-provider-app.matter index dafc45b9628fc9..631d8303ffa7c8 100644 --- a/examples/ota-provider-app/ota-provider-common/ota-provider-app.matter +++ b/examples/ota-provider-app/ota-provider-common/ota-provider-app.matter @@ -393,7 +393,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter index 00ec6a26d82721..a2ce3e2b02aa6f 100644 --- a/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter +++ b/examples/ota-requestor-app/ota-requestor-common/ota-requestor-app.matter @@ -558,7 +558,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/placeholder/linux/apps/app1/config.matter b/examples/placeholder/linux/apps/app1/config.matter index 4ad37a9e6f581b..f8ffde9dff6c9b 100644 --- a/examples/placeholder/linux/apps/app1/config.matter +++ b/examples/placeholder/linux/apps/app1/config.matter @@ -819,7 +819,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/placeholder/linux/apps/app2/config.matter b/examples/placeholder/linux/apps/app2/config.matter index 4ad37a9e6f581b..f8ffde9dff6c9b 100644 --- a/examples/placeholder/linux/apps/app2/config.matter +++ b/examples/placeholder/linux/apps/app2/config.matter @@ -819,7 +819,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/pump-app/pump-common/pump-app.matter b/examples/pump-app/pump-common/pump-app.matter index 9f7d9dd521d959..729a6ad9012a7d 100644 --- a/examples/pump-app/pump-common/pump-app.matter +++ b/examples/pump-app/pump-common/pump-app.matter @@ -561,7 +561,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/pump-controller-app/pump-controller-common/pump-controller-app.matter b/examples/pump-controller-app/pump-controller-common/pump-controller-app.matter index fbbb3ad0e1a546..da44ef42b0a06b 100644 --- a/examples/pump-controller-app/pump-controller-common/pump-controller-app.matter +++ b/examples/pump-controller-app/pump-controller-common/pump-controller-app.matter @@ -460,7 +460,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/temperature-measurement-app/esp32/main/temperature-measurement.matter b/examples/temperature-measurement-app/esp32/main/temperature-measurement.matter index bf88563db716ce..c49f2ec01f56e4 100644 --- a/examples/temperature-measurement-app/esp32/main/temperature-measurement.matter +++ b/examples/temperature-measurement-app/esp32/main/temperature-measurement.matter @@ -274,7 +274,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/thermostat/thermostat-common/thermostat.matter b/examples/thermostat/thermostat-common/thermostat.matter index 28f3870a5a281c..15d06410def29c 100644 --- a/examples/thermostat/thermostat-common/thermostat.matter +++ b/examples/thermostat/thermostat-common/thermostat.matter @@ -662,7 +662,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/tv-app/tv-common/tv-app.matter b/examples/tv-app/tv-common/tv-app.matter index 98b68bf8f34b43..e3c07dd6d3bd8b 100644 --- a/examples/tv-app/tv-common/tv-app.matter +++ b/examples/tv-app/tv-common/tv-app.matter @@ -573,7 +573,7 @@ client cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; @@ -707,7 +707,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/tv-casting-app/tv-casting-common/tv-casting-app.matter b/examples/tv-casting-app/tv-casting-common/tv-casting-app.matter index ea6c92a294542b..b073a35a99aea5 100644 --- a/examples/tv-casting-app/tv-casting-common/tv-casting-app.matter +++ b/examples/tv-casting-app/tv-casting-common/tv-casting-app.matter @@ -879,7 +879,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/examples/window-app/common/window-app.matter b/examples/window-app/common/window-app.matter index cd0a0e789a10de..c29a4d437cd2d4 100644 --- a/examples/window-app/common/window-app.matter +++ b/examples/window-app/common/window-app.matter @@ -740,7 +740,7 @@ server cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml index eaf97404c4365b..57d469de794daa 100644 --- a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml @@ -43,7 +43,7 @@ limitations under the License. - + @@ -171,8 +171,8 @@ limitations under the License. - - - + + + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 4de517ed5d514e..f7573977ba4a49 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -1143,7 +1143,7 @@ client cluster NetworkCommissioning = 49 { bitmap WiFiSecurity : BITMAP8 { kUnencrypted = 0x1; - kWepPersonal = 0x2; + kWep = 0x2; kWpaPersonal = 0x4; kWpa2Personal = 0x8; kWpa3Personal = 0x10; diff --git a/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt b/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt index 433c778543c4dd..99a43ecc41aadc 100644 --- a/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt +++ b/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt @@ -121,7 +121,7 @@ typedef NS_OPTIONS({{asUnderlyingZclType name}}, {{objCEnumName clusterName bitm {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel label}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=(objCEnumItemLabel label) deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex mask}}, {{#*inline "oldNameItemDecl"}} {{#if oldItemName}} - {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName bitmap=../enumName bitmapValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex value 2}}, + {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex mask}}, {{/if}} {{/inline}} {{> oldNameItemDecl oldItemName=(oldName ../clusterName bitmap=../bitmapName bitmapValue=(objCEnumItemLabel label))}} diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index bc301ada0ea09e..fb9685f8ad5539 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -5205,6 +5205,9 @@ LevelControlOptions: - ExecuteIfOff - CoupleColorTempToLevel + NetworkCommissioning: + WiFiSecurity: + - WEP deprecated: clusters: - OtaSoftwareUpdateProvider @@ -5269,6 +5272,10 @@ PowerSource: BatChargeLevel: - Ok + bitmap values: + NetworkCommissioning: + WiFiSecurity: + - WepPersonal apis: - Timed Invoke for server to client commands - Deprecated global attribute names @@ -5347,3 +5354,7 @@ PowerSource: BatChargeLevel: OK: Ok + bitmap values: + NetworkCommissioning: + WiFiSecurity: + WEP: WepPersonal diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index 7999ed99518178..0387e8cc9334ac 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -17522,7 +17522,10 @@ typedef NS_OPTIONS(uint32_t, MTRNetworkCommissioningFeature) { typedef NS_OPTIONS(uint8_t, MTRNetworkCommissioningWiFiSecurity) { MTRNetworkCommissioningWiFiSecurityUnencrypted API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, - MTRNetworkCommissioningWiFiSecurityWepPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x2, + MTRNetworkCommissioningWiFiSecurityWEP MTR_NEWLY_AVAILABLE = 0x2, + MTRNetworkCommissioningWiFiSecurityWepPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRNetworkCommissioningWiFiSecurityWEP") + = 0x2, MTRNetworkCommissioningWiFiSecurityWpaPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x4, MTRNetworkCommissioningWiFiSecurityWpa2Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x8, MTRNetworkCommissioningWiFiSecurityWpa3Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x10, diff --git a/src/platform/Darwin/WiFi/NetworkCommissioningWiFiDriver.mm b/src/platform/Darwin/WiFi/NetworkCommissioningWiFiDriver.mm index 94a67373de41aa..a393e79996f9c9 100644 --- a/src/platform/Darwin/WiFi/NetworkCommissioningWiFiDriver.mm +++ b/src/platform/Darwin/WiFi/NetworkCommissioningWiFiDriver.mm @@ -93,7 +93,7 @@ WiFiSecurity GetWiFiSecurity(CWNetwork * network) } if ([network supportsSecurity:kCWSecurityWEP]) { - return WiFiSecurity::kWepPersonal; + return WiFiSecurity::kWep; } if ([network supportsSecurity:kCWSecurityWPAPersonal]) { diff --git a/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp b/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp index b63d617befcec8..98af04b7319a2f 100644 --- a/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp @@ -203,7 +203,7 @@ chip::BitFlags SlWiFiDriver::ConvertSecuritytype(uint8_t security) } else if (security & WFX_SEC_WEP) { - securityType = WiFiSecurity::kWepPersonal; + securityType = WiFiSecurity::kWep; } else if (security & WFX_SEC_WPA) { diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h index c29a4d426ea87d..bb5cf6a6e78b5d 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h @@ -622,7 +622,7 @@ enum class NetworkCommissioningFeature : uint32_t enum class WiFiSecurity : uint8_t { kUnencrypted = 0x1, - kWepPersonal = 0x2, + kWep = 0x2, kWpaPersonal = 0x4, kWpa2Personal = 0x8, kWpa3Personal = 0x10, diff --git a/zzz_generated/app-common/app-common/zap-generated/enums.h b/zzz_generated/app-common/app-common/zap-generated/enums.h index f2d3e87a8a3812..5e0312ef23de4c 100644 --- a/zzz_generated/app-common/app-common/zap-generated/enums.h +++ b/zzz_generated/app-common/app-common/zap-generated/enums.h @@ -962,8 +962,8 @@ enum EmberAfWiFiVersionType : uint8_t #define EMBER_AF_WI_FI_NETWORK_DIAGNOSTICS_FEATURE_ERROR_COUNTS_OFFSET (1) #define EMBER_AF_WI_FI_SECURITY_UNENCRYPTED (1) #define EMBER_AF_WI_FI_SECURITY_UNENCRYPTED_OFFSET (0) -#define EMBER_AF_WI_FI_SECURITY_WEP_PERSONAL (2) -#define EMBER_AF_WI_FI_SECURITY_WEP_PERSONAL_OFFSET (1) +#define EMBER_AF_WI_FI_SECURITY_WEP (2) +#define EMBER_AF_WI_FI_SECURITY_WEP_OFFSET (1) #define EMBER_AF_WI_FI_SECURITY_WPA_PERSONAL (4) #define EMBER_AF_WI_FI_SECURITY_WPA_PERSONAL_OFFSET (2) #define EMBER_AF_WI_FI_SECURITY_WPA2_PERSONAL (8) From 631e2c4656d6f5127be1865878ceb9d325e77791 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 5 Jan 2023 09:48:20 -0500 Subject: [PATCH 22/31] Increase build timeout for cc13x2x7_26x2x7 builds (#24282) --- .github/workflows/examples-cc13x2x7_26x2x7.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index d8598c6561eba9..aa11433edd9fa6 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -28,7 +28,7 @@ env: jobs: cc26x2x7: name: cc26x2x7 - timeout-minutes: 60 + timeout-minutes: 120 env: BUILD_TYPE: gn_cc26x2x7 @@ -68,7 +68,7 @@ jobs: .environment/gn_out/.ninja_log .environment/pigweed-venv/*.log - name: Build examples - timeout-minutes: 60 + timeout-minutes: 100 run: | scripts/run_in_build_env.sh "\ ./scripts/build/build_examples.py \ From 7fe65779c7cd1f61a67f9728f5418ad0144b9129 Mon Sep 17 00:00:00 2001 From: Sharad Binjola <31142146+sharadb-amazon@users.noreply.github.com> Date: Thu, 5 Jan 2023 06:49:14 -0800 Subject: [PATCH 23/31] tv-casting-app: On kBindingsChangedViaCluster, connect to VideoPlayer if already commissioned with it (#24268) * tv-casting-app: On kBindingsChangedViaCluster, connect to VideoPlayer if already commissioned with it * Addressing chrisdecenzo@'s feedback * Addressing bzbarsky-apple@'s feedback --- .../tv-casting-common/include/CastingServer.h | 3 +- .../include/TargetVideoPlayerInfo.h | 1 + .../tv-casting-common/src/CastingServer.cpp | 73 ++++++++++++++++++- .../src/TargetVideoPlayerInfo.cpp | 27 ++++--- 4 files changed, 90 insertions(+), 14 deletions(-) diff --git a/examples/tv-casting-app/tv-casting-common/include/CastingServer.h b/examples/tv-casting-app/tv-casting-common/include/CastingServer.h index 09fb76d21525df..0eab5ab0311dcb 100644 --- a/examples/tv-casting-app/tv-casting-common/include/CastingServer.h +++ b/examples/tv-casting-app/tv-casting-common/include/CastingServer.h @@ -415,7 +415,8 @@ class CastingServer void ReadServerClusters(chip::EndpointId endpointId); PersistenceManager mPersistenceManager; - bool mInited = false; + bool mInited = false; + bool mUdcInProgress = false; TargetVideoPlayerInfo mActiveTargetVideoPlayerInfo; TargetVideoPlayerInfo mCachedTargetVideoPlayerInfo[kMaxCachedVideoPlayers]; uint16_t mTargetVideoPlayerVendorId = 0; diff --git a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h index c362ec95c99a24..4c0fd1455e7ea1 100644 --- a/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h +++ b/examples/tv-casting-app/tv-casting-common/include/TargetVideoPlayerInfo.h @@ -43,6 +43,7 @@ class TargetVideoPlayerInfo size_t GetNumIPs() const { return mNumIPs; } const chip::Inet::IPAddress * GetIpAddresses() const { return mIpAddress; } bool IsSameAs(const chip::Dnssd::DiscoveredNodeData * discoveredNodeData); + bool IsSameAs(const char * deviceName, size_t numIPs, const chip::Inet::IPAddress * ipAddresses); chip::OperationalDeviceProxy * GetOperationalDeviceProxy() { diff --git a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp index 1fa2965abcbff6..558139f3cff155 100644 --- a/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/CastingServer.cpp @@ -130,6 +130,7 @@ CHIP_ERROR CastingServer::SendUserDirectedCommissioningRequest(chip::Transport:: CHIP_ERROR CastingServer::SendUserDirectedCommissioningRequest(Dnssd::DiscoveredNodeData * selectedCommissioner) { + mUdcInProgress = true; // Send User Directed commissioning request ReturnErrorOnFailure(SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress::UDP( selectedCommissioner->resolutionData.ipAddress[0], selectedCommissioner->resolutionData.port, @@ -320,24 +321,92 @@ CastingServer::ContentLauncherLaunchURL(TargetEndpointInfo * endpoint, const cha void CastingServer::DeviceEventCallback(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) { + bool runPostCommissioning = false; + chip::NodeId targetPeerNodeId = 0; + chip::FabricIndex targetFabricIndex = 0; if (event->Type == DeviceLayer::DeviceEventType::kBindingsChangedViaCluster) { + ChipLogProgress(AppServer, "CastingServer::DeviceEventCallback kBindingsChangedViaCluster received"); if (CastingServer::GetInstance()->GetActiveTargetVideoPlayer()->IsInitialized()) { + ChipLogProgress(AppServer, + "CastingServer::DeviceEventCallback already connected to video player, reading server clusters"); CastingServer::GetInstance()->ReadServerClustersForNode( CastingServer::GetInstance()->GetActiveTargetVideoPlayer()->GetNodeId()); } + else if (CastingServer::GetInstance()->mUdcInProgress) + { + ChipLogProgress(AppServer, + "CastingServer::DeviceEventCallback UDC is in progress while handling kBindingsChangedViaCluster"); + CastingServer::GetInstance()->mUdcInProgress = false; + if (CastingServer::GetInstance()->mTargetVideoPlayerNumIPs > 0) + { + TargetVideoPlayerInfo * connectableVideoPlayerList = + CastingServer::GetInstance()->ReadCachedTargetVideoPlayerInfos(); + if (connectableVideoPlayerList == nullptr || !connectableVideoPlayerList[0].IsInitialized()) + { + ChipLogError(AppServer, "CastingServer::DeviceEventCallback No cached video players found"); + CastingServer::GetInstance()->mCommissioningCompleteCallback(CHIP_ERROR_INCORRECT_STATE); + return; + } + + for (size_t i = 0; i < kMaxCachedVideoPlayers && connectableVideoPlayerList[i].IsInitialized(); i++) + { + if (connectableVideoPlayerList[i].IsSameAs(CastingServer::GetInstance()->mTargetVideoPlayerDeviceName, + CastingServer::GetInstance()->mTargetVideoPlayerNumIPs, + CastingServer::GetInstance()->mTargetVideoPlayerIpAddress)) + { + ChipLogProgress(AppServer, + "CastingServer::DeviceEventCallback found the video player to initialize/connect to"); + targetPeerNodeId = connectableVideoPlayerList[i].GetNodeId(); + targetFabricIndex = connectableVideoPlayerList[i].GetFabricIndex(); + runPostCommissioning = true; + } + } + + if (targetPeerNodeId == 0 && runPostCommissioning == false) + { + ChipLogError(AppServer, + "CastingServer::DeviceEventCallback did NOT find the video player to initialize/connect to"); + CastingServer::GetInstance()->mCommissioningCompleteCallback(CHIP_ERROR_INCORRECT_STATE); + return; + } + } + } } else if (event->Type == DeviceLayer::DeviceEventType::kCommissioningComplete) { + ChipLogProgress(AppServer, "CastingServer::DeviceEventCallback kCommissioningComplete received"); + CastingServer::GetInstance()->mUdcInProgress = false; + targetPeerNodeId = event->CommissioningComplete.nodeId; + targetFabricIndex = event->CommissioningComplete.fabricIndex; + runPostCommissioning = true; + } + + if (runPostCommissioning) + { + ChipLogProgress(AppServer, + "CastingServer::DeviceEventCallback will connect with nodeId=0x" ChipLogFormatX64 " fabricIndex=%d", + ChipLogValueX64(targetPeerNodeId), targetFabricIndex); CHIP_ERROR err = CastingServer::GetInstance()->GetActiveTargetVideoPlayer()->Initialize( - event->CommissioningComplete.nodeId, event->CommissioningComplete.fabricIndex, - CastingServer::GetInstance()->mOnConnectionSuccessClientCallback, + targetPeerNodeId, targetFabricIndex, CastingServer::GetInstance()->mOnConnectionSuccessClientCallback, CastingServer::GetInstance()->mOnConnectionFailureClientCallback, CastingServer::GetInstance()->mTargetVideoPlayerVendorId, CastingServer::GetInstance()->mTargetVideoPlayerProductId, CastingServer::GetInstance()->mTargetVideoPlayerDeviceType, CastingServer::GetInstance()->mTargetVideoPlayerDeviceName, CastingServer::GetInstance()->mTargetVideoPlayerNumIPs, CastingServer::GetInstance()->mTargetVideoPlayerIpAddress); + if (err != CHIP_NO_ERROR) + { + ChipLogError(AppServer, "Failed to initialize target video player"); + } + + err = CastingServer::GetInstance()->mPersistenceManager.AddVideoPlayer( + &CastingServer::GetInstance()->mActiveTargetVideoPlayerInfo); + if (err != CHIP_NO_ERROR) + { + ChipLogError(AppServer, "AddVideoPlayer(ToCache) error: %" CHIP_ERROR_FORMAT, err.Format()); + } + CastingServer::GetInstance()->mCommissioningCompleteCallback(err); } } diff --git a/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp b/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp index 70609f328fc5ef..7e1d13f7e4677a 100644 --- a/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp +++ b/examples/tv-casting-app/tv-casting-common/src/TargetVideoPlayerInfo.cpp @@ -126,16 +126,10 @@ void TargetVideoPlayerInfo::PrintInfo() } } -bool TargetVideoPlayerInfo::IsSameAs(const chip::Dnssd::DiscoveredNodeData * discoveredNodeData) +bool TargetVideoPlayerInfo::IsSameAs(const char * deviceName, size_t numIPs, const chip::Inet::IPAddress * ipAddresses) { - // return false because 'this' VideoPlayer is not null - if (discoveredNodeData == nullptr) - { - return false; - } - // return false because deviceNames are different - if (strcmp(mDeviceName, discoveredNodeData->commissionData.deviceName) != 0) + if (strcmp(mDeviceName, deviceName) != 0) { return false; } @@ -146,10 +140,9 @@ bool TargetVideoPlayerInfo::IsSameAs(const chip::Dnssd::DiscoveredNodeData * dis bool matchFound = false; for (size_t i = 0; i < mNumIPs && i < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; i++) { - for (size_t j = 0; - j < discoveredNodeData->resolutionData.numIPs && j < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; j++) + for (size_t j = 0; j < numIPs && j < chip::Dnssd::CommonResolutionData::kMaxIPAddresses; j++) { - if (mIpAddress[i] == discoveredNodeData->resolutionData.ipAddress[j]) + if (mIpAddress[i] == ipAddresses[j]) { matchFound = true; break; @@ -169,3 +162,15 @@ bool TargetVideoPlayerInfo::IsSameAs(const chip::Dnssd::DiscoveredNodeData * dis return true; } + +bool TargetVideoPlayerInfo::IsSameAs(const chip::Dnssd::DiscoveredNodeData * discoveredNodeData) +{ + // return false because 'this' VideoPlayer is not null + if (discoveredNodeData == nullptr) + { + return false; + } + + return IsSameAs(discoveredNodeData->commissionData.deviceName, discoveredNodeData->resolutionData.numIPs, + discoveredNodeData->resolutionData.ipAddress); +} From 08e1711e969d5ed90404e5a854052371acffd92e Mon Sep 17 00:00:00 2001 From: Alexander Mazuruk Date: Thu, 5 Jan 2023 15:54:54 +0100 Subject: [PATCH 24/31] Cleanup devcontainer dockerfile (#23908) - group similiar things into single layers (e.g. apt-get stuff, creating user and setting it up or chowning everything in /opt) - move cpptools installation to devcontainer.json instead of current manual installation in the dockerfile - adds noop : on end of each multi-line RUN - move restyle-path binary to /usr/local/bin rather than add a new location to the PATH - add ms-vscode.cpptools to recommended extensions for vscode Signed-off-by: Alexander Mazuruk Signed-off-by: Alexander Mazuruk --- .devcontainer/Dockerfile | 75 +++++++++++++-------------------- .devcontainer/devcontainer.json | 1 + .vscode/extensions.json | 1 + 3 files changed, 31 insertions(+), 46 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index b860db10af8d43..f8e46241763eb4 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -25,9 +25,10 @@ ENV LANG en_US.utf8 # these are installed for terminal/dev convenience. If more tooling for build is required, please # add them to chip-build (in integrations/docker/images/chip-build) -RUN apt-get update -RUN apt-get install -y locales && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 -RUN apt-get -fy install git vim emacs sudo \ +RUN apt-get update \ + && apt-get install -y locales \ + && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \ + && apt-get -fy install git vim emacs sudo \ apt-utils dialog zsh \ iproute2 procps lsb-release \ bash-completion \ @@ -36,49 +37,31 @@ RUN apt-get -fy install git vim emacs sudo \ docker.io \ iputils-ping net-tools \ libncurses5 \ - libpython2.7 - -RUN groupadd -g $USER_GID $USERNAME -RUN useradd -s /bin/bash -u $USER_UID -g $USER_GID -G docker -m $USERNAME -RUN echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME -RUN chmod 0440 /etc/sudoers.d/$USERNAME - -RUN mkdir -p /var/downloads -RUN cd /var/downloads -RUN curl -JL https://github.com/microsoft/vscode-cpptools/releases/download/0.27.0/cpptools-linux.vsix > extension.zip -RUN unzip extension.zip -RUN mkdir -p /home/$USERNAME/.vscode-server/extensions -RUN mv extension /home/$USERNAME/.vscode-server/extensions/ms-vscode.cpptools-0.27.0 -RUN mkdir -p /home/$USERNAME/bin -RUN curl https://raw.githubusercontent.com/restyled-io/restyler/master/bin/restyle-path -o /home/$USERNAME/bin/restyle-path -RUN chmod +x /home/$USERNAME/bin/restyle-path -RUN chown -R $USERNAME:$USERNAME /home/$USERNAME -RUN echo "PATH=/home/$USERNAME/bin:${PATH}" >> /home/$USERNAME/.bashrc - -# $USERNAME needs to own the esp-idf and tools for the examples to build -RUN chown -R $USERNAME:$USERNAME /opt/espressif/esp-idf -RUN chown -R $USERNAME:$USERNAME /opt/espressif/tools - -# $USERNAME needs to own west configuration to build nRF Connect examples -RUN chown -R $USERNAME:$USERNAME /opt/NordicSemiconductor/nrfconnect/ - -# allow read/write access to header and libraries -RUN chown -R $USERNAME:$USERNAME /opt/ubuntu-21.04-aarch64-sysroot/usr/ - -# allow licenses to be accepted -RUN chown -R $USERNAME:$USERNAME /opt/android/sdk - -# AmebaD requires access to change build_info.h -RUN chown -R $USERNAME:$USERNAME /opt/ameba/ambd_sdk_with_chip_non_NDA/ - -# NXP uses a patch_sdk script to change SDK files -RUN mkdir -p /opt/sdk/sdks/ -RUN chown -R $USERNAME:$USERNAME /opt/sdk/sdks/ - -RUN chown -R $USERNAME:$USERNAME /opt/fsl-imx-xwayland/5.15-kirkstone/ - -# Add access to openocd for VSCode debugging -RUN chown -R $USERNAME:$USERNAME /opt/openocd + libpython2.7 \ + && : + +RUN groupadd -g $USER_GID $USERNAME \ + && useradd -s /bin/bash -u $USER_UID -g $USER_GID -G docker,sudo -m $USERNAME \ + && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \ + && chmod 0440 /etc/sudoers.d/$USERNAME \ + && : + +RUN curl https://raw.githubusercontent.com/restyled-io/restyler/master/bin/restyle-path -o /usr/local/bin/restyle-path \ + && chmod +x /usr/local/bin/restyle-path \ + && : + +RUN mkdir -p /opt/sdk/sdks/ \ + && chown -R $USERNAME:$USERNAME \ + /opt/sdk/sdks/ `# NXP uses a patch_sdk script to change SDK files` \ + /opt/espressif/esp-idf `# $USERNAME needs to own the esp-idf and tools for the examples to build` \ + /opt/espressif/tools \ + /opt/NordicSemiconductor/nrfconnect/ `# $USERNAME needs to own west configuration to build nRF Connect examples` \ + /opt/ubuntu-21.04-aarch64-sysroot/usr/ `# allow read/write access to header and libraries` \ + /opt/android/sdk `# allow licenses to be accepted` \ + /opt/ameba/ambd_sdk_with_chip_non_NDA/ `# AmebaD requires access to change build_info.h` \ + /opt/fsl-imx-xwayland/5.15-kirkstone/ \ + /opt/openocd \ + && : # Fix Tizen SDK paths for new user RUN sed -i '/^TIZEN_SDK_DATA_PATH/d' $TIZEN_SDK_ROOT/sdk.info \ diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 70c206f1058ce3..95625da71a1e40 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -34,6 +34,7 @@ "maelvalais.autoconf", "marus25.cortex-debug", "ms-azuretools.vscode-docker", + "ms-vscode.cpptools", "msedge-dev.gnls", "redhat.vscode-yaml", "vadimcn.vscode-lldb", diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 352fb19ae65035..d5969bc3ae58f2 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -15,6 +15,7 @@ "maelvalais.autoconf", "marus25.cortex-debug", "ms-azuretools.vscode-docker", + "ms-vscode.cpptools", "msedge-dev.gnls", "redhat.vscode-yaml", "vadimcn.vscode-lldb", From 260307bf2d72fd27c010357da4be76990198f05a Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Thu, 5 Jan 2023 09:56:23 -0500 Subject: [PATCH 25/31] Python packaging idl and yamltests (#24140) * Initial attempt at modularizing python packages in scripts * Put packages into separate directories with stutter * hopefully fix codegen path to idl * Fix issue with building yamltests_distribution * Hopefully fix CI * Hopefully fix CI * Hopefully fix CI * Restyle * Hopefully fix CI * Restyle * Remove directory repitition and prepend matter to py package names * Restyle * Restyle --- .github/workflows/lint.yml | 14 +- .github/workflows/tests.yaml | 2 +- .restyled.yaml | 2 +- BUILD.gn | 8 +- build/chip/chip_codegen.gni | 2 +- docs/code_generation.md | 9 +- scripts/BUILD.gn | 17 +- scripts/codegen.py | 10 +- scripts/common_setup.cfg | 19 + scripts/idl/BUILD.gn | 79 ---- scripts/idl/files.gni | 37 -- scripts/idl_lint.py | 10 +- scripts/py_matter_idl/BUILD.gn | 83 ++++ scripts/py_matter_idl/files.gni | 37 ++ .../matter_idl}/README.md | 2 +- .../matter_idl}/__init__.py | 0 .../matter_idl}/generators/__init__.py | 5 +- .../bridge/BridgeClustersCommon.jinja | 0 .../generators/bridge/BridgeClustersCpp.jinja | 0 .../bridge/BridgeClustersGlobalStructs.jinja | 0 .../bridge/BridgeClustersHeader.jinja | 0 .../matter_idl}/generators/bridge/__init__.py | 16 +- .../matter_idl}/generators/cpp/__init__.py | 0 .../cpp/application/CallbackStubSource.jinja | 0 .../PluginApplicationCallbacksHeader.jinja | 0 .../generators/cpp/application/__init__.py | 8 +- .../matter_idl}/generators/filters.py | 0 .../generators/java/ChipClustersCpp.jinja | 0 .../generators/java/ChipClustersRead.jinja | 0 .../matter_idl}/generators/java/__init__.py | 8 +- .../matter_idl}/generators/registry.py | 6 +- .../matter_idl}/generators/types.py | 4 +- .../matter_idl}/lint/__init__.py | 0 .../matter_idl}/lint/lint_rules_grammar.lark | 0 .../matter_idl}/lint/lint_rules_parser.py | 23 +- .../matter_idl}/lint/types.py | 20 +- .../matter_idl}/matter_grammar.lark | 0 .../matter_idl}/matter_idl_parser.py | 0 .../matter_idl}/matter_idl_types.py | 0 .../matter_idl}/test_generators.py | 14 +- .../matter_idl}/test_matter_idl_parser.py | 0 .../matter_idl}/test_xml_parser.py | 41 +- .../matter_idl}/tests/available_tests.yaml | 0 .../inputs/cluster_struct_attribute.matter | 0 .../inputs/global_struct_attribute.matter | 0 .../inputs/large_all_clusters_app.matter | 0 .../tests/inputs/large_lighting_app.matter | 0 .../tests/inputs/optional_argument.matter | 0 .../tests/inputs/several_clusters.matter | 0 .../tests/inputs/simple_attribute.matter | 0 .../bridge/BridgeClustersImpl.h | 0 .../bridge/BridgeGlobalStructs.h | 0 .../bridge/DemoClusterServer.h | 0 .../DemoClusterClient-InvokeSubscribeImpl.cpp | 0 .../jni/DemoClusterClient-ReadImpl.cpp | 0 .../bridge/BridgeClustersImpl.h | 0 .../bridge/BridgeGlobalStructs.h | 0 .../bridge/DemoClusterServer.h | 0 .../DemoClusterClient-InvokeSubscribeImpl.cpp | 0 .../jni/DemoClusterClient-ReadImpl.cpp | 0 .../cpp-app/PluginApplicationCallbacks.h | 0 .../cpp-app/callback-stub.cpp | 0 .../cpp-app/PluginApplicationCallbacks.h | 0 .../cpp-app/callback-stub.cpp | 0 .../MyClusterClient-InvokeSubscribeImpl.cpp | 0 .../jni/MyClusterClient-ReadImpl.cpp | 0 .../bridge/BridgeClustersImpl.h | 0 .../bridge/BridgeGlobalStructs.h | 0 .../several_clusters/bridge/FirstServer.h | 0 .../several_clusters/bridge/SecondServer.h | 0 .../outputs/several_clusters/bridge/Third.h | 0 .../several_clusters/bridge/ThirdServer.h | 0 .../cpp-app/PluginApplicationCallbacks.h | 0 .../cpp-app/callback-stub.cpp | 0 .../jni/FirstClient-InvokeSubscribeImpl.cpp | 0 .../jni/FirstClient-ReadImpl.cpp | 0 .../jni/SecondClient-InvokeSubscribeImpl.cpp | 0 .../jni/SecondClient-ReadImpl.cpp | 0 .../jni/ThirdClient-InvokeSubscribeImpl.cpp | 0 .../jni/ThirdClient-ReadImpl.cpp | 0 .../bridge/BridgeClustersImpl.h | 0 .../bridge/BridgeGlobalStructs.h | 0 .../simple_attribute/bridge/MyClusterServer.h | 0 .../MyClusterClient-InvokeSubscribeImpl.cpp | 0 .../jni/MyClusterClient-ReadImpl.cpp | 0 .../matter_idl}/xml_parser.py | 6 +- .../matter_idl}/zapxml/__init__.py | 12 +- .../matter_idl}/zapxml/handlers/__init__.py | 2 +- .../matter_idl}/zapxml/handlers/base.py | 0 .../matter_idl}/zapxml/handlers/context.py | 5 +- .../matter_idl}/zapxml/handlers/handlers.py | 23 +- .../matter_idl}/zapxml/handlers/parsing.py | 2 +- scripts/py_matter_idl/pyproject.toml | 17 + scripts/py_matter_idl/setup.cfg | 36 ++ scripts/{idl => py_matter_idl}/setup.py | 12 +- .../BUILD.gn | 20 +- .../matter_yamltests}/__init__.py | 0 .../matter_yamltests}/constraints.py | 0 .../matter_yamltests}/definitions.py | 56 +-- .../matter_yamltests}/fixes.py | 0 .../matter_yamltests}/parser.py | 0 scripts/py_matter_yamltests/pyproject.toml | 17 + scripts/py_matter_yamltests/setup.cfg | 24 ++ .../setup.py | 12 +- .../test_spec_definitions.py | 358 ++++++++++++++++++ .../test_yaml_parser.py | 7 +- scripts/requirements.txt | 3 +- .../tests/yamltests/test_spec_definitions.py | 291 -------------- 108 files changed, 808 insertions(+), 571 deletions(-) create mode 100644 scripts/common_setup.cfg delete mode 100644 scripts/idl/BUILD.gn delete mode 100644 scripts/idl/files.gni create mode 100644 scripts/py_matter_idl/BUILD.gn create mode 100644 scripts/py_matter_idl/files.gni rename scripts/{idl => py_matter_idl/matter_idl}/README.md (99%) rename scripts/{idl => py_matter_idl/matter_idl}/__init__.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/__init__.py (97%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/bridge/BridgeClustersCommon.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/bridge/BridgeClustersCpp.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/bridge/BridgeClustersGlobalStructs.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/bridge/BridgeClustersHeader.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/bridge/__init__.py (91%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/cpp/__init__.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/cpp/application/CallbackStubSource.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/cpp/application/PluginApplicationCallbacksHeader.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/cpp/application/__init__.py (84%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/filters.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/java/ChipClustersCpp.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/java/ChipClustersRead.jinja (100%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/java/__init__.py (97%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/registry.py (90%) rename scripts/{idl => py_matter_idl/matter_idl}/generators/types.py (99%) rename scripts/{idl => py_matter_idl/matter_idl}/lint/__init__.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/lint/lint_rules_grammar.lark (100%) rename scripts/{idl => py_matter_idl/matter_idl}/lint/lint_rules_parser.py (91%) rename scripts/{idl => py_matter_idl/matter_idl}/lint/types.py (92%) rename scripts/{idl => py_matter_idl/matter_idl}/matter_grammar.lark (100%) rename scripts/{idl => py_matter_idl/matter_idl}/matter_idl_parser.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/matter_idl_types.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/test_generators.py (93%) rename scripts/{idl => py_matter_idl/matter_idl}/test_matter_idl_parser.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/test_xml_parser.py (90%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/available_tests.yaml (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/cluster_struct_attribute.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/global_struct_attribute.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/large_all_clusters_app.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/large_lighting_app.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/optional_argument.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/several_clusters.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/inputs/simple_attribute.matter (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/FirstServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/SecondServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/Third.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/bridge/ThirdServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/cpp-app/callback-stub.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/simple_attribute/bridge/MyClusterServer.h (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp (100%) rename scripts/{idl => py_matter_idl/matter_idl}/xml_parser.py (93%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/__init__.py (90%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/handlers/__init__.py (96%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/handlers/base.py (100%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/handlers/context.py (95%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/handlers/handlers.py (96%) rename scripts/{idl => py_matter_idl/matter_idl}/zapxml/handlers/parsing.py (98%) create mode 100644 scripts/py_matter_idl/pyproject.toml create mode 100644 scripts/py_matter_idl/setup.cfg rename scripts/{idl => py_matter_idl}/setup.py (70%) rename scripts/{tests/yamltests => py_matter_yamltests}/BUILD.gn (72%) rename scripts/{tests/yamltests => py_matter_yamltests/matter_yamltests}/__init__.py (100%) rename scripts/{tests/yamltests => py_matter_yamltests/matter_yamltests}/constraints.py (100%) rename scripts/{tests/yamltests => py_matter_yamltests/matter_yamltests}/definitions.py (82%) rename scripts/{tests/yamltests => py_matter_yamltests/matter_yamltests}/fixes.py (100%) rename scripts/{tests/yamltests => py_matter_yamltests/matter_yamltests}/parser.py (100%) create mode 100644 scripts/py_matter_yamltests/pyproject.toml create mode 100644 scripts/py_matter_yamltests/setup.cfg rename scripts/{tests/yamltests => py_matter_yamltests}/setup.py (68%) create mode 100644 scripts/py_matter_yamltests/test_spec_definitions.py rename scripts/{tests => py_matter_yamltests}/test_yaml_parser.py (92%) delete mode 100644 scripts/tests/yamltests/test_spec_definitions.py diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 89e8c44d26a37f..3bfcc32bd9da4c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -98,13 +98,13 @@ jobs: if [ "$idl_file" = './examples/window-app/common/window-app.matter' ]; then continue; fi # Test files are intentionally small and not spec-compilant, just parse-compliant - if [ "$idl_file" = "./scripts/idl/tests/inputs/cluster_struct_attribute.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/global_struct_attribute.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/optional_argument.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/several_clusters.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/simple_attribute.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/large_lighting_app.matter" ]; then continue; fi - if [ "$idl_file" = "./scripts/idl/tests/inputs/large_all_clusters_app.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter" ]; then continue; fi + if [ "$idl_file" = "./scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter" ]; then continue; fi ./scripts/run_in_build_env.sh "./scripts/idl_lint.py --log-level warn $idl_file" >/dev/null || exit 1 done diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 7d35cde0db27ff..8f96c75a1e280b 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -105,7 +105,7 @@ jobs: # things. run: | ./scripts/run_in_build_env.sh \ - "./scripts/idl/xml_parser.py \ + "./scripts/py_matter_idl/matter_idl/xml_parser.py \ --no-print \ --log-level info \ src/app/zap-templates/zcl/data-model/chip/global-attributes.xml \ diff --git a/.restyled.yaml b/.restyled.yaml index 13d499b2b8967f..75b649d9e4242d 100644 --- a/.restyled.yaml +++ b/.restyled.yaml @@ -69,7 +69,7 @@ exclude: - "third_party/android_deps/gradlew" # gradle wrapper generated file - "src/controller/python/chip/clusters/Objects.py" # generated file, no point to restyle - "src/controller/python/chip/clusters/CHIPClusters.py" # generated file, no point to restyle - - "scripts/idl/tests/outputs/**/*" # Matches generated output 1:1 + - "scripts/py_matter_idl/matter_idl/tests/outputs/**/*" # Matches generated output 1:1 - "examples/chef/sample_app_util/test_files/*.yaml" - "examples/chef/zzz_generated/**/*" - "examples/platform/nxp/k32w/k32w0/scripts/demo_generated_certs/**/*" diff --git a/BUILD.gn b/BUILD.gn index e4e1b8e02da1b5..23bc58926aac8d 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -120,7 +120,10 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { } pw_python_pip_install("pip_install_matter_packages") { - packages = [ "//examples/common/pigweed/rpc_console:chip_rpc_distribution" ] + packages = [ + "//examples/common/pigweed/rpc_console:chip_rpc_distribution", + "//scripts:yamltests_distribution", + ] } # Python packages installed during bootstrap. @@ -260,7 +263,8 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { "//:fake_platform_tests", "//examples/chef:chef.tests", "//scripts/build:build_examples.tests", - "//scripts/idl:idl.tests", + "//scripts/py_matter_idl:matter_idl.tests", + "//scripts/py_matter_yamltests:matter_yamltests.tests", "//src:tests_run", ] } diff --git a/build/chip/chip_codegen.gni b/build/chip/chip_codegen.gni index 533cd02b27ea76..d59277ae1e484d 100644 --- a/build/chip/chip_codegen.gni +++ b/build/chip/chip_codegen.gni @@ -17,7 +17,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") import("$dir_pw_build/python.gni") -import("${chip_root}/scripts/idl/files.gni") +import("${chip_root}/scripts/py_matter_idl/files.gni") declare_args() { # Location where code has been pre-generated diff --git a/docs/code_generation.md b/docs/code_generation.md index 7deed7ba05fb1a..c676fa887ebd7c 100644 --- a/docs/code_generation.md +++ b/docs/code_generation.md @@ -84,9 +84,10 @@ specific codegen. ### `*.matter` parsing and codegen `*.matter` files are both human and machine readable. Code that can process -these files is available at `scripts/idl` and `scripts/codegen.py`. You can read -the [scripts/idl/README.md](../scripts/idl/README.md) for details of how things -work. +these files is available at `scripts/py_matter_idl` and `scripts/codegen.py`. +You can read the +[scripts/py_matter_idl/matter_idl/README.md](../scripts/py_matter_idl/matter_idl/README.md) +for details of how things work. `scripts/codegen.py` can generate various outputs based on an input `*.matter` file. @@ -198,7 +199,7 @@ Code pre-generation can be used: generation at build time or to save the code generation time at the expense of running code generation for every possible zap/generation type - To check changes in generated code across versions, beyond the comparisons - of golden image tests in `scripts/idl/tests` + of golden image tests in `scripts/py_matter_idl/matter_idl/tests` The script to trigger code pre-generation is `scripts/code_pregenerate.py` and requires the pre-generation output directory as an argument diff --git a/scripts/BUILD.gn b/scripts/BUILD.gn index 141e262d5db3e4..878102414b89ce 100644 --- a/scripts/BUILD.gn +++ b/scripts/BUILD.gn @@ -12,6 +12,21 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + import("//build_overrides/pigweed.gni") +import("$dir_pw_build/python_dist.gni") -import("$dir_pw_build/python.gni") +# This target creates a single Python package and wheel for yamltests. It will +# merge all Python dependencies Matter. The output is located in: +# out/obj/yamltests_distribution/ <- source files here +# out/obj/yamltests_distribution._build_wheel/yamltests-0.0.1-py3-none-any.whl +pw_python_distribution("yamltests_distribution") { + packages = [ "${chip_root}/scripts/py_matter_yamltests:matter_yamltests" ] + generate_setup_cfg = { + common_config_file = "common_setup.cfg" + include_default_pyproject_file = true + append_date_to_version = true + } +} diff --git a/scripts/codegen.py b/scripts/codegen.py index 67898af6ebce5f..5d824be7bfebf8 100755 --- a/scripts/codegen.py +++ b/scripts/codegen.py @@ -25,14 +25,14 @@ _has_coloredlogs = False try: - from idl.matter_idl_parser import CreateParser + from matter_idl.matter_idl_parser import CreateParser except: import os - sys.path.append(os.path.abspath(os.path.dirname(__file__))) - from idl.matter_idl_parser import CreateParser + sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'py_matter_idl'))) + from matter_idl.matter_idl_parser import CreateParser -from idl.generators import FileSystemGeneratorStorage, GeneratorStorage -from idl.generators.registry import CodeGenerator, GENERATORS +from matter_idl.generators import FileSystemGeneratorStorage, GeneratorStorage +from matter_idl.generators.registry import CodeGenerator, GENERATORS class ListGeneratedFilesStorage(GeneratorStorage): diff --git a/scripts/common_setup.cfg b/scripts/common_setup.cfg new file mode 100644 index 00000000000000..76987454de4736 --- /dev/null +++ b/scripts/common_setup.cfg @@ -0,0 +1,19 @@ +# 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. +[metadata] +name = matter_yamltests +version = 0.0.1 + +[options] +zip_safe = False diff --git a/scripts/idl/BUILD.gn b/scripts/idl/BUILD.gn deleted file mode 100644 index 324ed3a737bbf0..00000000000000 --- a/scripts/idl/BUILD.gn +++ /dev/null @@ -1,79 +0,0 @@ -# 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("//build_overrides/build.gni") -import("//build_overrides/chip.gni") - -import("//build_overrides/pigweed.gni") -import("$dir_pw_build/python.gni") - -import("${chip_root}/scripts/idl/files.gni") - -pw_python_package("idl") { - setup = [ "setup.py" ] - inputs = matter_idl_generator_templates - inputs += [ - # Dependency grammar - "matter_grammar.lark", - - # Unit test data - "tests/available_tests.yaml", - "tests/inputs/cluster_struct_attribute.matter", - "tests/inputs/global_struct_attribute.matter", - "tests/inputs/optional_argument.matter", - "tests/inputs/several_clusters.matter", - "tests/inputs/simple_attribute.matter", - "tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h", - "tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h", - "tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h", - "tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", - "tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", - "tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h", - "tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h", - "tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h", - "tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", - "tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", - "tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp", - "tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp", - "tests/outputs/several_clusters/bridge/BridgeClustersImpl.h", - "tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h", - "tests/outputs/several_clusters/bridge/FirstServer.h", - "tests/outputs/several_clusters/bridge/SecondServer.h", - "tests/outputs/several_clusters/bridge/Third.h", - "tests/outputs/several_clusters/bridge/ThirdServer.h", - "tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp", - "tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp", - "tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp", - "tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp", - "tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp", - "tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp", - "tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h", - "tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h", - "tests/outputs/simple_attribute/bridge/MyClusterServer.h", - "tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp", - "tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp", - ] - - sources = matter_idl_generator_sources - - tests = [ - "test_matter_idl_parser.py", - "test_generators.py", - "test_xml_parser.py", - ] - - # TODO: at a future time consider enabling all (* or missing) here to get - # pylint checking these files - static_analysis = [] -} diff --git a/scripts/idl/files.gni b/scripts/idl/files.gni deleted file mode 100644 index 997f1eab8b06c5..00000000000000 --- a/scripts/idl/files.gni +++ /dev/null @@ -1,37 +0,0 @@ -import("//build_overrides/build.gni") -import("//build_overrides/chip.gni") - -# Templates used for generation -matter_idl_generator_templates = [ - "${chip_root}/scripts/idl/generators/bridge/BridgeClustersCpp.jinja", - "${chip_root}/scripts/idl/generators/bridge/BridgeClustersCommon.jinja", - "${chip_root}/scripts/idl/generators/bridge/BridgeClustersGlobalStructs.jinja", - "${chip_root}/scripts/idl/generators/java/ChipClustersCpp.jinja", - "${chip_root}/scripts/idl/generators/java/ChipClustersRead.jinja", - "${chip_root}/scripts/idl/generators/cpp/application/CallbackStubSource.jinja", - "${chip_root}/scripts/idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja", -] - -matter_idl_generator_sources = [ - "${chip_root}/scripts/idl/__init__.py", - "${chip_root}/scripts/idl/generators/__init__.py", - "${chip_root}/scripts/idl/generators/bridge/__init__.py", - "${chip_root}/scripts/idl/generators/cpp/__init__.py", - "${chip_root}/scripts/idl/generators/cpp/application/__init__.py", - "${chip_root}/scripts/idl/generators/filters.py", - "${chip_root}/scripts/idl/generators/java/__init__.py", - "${chip_root}/scripts/idl/generators/types.py", - "${chip_root}/scripts/idl/matter_idl_parser.py", - "${chip_root}/scripts/idl/matter_idl_types.py", - "${chip_root}/scripts/idl/xml_parser.py", - "${chip_root}/scripts/idl/zapxml/__init__.py", - "${chip_root}/scripts/idl/zapxml/handlers/__init__.py", - "${chip_root}/scripts/idl/zapxml/handlers/base.py", - "${chip_root}/scripts/idl/zapxml/handlers/context.py", - "${chip_root}/scripts/idl/zapxml/handlers/handlers.py", - "${chip_root}/scripts/idl/zapxml/handlers/parsing.py", -] - -# All the files that the matter idl infrastructure will use -matter_idl_generator_files = - matter_idl_generator_templates + matter_idl_generator_sources diff --git a/scripts/idl_lint.py b/scripts/idl_lint.py index 83f606201f8bac..a9271afbd73fc0 100755 --- a/scripts/idl_lint.py +++ b/scripts/idl_lint.py @@ -23,12 +23,12 @@ from typing import List, Optional try: - from idl import matter_idl_parser + from matter_idl import matter_idl_parser except: - sys.path.append(os.path.abspath(os.path.dirname(__file__))) - from idl import matter_idl_parser + sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'py_matter_idl'))) + from matter_idl import matter_idl_parser -import idl.lint +import matter_idl.lint # Supported log levels, mapping string values required for argument # parsing into logging constants @@ -64,7 +64,7 @@ def main(log_level, rules, idl_path): lint_rules = [] logging.info("Loading rules from %s" % rules) - lint_rules.extend(idl.lint.CreateParser(rules).parse()) + lint_rules.extend(matter_idl.lint.CreateParser(rules).parse()) logging.info("Parsing idl from %s" % idl_path) idl_tree = matter_idl_parser.CreateParser().parse(open(idl_path, "rt").read(), file_name=idl_path) diff --git a/scripts/py_matter_idl/BUILD.gn b/scripts/py_matter_idl/BUILD.gn new file mode 100644 index 00000000000000..7e3254573e9cac --- /dev/null +++ b/scripts/py_matter_idl/BUILD.gn @@ -0,0 +1,83 @@ +# 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("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +import("//build_overrides/pigweed.gni") +import("$dir_pw_build/python.gni") + +import("${chip_root}/scripts/py_matter_idl/files.gni") + +pw_python_package("matter_idl") { + setup = [ + "setup.py", + "setup.cfg", + "pyproject.toml", + ] + inputs = matter_idl_generator_templates + inputs += [ + # Dependency grammar + "matter_idl/matter_grammar.lark", + + # Unit test data + "matter_idl/tests/available_tests.yaml", + "matter_idl/tests/inputs/cluster_struct_attribute.matter", + "matter_idl/tests/inputs/global_struct_attribute.matter", + "matter_idl/tests/inputs/optional_argument.matter", + "matter_idl/tests/inputs/several_clusters.matter", + "matter_idl/tests/inputs/simple_attribute.matter", + "matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h", + "matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h", + "matter_idl/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h", + "matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", + "matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h", + "matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h", + "matter_idl/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h", + "matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp", + "matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp", + "matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h", + "matter_idl/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h", + "matter_idl/tests/outputs/several_clusters/bridge/FirstServer.h", + "matter_idl/tests/outputs/several_clusters/bridge/SecondServer.h", + "matter_idl/tests/outputs/several_clusters/bridge/Third.h", + "matter_idl/tests/outputs/several_clusters/bridge/ThirdServer.h", + "matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp", + "matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp", + "matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp", + "matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp", + "matter_idl/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h", + "matter_idl/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h", + "matter_idl/tests/outputs/simple_attribute/bridge/MyClusterServer.h", + "matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp", + "matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp", + ] + + sources = matter_idl_generator_sources + + tests = [ + "matter_idl/test_matter_idl_parser.py", + "matter_idl/test_generators.py", + "matter_idl/test_xml_parser.py", + ] + + # TODO: at a future time consider enabling all (* or missing) here to get + # pylint checking these files + static_analysis = [] +} diff --git a/scripts/py_matter_idl/files.gni b/scripts/py_matter_idl/files.gni new file mode 100644 index 00000000000000..aa22f705caff2d --- /dev/null +++ b/scripts/py_matter_idl/files.gni @@ -0,0 +1,37 @@ +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +# Templates used for generation +matter_idl_generator_templates = [ + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCpp.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCommon.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersGlobalStructs.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja", +] + +matter_idl_generator_sources = [ + "${chip_root}/scripts/py_matter_idl/matter_idl/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/bridge/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/filters.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/java/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/generators/types.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/matter_idl_parser.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/matter_idl_types.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/xml_parser.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py", + "${chip_root}/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py", +] + +# All the files that the matter idl infrastructure will use +matter_idl_generator_files = + matter_idl_generator_templates + matter_idl_generator_sources diff --git a/scripts/idl/README.md b/scripts/py_matter_idl/matter_idl/README.md similarity index 99% rename from scripts/idl/README.md rename to scripts/py_matter_idl/matter_idl/README.md index ac3ddf517f8277..e46fb4d00c853a 100644 --- a/scripts/idl/README.md +++ b/scripts/py_matter_idl/matter_idl/README.md @@ -184,7 +184,7 @@ endpoint 0 { ## Parsing of IDLs -IDL parsing is done within the `idl` python package (this is the current +IDL parsing is done within the `matter_idl` python package (this is the current directory of this README). Most of the heavy lifting is done by the lark using [matter_grammar.lark](./matter_grammar.lark), which is then turned into an AST: diff --git a/scripts/idl/__init__.py b/scripts/py_matter_idl/matter_idl/__init__.py similarity index 100% rename from scripts/idl/__init__.py rename to scripts/py_matter_idl/matter_idl/__init__.py diff --git a/scripts/idl/generators/__init__.py b/scripts/py_matter_idl/matter_idl/generators/__init__.py similarity index 97% rename from scripts/idl/generators/__init__.py rename to scripts/py_matter_idl/matter_idl/generators/__init__.py index 1adbb6d4d0071b..779c5ad800ace2 100644 --- a/scripts/idl/generators/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/__init__.py @@ -18,7 +18,7 @@ import jinja2 from typing import Dict -from idl.matter_idl_types import Idl +from matter_idl.matter_idl_types import Idl from .filters import RegisterCommonFilters @@ -113,7 +113,8 @@ def __init__(self, storage: GeneratorStorage, idl: Idl): self.storage = storage self.idl = idl self.jinja_env = jinja2.Environment( - loader=jinja2.FileSystemLoader(searchpath=os.path.dirname(__file__)), + loader=jinja2.FileSystemLoader( + searchpath=os.path.dirname(__file__)), keep_trailing_newline=True) self.dry_run = False diff --git a/scripts/idl/generators/bridge/BridgeClustersCommon.jinja b/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCommon.jinja similarity index 100% rename from scripts/idl/generators/bridge/BridgeClustersCommon.jinja rename to scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCommon.jinja diff --git a/scripts/idl/generators/bridge/BridgeClustersCpp.jinja b/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCpp.jinja similarity index 100% rename from scripts/idl/generators/bridge/BridgeClustersCpp.jinja rename to scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersCpp.jinja diff --git a/scripts/idl/generators/bridge/BridgeClustersGlobalStructs.jinja b/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersGlobalStructs.jinja similarity index 100% rename from scripts/idl/generators/bridge/BridgeClustersGlobalStructs.jinja rename to scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersGlobalStructs.jinja diff --git a/scripts/idl/generators/bridge/BridgeClustersHeader.jinja b/scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersHeader.jinja similarity index 100% rename from scripts/idl/generators/bridge/BridgeClustersHeader.jinja rename to scripts/py_matter_idl/matter_idl/generators/bridge/BridgeClustersHeader.jinja diff --git a/scripts/idl/generators/bridge/__init__.py b/scripts/py_matter_idl/matter_idl/generators/bridge/__init__.py similarity index 91% rename from scripts/idl/generators/bridge/__init__.py rename to scripts/py_matter_idl/matter_idl/generators/bridge/__init__.py index 7a43c9e802b88a..149e6cf33e1d04 100644 --- a/scripts/idl/generators/bridge/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/bridge/__init__.py @@ -17,11 +17,11 @@ import logging import re -from idl.generators import CodeGenerator, GeneratorStorage -from idl.matter_idl_types import Idl, Field, Attribute, Cluster, ClusterSide -from idl import matter_idl_types -from idl.generators.types import (ParseDataType, BasicString, BasicInteger, FundamentalType, - IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext) +from matter_idl.generators import CodeGenerator, GeneratorStorage +from matter_idl.matter_idl_types import Idl, Field, Attribute, Cluster, ClusterSide +from matter_idl import matter_idl_types +from matter_idl.generators.types import (ParseDataType, BasicString, BasicInteger, FundamentalType, + IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext) from typing import Union, List, Set @@ -74,14 +74,16 @@ def get_field_info(definition: Field, cluster: Cluster, idl: Idl): def get_raw_size_and_type(attr: Attribute, cluster: Cluster, idl: Idl): - container, cType, size, matterType = get_field_info(attr.definition, cluster, idl) + container, cType, size, matterType = get_field_info( + attr.definition, cluster, idl) if attr.definition.is_list: return 'ZCL_ARRAY_ATTRIBUTE_TYPE, {}'.format(size) return '{}, {}'.format(matterType, size) def get_field_type(definition: Field, cluster: Cluster, idl: Idl): - container, cType, size, matterType = get_field_info(definition, cluster, idl) + container, cType, size, matterType = get_field_info( + definition, cluster, idl) if container == 'OctetString': return 'std::string' if definition.is_list: diff --git a/scripts/idl/generators/cpp/__init__.py b/scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py similarity index 100% rename from scripts/idl/generators/cpp/__init__.py rename to scripts/py_matter_idl/matter_idl/generators/cpp/__init__.py diff --git a/scripts/idl/generators/cpp/application/CallbackStubSource.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja similarity index 100% rename from scripts/idl/generators/cpp/application/CallbackStubSource.jinja rename to scripts/py_matter_idl/matter_idl/generators/cpp/application/CallbackStubSource.jinja diff --git a/scripts/idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja b/scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja similarity index 100% rename from scripts/idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja rename to scripts/py_matter_idl/matter_idl/generators/cpp/application/PluginApplicationCallbacksHeader.jinja diff --git a/scripts/idl/generators/cpp/application/__init__.py b/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py similarity index 84% rename from scripts/idl/generators/cpp/application/__init__.py rename to scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py index 4a7a3b0035ce75..ead462b2c33cb0 100644 --- a/scripts/idl/generators/cpp/application/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/cpp/application/__init__.py @@ -12,10 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -from idl.generators import CodeGenerator, GeneratorStorage -from idl.matter_idl_types import Idl, ClusterSide, Field, Attribute, Cluster, FieldQuality, Command, DataType -from idl import matter_idl_types -from idl.generators.types import ParseDataType, BasicString, BasicInteger, FundamentalType, IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext +from matter_idl.generators import CodeGenerator, GeneratorStorage +from matter_idl.matter_idl_types import Idl, ClusterSide, Field, Attribute, Cluster, FieldQuality, Command, DataType +from matter_idl import matter_idl_types +from matter_idl.generators.types import ParseDataType, BasicString, BasicInteger, FundamentalType, IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext from typing import Union, List, Set from stringcase import capitalcase diff --git a/scripts/idl/generators/filters.py b/scripts/py_matter_idl/matter_idl/generators/filters.py similarity index 100% rename from scripts/idl/generators/filters.py rename to scripts/py_matter_idl/matter_idl/generators/filters.py diff --git a/scripts/idl/generators/java/ChipClustersCpp.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja similarity index 100% rename from scripts/idl/generators/java/ChipClustersCpp.jinja rename to scripts/py_matter_idl/matter_idl/generators/java/ChipClustersCpp.jinja diff --git a/scripts/idl/generators/java/ChipClustersRead.jinja b/scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja similarity index 100% rename from scripts/idl/generators/java/ChipClustersRead.jinja rename to scripts/py_matter_idl/matter_idl/generators/java/ChipClustersRead.jinja diff --git a/scripts/idl/generators/java/__init__.py b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py similarity index 97% rename from scripts/idl/generators/java/__init__.py rename to scripts/py_matter_idl/matter_idl/generators/java/__init__.py index 6f18e9629304e5..a0f465b4e2f416 100644 --- a/scripts/idl/generators/java/__init__.py +++ b/scripts/py_matter_idl/matter_idl/generators/java/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -from idl.generators import CodeGenerator, GeneratorStorage -from idl.matter_idl_types import Idl, ClusterSide, Field, Attribute, Cluster, FieldQuality, Command, DataType -from idl import matter_idl_types -from idl.generators.types import ParseDataType, BasicString, BasicInteger, FundamentalType, IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext +from matter_idl.generators import CodeGenerator, GeneratorStorage +from matter_idl.matter_idl_types import Idl, ClusterSide, Field, Attribute, Cluster, FieldQuality, Command, DataType +from matter_idl import matter_idl_types +from matter_idl.generators.types import ParseDataType, BasicString, BasicInteger, FundamentalType, IdlType, IdlEnumType, IdlBitmapType, TypeLookupContext from typing import Union, List, Set from stringcase import capitalcase diff --git a/scripts/idl/generators/registry.py b/scripts/py_matter_idl/matter_idl/generators/registry.py similarity index 90% rename from scripts/idl/generators/registry.py rename to scripts/py_matter_idl/matter_idl/generators/registry.py index 8feeb2c48d1124..5510d3976dc623 100644 --- a/scripts/idl/generators/registry.py +++ b/scripts/py_matter_idl/matter_idl/generators/registry.py @@ -14,9 +14,9 @@ import enum -from idl.generators.java import JavaGenerator -from idl.generators.bridge import BridgeGenerator -from idl.generators.cpp.application import CppApplicationGenerator +from matter_idl.generators.java import JavaGenerator +from matter_idl.generators.bridge import BridgeGenerator +from matter_idl.generators.cpp.application import CppApplicationGenerator class CodeGenerator(enum.Enum): diff --git a/scripts/idl/generators/types.py b/scripts/py_matter_idl/matter_idl/generators/types.py similarity index 99% rename from scripts/idl/generators/types.py rename to scripts/py_matter_idl/matter_idl/generators/types.py index b6f216802de0d8..dd7705dc7070f9 100644 --- a/scripts/idl/generators/types.py +++ b/scripts/py_matter_idl/matter_idl/generators/types.py @@ -15,8 +15,8 @@ import logging import enum -from idl.matter_idl_types import DataType -from idl import matter_idl_types # to explicitly say 'Enum' +from matter_idl.matter_idl_types import DataType +from matter_idl import matter_idl_types # to explicitly say 'Enum' from typing import Union, List, Optional from dataclasses import dataclass diff --git a/scripts/idl/lint/__init__.py b/scripts/py_matter_idl/matter_idl/lint/__init__.py similarity index 100% rename from scripts/idl/lint/__init__.py rename to scripts/py_matter_idl/matter_idl/lint/__init__.py diff --git a/scripts/idl/lint/lint_rules_grammar.lark b/scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark similarity index 100% rename from scripts/idl/lint/lint_rules_grammar.lark rename to scripts/py_matter_idl/matter_idl/lint/lint_rules_grammar.lark diff --git a/scripts/idl/lint/lint_rules_parser.py b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py similarity index 91% rename from scripts/idl/lint/lint_rules_parser.py rename to scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py index fdd507cdbc383e..18bbb473b7871c 100755 --- a/scripts/idl/lint/lint_rules_parser.py +++ b/scripts/py_matter_idl/matter_idl/lint/lint_rules_parser.py @@ -16,8 +16,9 @@ except: import sys - sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..", "..")) - from idl.lint.types import RequiredAttributesRule, AttributeRequirement, ClusterRequirement, RequiredCommandsRule, ClusterCommandRequirement + sys.path.append(os.path.join(os.path.abspath( + os.path.dirname(__file__)), "..", "..")) + from matter_idl.lint.types import RequiredAttributesRule, AttributeRequirement, ClusterRequirement, RequiredCommandsRule, ClusterCommandRequirement def parseNumberString(n): @@ -90,7 +91,8 @@ def DecodeClusterFromXml(element: xml.etree.ElementTree.Element): if 'optional' in cmd.attrib and cmd.attrib['optional'] == 'true': continue - required_commands.append(RequiredCommand(name=cmd.attrib["name"], code=parseNumberString(cmd.attrib['code']))) + required_commands.append(RequiredCommand( + name=cmd.attrib["name"], code=parseNumberString(cmd.attrib['code']))) return DecodedCluster( name=name, @@ -124,8 +126,10 @@ class LintRulesContext: """ def __init__(self): - self._required_attributes_rule = RequiredAttributesRule("Required attributes") - self._required_commands_rule = RequiredCommandsRule("Required commands") + self._required_attributes_rule = RequiredAttributesRule( + "Required attributes") + self._required_commands_rule = RequiredCommandsRule( + "Required commands") # Map cluster names to the underlying code self._cluster_codes: Mapping[str, int] = {} @@ -146,7 +150,8 @@ def RequireClusterInEndpoint(self, name: str, code: int): name = "ID_%s" % name except ValueError: logging.error("UNKNOWN cluster name %s" % name) - logging.error("Known names: %s" % (",".join(self._cluster_codes.keys()), )) + logging.error("Known names: %s" % + (",".join(self._cluster_codes.keys()), )) return else: cluster_code = self._cluster_codes[name] @@ -237,7 +242,8 @@ def all_endpoint_rule(self, attributes): @v_args(inline=True) def load_xml(self, path): if not os.path.isabs(path): - path = os.path.abspath(os.path.join(os.path.dirname(self.file_name), path)) + path = os.path.abspath(os.path.join( + os.path.dirname(self.file_name), path)) self.context.LoadXml(path) @@ -262,7 +268,8 @@ def __init__(self, parser, file_name: str): self.file_name = file_name def parse(self): - data = LintRulesTransformer(self.file_name).transform(self.parser.parse(open(self.file_name, "rt").read())) + data = LintRulesTransformer(self.file_name).transform( + self.parser.parse(open(self.file_name, "rt").read())) return data diff --git a/scripts/idl/lint/types.py b/scripts/py_matter_idl/matter_idl/lint/types.py similarity index 92% rename from scripts/idl/lint/types.py rename to scripts/py_matter_idl/matter_idl/lint/types.py index 85dfbdeacd0bc3..8ee6a805ec4d4e 100644 --- a/scripts/idl/lint/types.py +++ b/scripts/py_matter_idl/matter_idl/lint/types.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from idl.matter_idl_types import Idl, ParseMetaData, ClusterSide +from matter_idl.matter_idl_types import Idl, ParseMetaData, ClusterSide from abc import ABC, abstractmethod from typing import List, Optional from dataclasses import dataclass, field @@ -40,7 +40,8 @@ class LintError: def __init__(self, text: str, location: Optional[LocationInFile] = None): self.message = text if location: - self.message += " at %s:%d:%d" % (location.file_name, location.line, location.column) + self.message += " at %s:%d:%d" % (location.file_name, + location.line, location.column) def __str__(self): return self.message @@ -84,7 +85,8 @@ def __init__(self, name): self._idl = None def _AddLintError(self, text, location): - self._lint_errors.append(LintError("%s: %s" % (self.name, text), location)) + self._lint_errors.append( + LintError("%s: %s" % (self.name, text), location)) def _ParseLocation(self, meta: Optional[ParseMetaData]) -> Optional[LocationInFile]: """Create a location in the current file that is being parsed. """ @@ -146,11 +148,13 @@ def _ServerClusterDefinition(self, name: str, location: Optional[LocationInFile] c for c in self._idl.clusters if c.name == name and c.side == ClusterSide.SERVER ] if not cluster_definition: - self._AddLintError("Cluster definition for %s not found" % cluster.name, location) + self._AddLintError( + "Cluster definition for %s not found" % cluster.name, location) return None if len(cluster_definition) > 1: - self._AddLintError("Multiple cluster definitions found for %s" % cluster.name, location) + self._AddLintError( + "Multiple cluster definitions found for %s" % cluster.name, location) return None return cluster_definition[0] @@ -161,7 +165,8 @@ def _LintImpl(self): cluster_codes = set() for cluster in endpoint.server_clusters: - cluster_definition = self._ServerClusterDefinition(cluster.name, self._ParseLocation(cluster.parse_meta)) + cluster_definition = self._ServerClusterDefinition( + cluster.name, self._ParseLocation(cluster.parse_meta)) if not cluster_definition: continue @@ -215,7 +220,8 @@ def __init__(self, name): super(RequiredCommandsRule, self).__init__(name) # Maps cluster id to mandatory cluster requirement - self._mandatory_commands: Maping[int, List[ClusterCommandRequirement]] = {} + self._mandatory_commands: Maping[int, + List[ClusterCommandRequirement]] = {} def __repr__(self): result = "RequiredCommandsRule{\n" diff --git a/scripts/idl/matter_grammar.lark b/scripts/py_matter_idl/matter_idl/matter_grammar.lark similarity index 100% rename from scripts/idl/matter_grammar.lark rename to scripts/py_matter_idl/matter_idl/matter_grammar.lark diff --git a/scripts/idl/matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/matter_idl_parser.py similarity index 100% rename from scripts/idl/matter_idl_parser.py rename to scripts/py_matter_idl/matter_idl/matter_idl_parser.py diff --git a/scripts/idl/matter_idl_types.py b/scripts/py_matter_idl/matter_idl/matter_idl_types.py similarity index 100% rename from scripts/idl/matter_idl_types.py rename to scripts/py_matter_idl/matter_idl/matter_idl_types.py diff --git a/scripts/idl/test_generators.py b/scripts/py_matter_idl/matter_idl/test_generators.py similarity index 93% rename from scripts/idl/test_generators.py rename to scripts/py_matter_idl/matter_idl/test_generators.py index 730bfdbc610762..9fb21aecf565dd 100755 --- a/scripts/idl/test_generators.py +++ b/scripts/py_matter_idl/matter_idl/test_generators.py @@ -22,19 +22,19 @@ from dataclasses import dataclass, field try: - from idl.matter_idl_parser import CreateParser + from matter_idl.matter_idl_parser import CreateParser except: import sys sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))) - from idl.matter_idl_parser import CreateParser + from matter_idl.matter_idl_parser import CreateParser -from idl.matter_idl_types import Idl -from idl.generators.java import JavaGenerator -from idl.generators.bridge import BridgeGenerator -from idl.generators.cpp.application import CppApplicationGenerator -from idl.generators import GeneratorStorage +from matter_idl.matter_idl_types import Idl +from matter_idl.generators.java import JavaGenerator +from matter_idl.generators.bridge import BridgeGenerator +from matter_idl.generators.cpp.application import CppApplicationGenerator +from matter_idl.generators import GeneratorStorage TESTS_DIR = os.path.join(os.path.dirname(__file__), "tests") diff --git a/scripts/idl/test_matter_idl_parser.py b/scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py similarity index 100% rename from scripts/idl/test_matter_idl_parser.py rename to scripts/py_matter_idl/matter_idl/test_matter_idl_parser.py diff --git a/scripts/idl/test_xml_parser.py b/scripts/py_matter_idl/matter_idl/test_xml_parser.py similarity index 90% rename from scripts/idl/test_xml_parser.py rename to scripts/py_matter_idl/matter_idl/test_xml_parser.py index 932a5731d59268..e8645cb0f4043d 100755 --- a/scripts/idl/test_xml_parser.py +++ b/scripts/py_matter_idl/matter_idl/test_xml_parser.py @@ -19,16 +19,17 @@ from typing import Optional, Union, List try: - from idl.matter_idl_types import * - from idl.zapxml import ParseSource, ParseXmls + from matter_idl.matter_idl_types import * + from matter_idl.zapxml import ParseSource, ParseXmls except: import os import sys - sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) + sys.path.append(os.path.abspath( + os.path.join(os.path.dirname(__file__), '..'))) - from idl.matter_idl_types import * - from idl.zapxml import ParseSource, ParseXmls + from matter_idl.matter_idl_types import * + from matter_idl.zapxml import ParseSource, ParseXmls def XmlToIdl(what: Union[str, List[str]]) -> Idl: @@ -37,7 +38,8 @@ def XmlToIdl(what: Union[str, List[str]]) -> Idl: sources = [] for idx, txt in enumerate(what): - sources.append(ParseSource(source=io.StringIO(txt), name=("Input %d" % (idx + 1)))) + sources.append(ParseSource(source=io.StringIO( + txt), name=("Input %d" % (idx + 1)))) return ParseXmls(sources, include_meta_data=False) @@ -97,8 +99,10 @@ def testCluster(self): structs=[ Struct(name='GetSomeDataRequest', fields=[ - Field(data_type=DataType(name='INT8U'), code=0, name='firstInput'), - Field(data_type=DataType(name='INT16U'), code=1, name='secondInput') + Field(data_type=DataType( + name='INT8U'), code=0, name='firstInput'), + Field(data_type=DataType( + name='INT16U'), code=1, name='secondInput') ], tag=StructTag.REQUEST), Struct(name='GetSomeDataResponse', @@ -142,8 +146,10 @@ def testBitmap(self): self.assertEqual(idl, Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, name='Test1', code=1, bitmaps=[bitmap]), - Cluster(side=ClusterSide.CLIENT, name='Test2', code=2, bitmaps=[bitmap]), + Cluster(side=ClusterSide.CLIENT, + name='Test1', code=1, bitmaps=[bitmap]), + Cluster(side=ClusterSide.CLIENT, + name='Test2', code=2, bitmaps=[bitmap]), ])) def testFabricScopedAndSensitive(self): @@ -226,19 +232,23 @@ def testStruct(self): name='SomeStruct', qualities=StructQuality.FABRIC_SCOPED, fields=[ - Field(data_type=DataType(name='int16u'), code=0, name='FirstMember'), - Field(data_type=DataType(name='int32u'), code=1, name='SecondMember') + Field(data_type=DataType(name='int16u'), + code=0, name='FirstMember'), + Field(data_type=DataType(name='int32u'), + code=1, name='SecondMember') ] ) self.assertEqual(idl, Idl(clusters=[ - Cluster(side=ClusterSide.CLIENT, name='Test1', code=10, structs=[struct]), + Cluster(side=ClusterSide.CLIENT, + name='Test1', code=10, structs=[struct]), Cluster(side=ClusterSide.CLIENT, name='Test2', code=20, structs=[struct], attributes=[ Attribute( definition=Field( - data_type=DataType(name='SomeStruct'), + data_type=DataType( + name='SomeStruct'), code=123, name='FabricAttribute', qualities=FieldQuality.NULLABLE @@ -287,7 +297,8 @@ def testSkipsNotProcessedFields(self): attributes=[ Attribute( definition=Field( - data_type=DataType(name='Type'), + data_type=DataType( + name='Type'), code=0, name='Type', ), diff --git a/scripts/idl/tests/available_tests.yaml b/scripts/py_matter_idl/matter_idl/tests/available_tests.yaml similarity index 100% rename from scripts/idl/tests/available_tests.yaml rename to scripts/py_matter_idl/matter_idl/tests/available_tests.yaml diff --git a/scripts/idl/tests/inputs/cluster_struct_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter similarity index 100% rename from scripts/idl/tests/inputs/cluster_struct_attribute.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/cluster_struct_attribute.matter diff --git a/scripts/idl/tests/inputs/global_struct_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter similarity index 100% rename from scripts/idl/tests/inputs/global_struct_attribute.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/global_struct_attribute.matter diff --git a/scripts/idl/tests/inputs/large_all_clusters_app.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter similarity index 100% rename from scripts/idl/tests/inputs/large_all_clusters_app.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/large_all_clusters_app.matter diff --git a/scripts/idl/tests/inputs/large_lighting_app.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter similarity index 100% rename from scripts/idl/tests/inputs/large_lighting_app.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/large_lighting_app.matter diff --git a/scripts/idl/tests/inputs/optional_argument.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter similarity index 100% rename from scripts/idl/tests/inputs/optional_argument.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/optional_argument.matter diff --git a/scripts/idl/tests/inputs/several_clusters.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter similarity index 100% rename from scripts/idl/tests/inputs/several_clusters.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/several_clusters.matter diff --git a/scripts/idl/tests/inputs/simple_attribute.matter b/scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter similarity index 100% rename from scripts/idl/tests/inputs/simple_attribute.matter rename to scripts/py_matter_idl/matter_idl/tests/inputs/simple_attribute.matter diff --git a/scripts/idl/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h similarity index 100% rename from scripts/idl/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeClustersImpl.h diff --git a/scripts/idl/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h similarity index 100% rename from scripts/idl/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/BridgeGlobalStructs.h diff --git a/scripts/idl/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h similarity index 100% rename from scripts/idl/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/bridge/DemoClusterServer.h diff --git a/scripts/idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/cluster_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h similarity index 100% rename from scripts/idl/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeClustersImpl.h diff --git a/scripts/idl/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h similarity index 100% rename from scripts/idl/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/BridgeGlobalStructs.h diff --git a/scripts/idl/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h similarity index 100% rename from scripts/idl/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/bridge/DemoClusterServer.h diff --git a/scripts/idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/global_struct_attribute/jni/DemoClusterClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h similarity index 100% rename from scripts/idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/PluginApplicationCallbacks.h diff --git a/scripts/idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp similarity index 100% rename from scripts/idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/large_all_clusters_app/cpp-app/callback-stub.cpp diff --git a/scripts/idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h similarity index 100% rename from scripts/idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/PluginApplicationCallbacks.h diff --git a/scripts/idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp similarity index 100% rename from scripts/idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/large_lighting_app/cpp-app/callback-stub.cpp diff --git a/scripts/idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/optional_argument/jni/MyClusterClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/BridgeClustersImpl.h diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/BridgeGlobalStructs.h diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/FirstServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/FirstServer.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/FirstServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/FirstServer.h diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/SecondServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/SecondServer.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/SecondServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/SecondServer.h diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/Third.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/Third.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/Third.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/Third.h diff --git a/scripts/idl/tests/outputs/several_clusters/bridge/ThirdServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/ThirdServer.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/bridge/ThirdServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/bridge/ThirdServer.h diff --git a/scripts/idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/PluginApplicationCallbacks.h diff --git a/scripts/idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/cpp-app/callback-stub.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/FirstClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/SecondClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/several_clusters/jni/ThirdClient-ReadImpl.cpp diff --git a/scripts/idl/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h similarity index 100% rename from scripts/idl/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/BridgeClustersImpl.h diff --git a/scripts/idl/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h similarity index 100% rename from scripts/idl/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/BridgeGlobalStructs.h diff --git a/scripts/idl/tests/outputs/simple_attribute/bridge/MyClusterServer.h b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/MyClusterServer.h similarity index 100% rename from scripts/idl/tests/outputs/simple_attribute/bridge/MyClusterServer.h rename to scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/bridge/MyClusterServer.h diff --git a/scripts/idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-InvokeSubscribeImpl.cpp diff --git a/scripts/idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp b/scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp similarity index 100% rename from scripts/idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp rename to scripts/py_matter_idl/matter_idl/tests/outputs/simple_attribute/jni/MyClusterClient-ReadImpl.cpp diff --git a/scripts/idl/xml_parser.py b/scripts/py_matter_idl/matter_idl/xml_parser.py similarity index 93% rename from scripts/idl/xml_parser.py rename to scripts/py_matter_idl/matter_idl/xml_parser.py index f2955c973ef632..5ef145ee377462 100755 --- a/scripts/idl/xml_parser.py +++ b/scripts/py_matter_idl/matter_idl/xml_parser.py @@ -21,15 +21,15 @@ import xml.sax.handler try: - from idl.matter_idl_types import Idl + from matter_idl.matter_idl_types import Idl except: import sys sys.path.append(os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))) - from idl.matter_idl_types import Idl + from matter_idl.matter_idl_types import Idl -from idl.zapxml import ParseSource, ParseXmls +from matter_idl.zapxml import ParseSource, ParseXmls if __name__ == '__main__': diff --git a/scripts/idl/zapxml/__init__.py b/scripts/py_matter_idl/matter_idl/zapxml/__init__.py similarity index 90% rename from scripts/idl/zapxml/__init__.py rename to scripts/py_matter_idl/matter_idl/zapxml/__init__.py index 332d1c244bea3b..41b31b452ae066 100644 --- a/scripts/idl/zapxml/__init__.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/__init__.py @@ -19,8 +19,8 @@ from dataclasses import dataclass from typing import Optional, Union, List -from idl.zapxml.handlers import Context, ZapXmlHandler -from idl.matter_idl_types import Idl +from matter_idl.zapxml.handlers import Context, ZapXmlHandler +from matter_idl.matter_idl_types import Idl class ParseHandler(xml.sax.handler.ContentHandler): @@ -32,7 +32,7 @@ class ParseHandler(xml.sax.handler.ContentHandler): - sets up parsing location within the context - keeps track of ParsePath - Overall converts a python SAX handler into idl.zapxml.handlers + Overall converts a python SAX handler into matter_idl.zapxml.handlers """ def __init__(self, include_meta_data=True): @@ -66,7 +66,8 @@ def endDocument(self): def startElement(self, name: str, attrs): logging.debug("ELEMENT START: %r / %r" % (name, attrs)) self._context.path.push(name) - self._processing_stack.append(self._processing_stack[-1].GetNextProcessor(name, attrs)) + self._processing_stack.append( + self._processing_stack[-1].GetNextProcessor(name, attrs)) def endElement(self, name: str): logging.debug("ELEMENT END: %r" % name) @@ -89,7 +90,8 @@ class ParseSource: Allows for named data sources to be parsed. """ source: Union[str, typing.IO] # filename or stream - name: Optional[str] = None # actual filename to use, None if the source is a filename already + # actual filename to use, None if the source is a filename already + name: Optional[str] = None @ property def source_file_name(self): diff --git a/scripts/idl/zapxml/handlers/__init__.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py similarity index 96% rename from scripts/idl/zapxml/handlers/__init__.py rename to scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py index 7a6bfa04682921..3745954a195cfd 100644 --- a/scripts/idl/zapxml/handlers/__init__.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/__init__.py @@ -16,7 +16,7 @@ from .context import Context from .handlers import ConfiguratorHandler -from idl.matter_idl_types import Idl +from matter_idl.matter_idl_types import Idl class ZapXmlHandler(BaseHandler): diff --git a/scripts/idl/zapxml/handlers/base.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py similarity index 100% rename from scripts/idl/zapxml/handlers/base.py rename to scripts/py_matter_idl/matter_idl/zapxml/handlers/base.py diff --git a/scripts/idl/zapxml/handlers/context.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py similarity index 95% rename from scripts/idl/zapxml/handlers/context.py rename to scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py index 2d82153d76d959..b8fd748dfdcfd2 100644 --- a/scripts/idl/zapxml/handlers/context.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/context.py @@ -15,7 +15,7 @@ import logging import xml.sax.xmlreader -from idl.matter_idl_types import Idl, ParseMetaData, Attribute +from matter_idl.matter_idl_types import Idl, ParseMetaData, Attribute from typing import Optional, List @@ -104,7 +104,8 @@ def AddGlobalAttribute(self, attribute: Attribute): # NOTE: this may get added several times as both 'client' and 'server' # however matter should not differentiate between the two code = attribute.definition.code - logging.info('Adding global attribute 0x%X (%d): %s' % (code, code, attribute.definition.name)) + logging.info('Adding global attribute 0x%X (%d): %s' % + (code, code, attribute.definition.name)) self._global_attributes[code] = attribute diff --git a/scripts/idl/zapxml/handlers/handlers.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py similarity index 96% rename from scripts/idl/zapxml/handlers/handlers.py rename to scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py index 313fc61e8cdbb7..f1396627247a36 100644 --- a/scripts/idl/zapxml/handlers/handlers.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py @@ -14,7 +14,7 @@ import logging -from idl.matter_idl_types import * +from matter_idl.matter_idl_types import * from typing import Optional, Union, List from .context import Context, IdlPostProcessor @@ -245,7 +245,8 @@ class EnumHandler(BaseHandler, IdlPostProcessor): def __init__(self, context: Context, attrs): super().__init__(context) self._cluster_code = None # if set, enum belongs to a specific cluster - self._enum = Enum(name=attrs['name'], base_type=attrs['type'], entries=[]) + self._enum = Enum(name=attrs['name'], + base_type=attrs['type'], entries=[]) def GetNextProcessor(self, name, attrs): if name.lower() == 'item': @@ -256,7 +257,8 @@ def GetNextProcessor(self, name, attrs): return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) elif name.lower() == 'cluster': if self._cluster_code is not None: - raise Exception('Multiple cluster codes for enum %s' % self._enum.name) + raise Exception( + 'Multiple cluster codes for enum %s' % self._enum.name) self._cluster_code = ParseInt(attrs['code']) return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) else: @@ -290,7 +292,8 @@ class BitmapHandler(BaseHandler): def __init__(self, context: Context, attrs): super().__init__(context) self._cluster_codes = set() - self._bitmap = Bitmap(name=attrs['name'], base_type=attrs['type'], entries=[]) + self._bitmap = Bitmap( + name=attrs['name'], base_type=attrs['type'], entries=[]) def GetNextProcessor(self, name, attrs): if name.lower() == 'cluster': @@ -410,7 +413,8 @@ def GetNextProcessor(self, name: str, attrs): if self._command: self._command.invokeacl = AttrsToAccessPrivilege(attrs) else: - logging.warning("Ignored access role for reply %r" % self._struct) + logging.warning( + "Ignored access role for reply %r" % self._struct) return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) elif name.lower() == 'arg': self._struct.fields.append(self.GetArgumentField(attrs)) @@ -444,13 +448,15 @@ def GetNextProcessor(self, name: str, attrs): if name.lower() == 'featurebit': # It is uncler what featurebits mean. likely a bitmap should be created # here, however only one such example exists currently: door-lock-cluster.xml - logging.info('Ignoring featurebit tag for global attribute 0x%X (%d)' % (self._code, self._code)) + logging.info('Ignoring featurebit tag for global attribute 0x%X (%d)' % ( + self._code, self._code)) return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) else: return BaseHandler(self.context) def EndProcessing(self): - self._cluster.attributes.append(self.context.GetGlobalAttribute(self._code)) + self._cluster.attributes.append( + self.context.GetGlobalAttribute(self._code)) class ClusterHandler(BaseHandler): @@ -566,7 +572,8 @@ def GetNextProcessor(self, name, attrs): if attrs['side'].lower() == 'client': # We expect to also have 'server' equivalent, so ignore client # side attributes - logging.debug('Ignoring global client-side attribute %s' % (attrs['code'])) + logging.debug( + 'Ignoring global client-side attribute %s' % (attrs['code'])) return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) return GlobalAttributeHandler(self.context, AttrsToAttribute(attrs)) diff --git a/scripts/idl/zapxml/handlers/parsing.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py similarity index 98% rename from scripts/idl/zapxml/handlers/parsing.py rename to scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py index f9315f3dab6875..40553edc0d4d1e 100644 --- a/scripts/idl/zapxml/handlers/parsing.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/parsing.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from idl.matter_idl_types import * +from matter_idl.matter_idl_types import * def ParseInt(value: str) -> int: diff --git a/scripts/py_matter_idl/pyproject.toml b/scripts/py_matter_idl/pyproject.toml new file mode 100644 index 00000000000000..ab9c08adaab8b5 --- /dev/null +++ b/scripts/py_matter_idl/pyproject.toml @@ -0,0 +1,17 @@ +# 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. + +[build-system] +requires = ['setuptools', 'wheel'] +build-backend = 'setuptools.build_meta' diff --git a/scripts/py_matter_idl/setup.cfg b/scripts/py_matter_idl/setup.cfg new file mode 100644 index 00000000000000..91e84f82ca8990 --- /dev/null +++ b/scripts/py_matter_idl/setup.cfg @@ -0,0 +1,36 @@ +# 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. + +[metadata] +name = matter_idl +version = 0.0.1 +author = Project CHIP Authors +description = Parse matter idl files + +[options] +packages = find: +zip_safe = False + +[options.package_data] +matter_idl = + lint/lint_rules_grammar.lark + matter_grammar.lark + generators/java/ChipClustersRead.jinja + generators/java/ChipClustersCpp.jinja + generators/cpp/application/CallbackStubSource.jinja + generators/cpp/application/PluginApplicationCallbacksHeader.jinja + generators/bridge/BridgeClustersHeader.jinja + generators/bridge/BridgeClustersCommon.jinja + generators/bridge/BridgeClustersCpp.jinja + generators/bridge/BridgeClustersGlobalStructs.jinja diff --git a/scripts/idl/setup.py b/scripts/py_matter_idl/setup.py similarity index 70% rename from scripts/idl/setup.py rename to scripts/py_matter_idl/setup.py index 4566792c40074a..5c10e05ae39916 100644 --- a/scripts/idl/setup.py +++ b/scripts/py_matter_idl/setup.py @@ -13,16 +13,8 @@ # limitations under the License. -"""The idl package.""" +"""The matter_idl package.""" import setuptools # type: ignore -setuptools.setup( - name='idl', - version='0.0.1', - author='Project CHIP Authors', - description='Parse matter idl files', - packages=setuptools.find_packages(), - package_data={'idl': ['py.typed']}, - zip_safe=False, -) +setuptools.setup() # Package definition in setup.cfg diff --git a/scripts/tests/yamltests/BUILD.gn b/scripts/py_matter_yamltests/BUILD.gn similarity index 72% rename from scripts/tests/yamltests/BUILD.gn rename to scripts/py_matter_yamltests/BUILD.gn index 2f9a49c0744181..88ba5a41b1cc19 100644 --- a/scripts/tests/yamltests/BUILD.gn +++ b/scripts/py_matter_yamltests/BUILD.gn @@ -18,18 +18,22 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") import("$dir_pw_build/python.gni") -pw_python_package("yamltests") { - setup = [ "setup.py" ] +pw_python_package("matter_yamltests") { + setup = [ + "setup.py", + "setup.cfg", + "pyproject.toml", + ] sources = [ - "__init__.py", - "constraints.py", - "definitions.py", - "fixes.py", - "parser.py", + "matter_yamltests/__init__.py", + "matter_yamltests/constraints.py", + "matter_yamltests/definitions.py", + "matter_yamltests/fixes.py", + "matter_yamltests/parser.py", ] - python_deps = [ "${chip_root}/scripts/idl" ] + python_deps = [ "${chip_root}/scripts/py_matter_idl:matter_idl" ] tests = [ "test_spec_definitions.py" ] diff --git a/scripts/tests/yamltests/__init__.py b/scripts/py_matter_yamltests/matter_yamltests/__init__.py similarity index 100% rename from scripts/tests/yamltests/__init__.py rename to scripts/py_matter_yamltests/matter_yamltests/__init__.py diff --git a/scripts/tests/yamltests/constraints.py b/scripts/py_matter_yamltests/matter_yamltests/constraints.py similarity index 100% rename from scripts/tests/yamltests/constraints.py rename to scripts/py_matter_yamltests/matter_yamltests/constraints.py diff --git a/scripts/tests/yamltests/definitions.py b/scripts/py_matter_yamltests/matter_yamltests/definitions.py similarity index 82% rename from scripts/tests/yamltests/definitions.py rename to scripts/py_matter_yamltests/matter_yamltests/definitions.py index 006704993d7bab..f4b39b134e3f1a 100644 --- a/scripts/tests/yamltests/definitions.py +++ b/scripts/py_matter_yamltests/matter_yamltests/definitions.py @@ -16,16 +16,8 @@ from typing import List import enum -try: - from idl.zapxml import ParseSource, ParseXmls - from idl.matter_idl_types import * -except: - import os - import sys - sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) - - from idl.zapxml import ParseSource, ParseXmls - from idl.matter_idl_types import * +from matter_idl.zapxml import ParseSource, ParseXmls +from matter_idl.matter_idl_types import * class _ItemType(enum.Enum): @@ -66,23 +58,31 @@ def __init__(self, sources: List[ParseSource]): self.__clusters_by_id[code] = cluster self.__commands_by_id[code] = {c.code: c for c in cluster.commands} self.__responses_by_id[code] = {} - self.__attributes_by_id[code] = {a.definition.code: a for a in cluster.attributes} + self.__attributes_by_id[code] = { + a.definition.code: a for a in cluster.attributes} self.__events_by_id[code] = {e.code: e for e in cluster.events} self.__clusters_by_name[name] = cluster.code - self.__commands_by_name[name] = {c.name.lower(): c.code for c in cluster.commands} + self.__commands_by_name[name] = { + c.name.lower(): c.code for c in cluster.commands} self.__responses_by_name[name] = {} - self.__attributes_by_name[name] = {a.definition.name.lower(): a.definition.code for a in cluster.attributes} - self.__events_by_name[name] = {e.name.lower(): e.code for e in cluster.events} - - self.__bitmaps_by_name[name] = {b.name.lower(): b for b in cluster.bitmaps} - self.__enums_by_name[name] = {e.name.lower(): e for e in cluster.enums} - self.__structs_by_name[name] = {s.name.lower(): s for s in cluster.structs} + self.__attributes_by_name[name] = { + a.definition.name.lower(): a.definition.code for a in cluster.attributes} + self.__events_by_name[name] = { + e.name.lower(): e.code for e in cluster.events} + + self.__bitmaps_by_name[name] = { + b.name.lower(): b for b in cluster.bitmaps} + self.__enums_by_name[name] = { + e.name.lower(): e for e in cluster.enums} + self.__structs_by_name[name] = { + s.name.lower(): s for s in cluster.structs} for struct in cluster.structs: if struct.tag == StructTag.RESPONSE: self.__responses_by_id[code][struct.code] = struct - self.__responses_by_name[name][struct.name.lower()] = struct.code + self.__responses_by_name[name][struct.name.lower( + )] = struct.code def get_cluster_name(self, cluster_id: int) -> str: cluster = self.__clusters_by_id.get(cluster_id) @@ -93,11 +93,13 @@ def get_command_name(self, cluster_id: int, command_id: int) -> str: return command.name if command else None def get_response_name(self, cluster_id: int, response_id: int) -> str: - response = self.__get_by_id(cluster_id, response_id, _ItemType.Response) + response = self.__get_by_id( + cluster_id, response_id, _ItemType.Response) return response.name if response else None def get_attribute_name(self, cluster_id: int, attribute_id: int) -> str: - attribute = self.__get_by_id(cluster_id, attribute_id, _ItemType.Attribute) + attribute = self.__get_by_id( + cluster_id, attribute_id, _ItemType.Attribute) return attribute.definition.name if attribute else None def get_event_name(self, cluster_id: int, event_id: int) -> str: @@ -162,16 +164,20 @@ def __get_by_name(self, cluster_name: str, target_name: str, target_type: _ItemT target = None if target_type == _ItemType.Request: - target_id = self.__commands_by_name.get(cluster_name).get(target_name) + target_id = self.__commands_by_name.get( + cluster_name).get(target_name) target = self.__get_by_id(cluster_id, target_id, target_type) elif target_type == _ItemType.Response: - target_id = self.__responses_by_name.get(cluster_name).get(target_name) + target_id = self.__responses_by_name.get( + cluster_name).get(target_name) target = self.__get_by_id(cluster_id, target_id, target_type) elif target_type == _ItemType.Event: - target_id = self.__events_by_name.get(cluster_name).get(target_name) + target_id = self.__events_by_name.get( + cluster_name).get(target_name) target = self.__get_by_id(cluster_id, target_id, target_type) elif target_type == _ItemType.Attribute: - target_id = self.__attributes_by_name.get(cluster_name).get(target_name) + target_id = self.__attributes_by_name.get( + cluster_name).get(target_name) target = self.__get_by_id(cluster_id, target_id, target_type) elif target_type == _ItemType.Bitmap: target = self.__bitmaps_by_name.get(cluster_name).get(target_name) diff --git a/scripts/tests/yamltests/fixes.py b/scripts/py_matter_yamltests/matter_yamltests/fixes.py similarity index 100% rename from scripts/tests/yamltests/fixes.py rename to scripts/py_matter_yamltests/matter_yamltests/fixes.py diff --git a/scripts/tests/yamltests/parser.py b/scripts/py_matter_yamltests/matter_yamltests/parser.py similarity index 100% rename from scripts/tests/yamltests/parser.py rename to scripts/py_matter_yamltests/matter_yamltests/parser.py diff --git a/scripts/py_matter_yamltests/pyproject.toml b/scripts/py_matter_yamltests/pyproject.toml new file mode 100644 index 00000000000000..ab9c08adaab8b5 --- /dev/null +++ b/scripts/py_matter_yamltests/pyproject.toml @@ -0,0 +1,17 @@ +# 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. + +[build-system] +requires = ['setuptools', 'wheel'] +build-backend = 'setuptools.build_meta' diff --git a/scripts/py_matter_yamltests/setup.cfg b/scripts/py_matter_yamltests/setup.cfg new file mode 100644 index 00000000000000..497022ce1459d9 --- /dev/null +++ b/scripts/py_matter_yamltests/setup.cfg @@ -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. + +[metadata] +name = matter_yamltests +version = 0.0.1 +author = Project CHIP Authors +description = Parse matter yaml tests files + +[options] +packages = find: + +zip_safe = False diff --git a/scripts/tests/yamltests/setup.py b/scripts/py_matter_yamltests/setup.py similarity index 68% rename from scripts/tests/yamltests/setup.py rename to scripts/py_matter_yamltests/setup.py index 2bcdfbe8c61d46..2d7f786e1957f6 100644 --- a/scripts/tests/yamltests/setup.py +++ b/scripts/py_matter_yamltests/setup.py @@ -13,16 +13,8 @@ # limitations under the License. -"""The yamltest package.""" +"""The yamltests package.""" import setuptools # type: ignore -setuptools.setup( - name='yamltests', - version='0.0.1', - author='Project CHIP Authors', - description='Parse matter yaml test files', - packages=setuptools.find_packages(), - package_data={'yamltest': ['py.typed']}, - zip_safe=False, -) +setuptools.setup() # Package definition in setup.cfg diff --git a/scripts/py_matter_yamltests/test_spec_definitions.py b/scripts/py_matter_yamltests/test_spec_definitions.py new file mode 100644 index 00000000000000..35a2dcd29f911a --- /dev/null +++ b/scripts/py_matter_yamltests/test_spec_definitions.py @@ -0,0 +1,358 @@ +#!/usr/bin/env -S python3 -B +# +# 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. + +from matter_yamltests.definitions import * + +import unittest +import io + +source_cluster = ''' + + + Test + 0x1234 + + +''' + +source_command = ''' + + + Test + 0x1234 + + + + + +''' + +source_response = ''' + + + Test + 0x1234 + + + + + + + +''' + +source_attribute = ''' + + + TestGlobalAttribute + + + + Test + 0x1234 + + + TestAttribute + + + +''' + +source_event = ''' + + + Test + 0x1234 + + + + + +''' + +source_bitmap = ''' + + + + + + + + + + + + + Test + 0x1234 + + + + TestWrong + 0x4321 + + +''' + +source_enum = ''' + + + + + + + + + + + + + Test + 0x1234 + + + + TestWrong + 0x4321 + + +''' + +source_struct = ''' + + + + + + + + + + + + + + + + + + Test + 0x1234 + + + + TestWrong + 0x4321 + + +''' + + +class TestSpecDefinitions(unittest.TestCase): + def test_cluster_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_cluster), name='source_cluster')]) + self.assertIsNone(definitions.get_cluster_name(0x4321)) + self.assertEqual(definitions.get_cluster_name(0x1234), 'Test') + + def test_command_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_command), name='source_command')]) + self.assertIsNone(definitions.get_command_name(0x4321, 0x0)) + self.assertIsNone(definitions.get_command_name(0x1234, 0x1)) + self.assertEqual(definitions.get_command_name( + 0x1234, 0x0), 'TestCommand') + + def test_response_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_response), name='source_response')]) + self.assertIsNone(definitions.get_response_name(0x4321, 0x0)) + self.assertIsNone(definitions.get_response_name(0x1234, 0x1)) + self.assertEqual(definitions.get_response_name( + 0x1234, 0x0), 'TestCommandResponse') + + def test_attribute_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) + self.assertIsNone(definitions.get_attribute_name(0x4321, 0x0)) + self.assertIsNone(definitions.get_attribute_name(0x4321, 0xFFFD)) + self.assertIsNone(definitions.get_attribute_name(0x1234, 0x1)) + self.assertEqual(definitions.get_attribute_name( + 0x1234, 0x0), 'TestAttribute') + self.assertEqual(definitions.get_attribute_name( + 0x1234, 0xFFFD), 'TestGlobalAttribute') + + def test_event_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_event), name='source_event')]) + self.assertIsNone(definitions.get_event_name(0x4321, 0x0)) + self.assertIsNone(definitions.get_event_name(0x1234, 0x1)) + self.assertEqual(definitions.get_event_name(0x1234, 0x0), 'TestEvent') + + def test_get_command_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_command), name='source_command')]) + self.assertIsNone(definitions.get_command_by_name( + 'WrongName', 'TestCommand')) + self.assertIsNone(definitions.get_command_by_name( + 'Test', 'TestWrongCommand')) + self.assertIsNone( + definitions.get_response_by_name('Test', 'TestCommand')) + self.assertIsInstance(definitions.get_command_by_name( + 'Test', 'TestCommand'), Command) + self.assertIsNone( + definitions.get_command_by_name('test', 'TestCommand')) + self.assertIsInstance(definitions.get_command_by_name( + 'Test', 'testcommand'), Command) + + def test_get_response_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_response), name='source_response')]) + self.assertIsNone(definitions.get_response_by_name( + 'WrongName', 'TestCommandResponse')) + self.assertIsNone(definitions.get_response_by_name( + 'Test', 'TestWrongCommandResponse')) + self.assertIsNone(definitions.get_command_by_name( + 'Test', 'TestCommandResponse')) + self.assertIsInstance(definitions.get_response_by_name( + 'Test', 'TestCommandResponse'), Struct) + self.assertIsNone(definitions.get_response_by_name( + 'test', 'TestCommandResponse')) + self.assertIsInstance(definitions.get_response_by_name( + 'Test', 'testcommandresponse'), Struct) + + def test_get_attribute_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) + self.assertIsNone(definitions.get_attribute_by_name( + 'WrongName', 'TestAttribute')) + self.assertIsNone(definitions.get_attribute_by_name( + 'WrongName', 'TestGlobalAttribute')) + self.assertIsNone(definitions.get_attribute_by_name( + 'Test', 'TestWrongAttribute')) + self.assertIsInstance(definitions.get_attribute_by_name( + 'Test', 'TestAttribute'), Attribute) + self.assertIsInstance(definitions.get_attribute_by_name( + 'Test', 'TestGlobalAttribute'), Attribute) + self.assertIsNone(definitions.get_attribute_by_name( + 'test', 'TestAttribute')) + self.assertIsNone(definitions.get_attribute_by_name( + 'test', 'TestGlobalAttribute')) + self.assertIsInstance(definitions.get_attribute_by_name( + 'Test', 'testattribute'), Attribute) + self.assertIsInstance(definitions.get_attribute_by_name( + 'Test', 'testglobalattribute'), Attribute) + + def test_get_event_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_event), name='source_event')]) + self.assertIsNone(definitions.get_event_by_name( + 'WrongName', 'TestEvent')) + self.assertIsNone(definitions.get_event_by_name( + 'Test', 'TestWrongEvent')) + self.assertIsInstance( + definitions.get_event_by_name('Test', 'TestEvent'), Event) + self.assertIsNone(definitions.get_event_by_name('test', 'TestEvent')) + self.assertIsInstance( + definitions.get_event_by_name('Test', 'testevent'), Event) + + def test_get_bitmap_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_bitmap), name='source_bitmap')]) + self.assertIsNone(definitions.get_bitmap_by_name( + 'WrongName', 'TestBitmap')) + self.assertIsNone(definitions.get_bitmap_by_name( + 'Test', 'TestWrongBitmap')) + self.assertIsInstance(definitions.get_bitmap_by_name( + 'Test', 'TestBitmap'), Bitmap) + self.assertIsNone(definitions.get_bitmap_by_name('test', 'TestBitmap')) + self.assertIsInstance(definitions.get_bitmap_by_name( + 'Test', 'testbitmap'), Bitmap) + + def test_get_enum_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_enum), name='source_enum')]) + self.assertIsNone(definitions.get_enum_by_name( + 'WrongName', 'TestEnum')) + self.assertIsNone(definitions.get_enum_by_name( + 'Test', 'TestWrongEnum')) + self.assertIsInstance( + definitions.get_enum_by_name('Test', 'TestEnum'), Enum) + self.assertIsNone(definitions.get_enum_by_name('test', 'TestEnum')) + self.assertIsInstance( + definitions.get_enum_by_name('Test', 'testenum'), Enum) + + def test_get_struct_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_struct), name='source_struct')]) + self.assertIsNone(definitions.get_struct_by_name( + 'WrongName', 'TestStruct')) + self.assertIsNone(definitions.get_struct_by_name( + 'Test', 'TestWrongStruct')) + self.assertIsInstance(definitions.get_struct_by_name( + 'Test', 'TestStruct'), Struct) + self.assertIsNone(definitions.get_struct_by_name('test', 'TestStruct')) + self.assertIsInstance(definitions.get_struct_by_name( + 'Test', 'teststruct'), Struct) + + def test_get_type_by_name(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_command), name='source_command')]) + self.assertIsNone(definitions.get_type_by_name('Test', 'TestCommand')) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_response), name='source_response')]) + self.assertIsInstance(definitions.get_type_by_name( + 'Test', 'TestCommandResponse'), Struct) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) + self.assertIsNone(definitions.get_type_by_name( + 'Test', 'TestAttribute')) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_event), name='source_event')]) + self.assertIsNone(definitions.get_type_by_name('Test', 'TestEvent')) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_bitmap), name='source_bitmap')]) + self.assertIsInstance(definitions.get_type_by_name( + 'Test', 'TestBitmap'), Bitmap) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_enum), name='source_enum')]) + self.assertIsInstance( + definitions.get_type_by_name('Test', 'TestEnum'), Enum) + + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_struct), name='source_struct')]) + self.assertIsInstance(definitions.get_type_by_name( + 'Test', 'TestStruct'), Struct) + + def test_is_fabric_scoped(self): + definitions = SpecDefinitions( + [ParseSource(source=io.StringIO(source_struct), name='source_struct')]) + + struct = definitions.get_struct_by_name('Test', 'TestStruct') + self.assertFalse(definitions.is_fabric_scoped(struct)) + + struct = definitions.get_struct_by_name( + 'Test', 'TestStructFabricScoped') + self.assertTrue(definitions.is_fabric_scoped(struct)) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/tests/test_yaml_parser.py b/scripts/py_matter_yamltests/test_yaml_parser.py similarity index 92% rename from scripts/tests/test_yaml_parser.py rename to scripts/py_matter_yamltests/test_yaml_parser.py index c6a73da4f8eed9..78df2c35fe64ad 100644 --- a/scripts/tests/test_yaml_parser.py +++ b/scripts/py_matter_yamltests/test_yaml_parser.py @@ -23,8 +23,8 @@ import tempfile import unittest -from yamltests.definitions import * -from yamltests.parser import TestParser +from matter_yamltests.definitions import * +from matter_yamltests.parser import TestParser simple_test_description = ''' @@ -75,7 +75,8 @@ def setUp(self): with open(self._temp_file.name, 'w') as f: f.writelines(simple_test_yaml) pics_file = None - self._yaml_parser = TestParser(self._temp_file.name, pics_file, self._definitions) + self._yaml_parser = TestParser( + self._temp_file.name, pics_file, self._definitions) def test_able_to_iterate_over_all_parsed_tests(self): # self._yaml_parser.tests implements `__next__`, which does value substitution. We are diff --git a/scripts/requirements.txt b/scripts/requirements.txt index b39ec86833bf6e..eb7b423cd90b05 100644 --- a/scripts/requirements.txt +++ b/scripts/requirements.txt @@ -69,8 +69,9 @@ tabulate # scripts/build click -# scripts/idl +# scripts/py_matter_idl/matter_idl lark +# scripts/py_matter_idl/matter_idl and scripts/py_matter_yamtests/matter_yamltests stringcase cryptography diff --git a/scripts/tests/yamltests/test_spec_definitions.py b/scripts/tests/yamltests/test_spec_definitions.py deleted file mode 100644 index 00a15da9940d0c..00000000000000 --- a/scripts/tests/yamltests/test_spec_definitions.py +++ /dev/null @@ -1,291 +0,0 @@ -#!/usr/bin/env -S python3 -B -# -# 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. - -from definitions import * - -import unittest -import io - -source_cluster = ''' - - - Test - 0x1234 - - -''' - -source_command = ''' - - - Test - 0x1234 - - - - - -''' - -source_response = ''' - - - Test - 0x1234 - - - - - - - -''' - -source_attribute = ''' - - - TestGlobalAttribute - - - - Test - 0x1234 - - - TestAttribute - - - -''' - -source_event = ''' - - - Test - 0x1234 - - - - - -''' - -source_bitmap = ''' - - - - - - - - - - - - - Test - 0x1234 - - - - TestWrong - 0x4321 - - -''' - -source_enum = ''' - - - - - - - - - - - - - Test - 0x1234 - - - - TestWrong - 0x4321 - - -''' - -source_struct = ''' - - - - - - - - - - - - - - - - - - Test - 0x1234 - - - - TestWrong - 0x4321 - - -''' - - -class TestSpecDefinitions(unittest.TestCase): - def test_cluster_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_cluster), name='source_cluster')]) - self.assertIsNone(definitions.get_cluster_name(0x4321)) - self.assertEqual(definitions.get_cluster_name(0x1234), 'Test') - - def test_command_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_command), name='source_command')]) - self.assertIsNone(definitions.get_command_name(0x4321, 0x0)) - self.assertIsNone(definitions.get_command_name(0x1234, 0x1)) - self.assertEqual(definitions.get_command_name(0x1234, 0x0), 'TestCommand') - - def test_response_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_response), name='source_response')]) - self.assertIsNone(definitions.get_response_name(0x4321, 0x0)) - self.assertIsNone(definitions.get_response_name(0x1234, 0x1)) - self.assertEqual(definitions.get_response_name(0x1234, 0x0), 'TestCommandResponse') - - def test_attribute_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) - self.assertIsNone(definitions.get_attribute_name(0x4321, 0x0)) - self.assertIsNone(definitions.get_attribute_name(0x4321, 0xFFFD)) - self.assertIsNone(definitions.get_attribute_name(0x1234, 0x1)) - self.assertEqual(definitions.get_attribute_name(0x1234, 0x0), 'TestAttribute') - self.assertEqual(definitions.get_attribute_name(0x1234, 0xFFFD), 'TestGlobalAttribute') - - def test_event_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_event), name='source_event')]) - self.assertIsNone(definitions.get_event_name(0x4321, 0x0)) - self.assertIsNone(definitions.get_event_name(0x1234, 0x1)) - self.assertEqual(definitions.get_event_name(0x1234, 0x0), 'TestEvent') - - def test_get_command_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_command), name='source_command')]) - self.assertIsNone(definitions.get_command_by_name('WrongName', 'TestCommand')) - self.assertIsNone(definitions.get_command_by_name('Test', 'TestWrongCommand')) - self.assertIsNone(definitions.get_response_by_name('Test', 'TestCommand')) - self.assertIsInstance(definitions.get_command_by_name('Test', 'TestCommand'), Command) - self.assertIsNone(definitions.get_command_by_name('test', 'TestCommand')) - self.assertIsInstance(definitions.get_command_by_name('Test', 'testcommand'), Command) - - def test_get_response_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_response), name='source_response')]) - self.assertIsNone(definitions.get_response_by_name('WrongName', 'TestCommandResponse')) - self.assertIsNone(definitions.get_response_by_name('Test', 'TestWrongCommandResponse')) - self.assertIsNone(definitions.get_command_by_name('Test', 'TestCommandResponse')) - self.assertIsInstance(definitions.get_response_by_name('Test', 'TestCommandResponse'), Struct) - self.assertIsNone(definitions.get_response_by_name('test', 'TestCommandResponse')) - self.assertIsInstance(definitions.get_response_by_name('Test', 'testcommandresponse'), Struct) - - def test_get_attribute_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) - self.assertIsNone(definitions.get_attribute_by_name('WrongName', 'TestAttribute')) - self.assertIsNone(definitions.get_attribute_by_name('WrongName', 'TestGlobalAttribute')) - self.assertIsNone(definitions.get_attribute_by_name('Test', 'TestWrongAttribute')) - self.assertIsInstance(definitions.get_attribute_by_name('Test', 'TestAttribute'), Attribute) - self.assertIsInstance(definitions.get_attribute_by_name('Test', 'TestGlobalAttribute'), Attribute) - self.assertIsNone(definitions.get_attribute_by_name('test', 'TestAttribute')) - self.assertIsNone(definitions.get_attribute_by_name('test', 'TestGlobalAttribute')) - self.assertIsInstance(definitions.get_attribute_by_name('Test', 'testattribute'), Attribute) - self.assertIsInstance(definitions.get_attribute_by_name('Test', 'testglobalattribute'), Attribute) - - def test_get_event_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_event), name='source_event')]) - self.assertIsNone(definitions.get_event_by_name('WrongName', 'TestEvent')) - self.assertIsNone(definitions.get_event_by_name('Test', 'TestWrongEvent')) - self.assertIsInstance(definitions.get_event_by_name('Test', 'TestEvent'), Event) - self.assertIsNone(definitions.get_event_by_name('test', 'TestEvent')) - self.assertIsInstance(definitions.get_event_by_name('Test', 'testevent'), Event) - - def test_get_bitmap_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_bitmap), name='source_bitmap')]) - self.assertIsNone(definitions.get_bitmap_by_name('WrongName', 'TestBitmap')) - self.assertIsNone(definitions.get_bitmap_by_name('Test', 'TestWrongBitmap')) - self.assertIsInstance(definitions.get_bitmap_by_name('Test', 'TestBitmap'), Bitmap) - self.assertIsNone(definitions.get_bitmap_by_name('test', 'TestBitmap')) - self.assertIsInstance(definitions.get_bitmap_by_name('Test', 'testbitmap'), Bitmap) - - def test_get_enum_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_enum), name='source_enum')]) - self.assertIsNone(definitions.get_enum_by_name('WrongName', 'TestEnum')) - self.assertIsNone(definitions.get_enum_by_name('Test', 'TestWrongEnum')) - self.assertIsInstance(definitions.get_enum_by_name('Test', 'TestEnum'), Enum) - self.assertIsNone(definitions.get_enum_by_name('test', 'TestEnum')) - self.assertIsInstance(definitions.get_enum_by_name('Test', 'testenum'), Enum) - - def test_get_struct_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_struct), name='source_struct')]) - self.assertIsNone(definitions.get_struct_by_name('WrongName', 'TestStruct')) - self.assertIsNone(definitions.get_struct_by_name('Test', 'TestWrongStruct')) - self.assertIsInstance(definitions.get_struct_by_name('Test', 'TestStruct'), Struct) - self.assertIsNone(definitions.get_struct_by_name('test', 'TestStruct')) - self.assertIsInstance(definitions.get_struct_by_name('Test', 'teststruct'), Struct) - - def test_get_type_by_name(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_command), name='source_command')]) - self.assertIsNone(definitions.get_type_by_name('Test', 'TestCommand')) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_response), name='source_response')]) - self.assertIsInstance(definitions.get_type_by_name('Test', 'TestCommandResponse'), Struct) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_attribute), name='source_attribute')]) - self.assertIsNone(definitions.get_type_by_name('Test', 'TestAttribute')) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_event), name='source_event')]) - self.assertIsNone(definitions.get_type_by_name('Test', 'TestEvent')) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_bitmap), name='source_bitmap')]) - self.assertIsInstance(definitions.get_type_by_name('Test', 'TestBitmap'), Bitmap) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_enum), name='source_enum')]) - self.assertIsInstance(definitions.get_type_by_name('Test', 'TestEnum'), Enum) - - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_struct), name='source_struct')]) - self.assertIsInstance(definitions.get_type_by_name('Test', 'TestStruct'), Struct) - - def test_is_fabric_scoped(self): - definitions = SpecDefinitions([ParseSource(source=io.StringIO(source_struct), name='source_struct')]) - - struct = definitions.get_struct_by_name('Test', 'TestStruct') - self.assertFalse(definitions.is_fabric_scoped(struct)) - - struct = definitions.get_struct_by_name('Test', 'TestStructFabricScoped') - self.assertTrue(definitions.is_fabric_scoped(struct)) - - -if __name__ == '__main__': - unittest.main() From 285f4ef09fd7facdc1fcea3fed798195be44308c Mon Sep 17 00:00:00 2001 From: Terence Hampson Date: Thu, 5 Jan 2023 12:52:26 -0500 Subject: [PATCH 26/31] Cleanup after matter_idl, matter_yamltests PR merged (#24283) --- BUILD.gn | 2 +- scripts/BUILD.gn | 6 +++--- scripts/py_matter_yamltests/setup.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 23bc58926aac8d..ce3a154774d272 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -122,7 +122,7 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { pw_python_pip_install("pip_install_matter_packages") { packages = [ "//examples/common/pigweed/rpc_console:chip_rpc_distribution", - "//scripts:yamltests_distribution", + "//scripts:matter_yamltests_distribution", ] } diff --git a/scripts/BUILD.gn b/scripts/BUILD.gn index 878102414b89ce..e14db546195de5 100644 --- a/scripts/BUILD.gn +++ b/scripts/BUILD.gn @@ -20,9 +20,9 @@ import("$dir_pw_build/python_dist.gni") # This target creates a single Python package and wheel for yamltests. It will # merge all Python dependencies Matter. The output is located in: -# out/obj/yamltests_distribution/ <- source files here -# out/obj/yamltests_distribution._build_wheel/yamltests-0.0.1-py3-none-any.whl -pw_python_distribution("yamltests_distribution") { +# out/obj/matter_yamltests_distribution/ <- source files here +# out/obj/matter_yamltests_distribution._build_wheel/matter_yamltests-0.0.1-py3-none-any.whl +pw_python_distribution("matter_yamltests_distribution") { packages = [ "${chip_root}/scripts/py_matter_yamltests:matter_yamltests" ] generate_setup_cfg = { common_config_file = "common_setup.cfg" diff --git a/scripts/py_matter_yamltests/setup.py b/scripts/py_matter_yamltests/setup.py index 2d7f786e1957f6..8917fa45238cf5 100644 --- a/scripts/py_matter_yamltests/setup.py +++ b/scripts/py_matter_yamltests/setup.py @@ -13,7 +13,7 @@ # limitations under the License. -"""The yamltests package.""" +"""The matter_yamltests package.""" import setuptools # type: ignore From adfb786808420a1a4fde0c92d9152e556290923c Mon Sep 17 00:00:00 2001 From: Evgeny Margolis Date: Thu, 5 Jan 2023 09:57:21 -0800 Subject: [PATCH 27/31] [crypto] Added Method That Finds and Replaces Resigned Version of a Certificate (#24212) * [crypto] Added Method That Finds and Replaces Resigned Version of a Certificate. This method checks for resigned version of the reference certificate in the list and returns it. The following conditions SHOULD be satisfied for the certificate to qualify as a resigned version of a reference certificate: - SKID of the candidate and the reference certificate should match. - SubjectDN of the candidate and the reference certificate should match. There is no specific use case for this method in Matter. However, specific ecosystem implementations may find this method useful. Some of the potential use cases could be finding resigned version of a PAI or DAC certificate. Also, this method can be useful when Matter introduces attestation certificate revocation mechanism. * Updated function description. --- .../Chip-Test-PAA-NoVID-ToResignPAIs-Cert.der | Bin 0 -> 436 bytes .../Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem | 12 ++ .../Chip-Test-PAI-FFF2-8001-Resigned-Cert.der | Bin 0 -> 465 bytes .../Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem | 12 ++ ...st-PAI-FFF2-8001-ResignedSKIDDiff-Cert.der | Bin 0 -> 464 bytes ...st-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem | 12 ++ ...est-PAI-FFF2-8001-ResignedSKIDDiff-Key.der | Bin 0 -> 121 bytes ...est-PAI-FFF2-8001-ResignedSKIDDiff-Key.pem | 5 + ...PAI-FFF2-8001-ResignedSubjectDiff-Cert.der | Bin 0 -> 474 bytes ...PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem | 12 ++ ...Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.der | Bin 0 -> 443 bytes ...Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.pem | 12 ++ .../test/gen-test-attestation-certs.sh | 62 ++++-- .../tests/CHIPAttCert_test_vectors.cpp | 199 ++++++++++++++++++ .../tests/CHIPAttCert_test_vectors.h | 17 ++ src/crypto/CHIPCryptoPAL.h | 23 ++ src/crypto/CHIPCryptoPALOpenSSL.cpp | 60 ++++++ src/crypto/CHIPCryptoPALTinyCrypt.cpp | 77 +++++++ src/crypto/CHIPCryptoPALmbedTLS.cpp | 77 +++++++ src/crypto/tests/CHIPCryptoPALTest.cpp | 82 ++++++++ .../silabs/EFR32/CHIPCryptoPALPsaEfr32.cpp | 77 +++++++ 21 files changed, 727 insertions(+), 12 deletions(-) create mode 100644 credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.der create mode 100644 credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.der create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.der create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Key.der create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Key.pem create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.der create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.der create mode 100644 credentials/test/attestation/Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.pem diff --git a/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.der b/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.der new file mode 100644 index 0000000000000000000000000000000000000000..93f956666154af3402ae150ef869fb5dde9d9a44 GIT binary patch literal 436 zcmXqLV%%WR#2B`KnTe5!iKCW*OI&&1eKrFwHV&;ek8`#x%uEKFhUx~YY|No7%sg_w zi6teeMG7IQ#U%;>j*bc;`3ga)#hK}OK%Qr@fr2=%k)eT^k%gg&k+F$!lmx#e5EvR6 z1Cgnvsbv%?hD90(v$2C+!Ndr44l^S=vl9c0zQh)uMTJZKup7E!b9Qab-p3%TOk6poQahgGjfe_G3 zvcimv|5-Q;*nkuhBclNyNQ@sO2J|>1n}IBd&&MLhB2p3aoOMTbzhD0G$*U4hJHN`z zXu4`350X}9kuVTzz^(u(7@0j73|yHMs*}HNy3s!UQt}4-we5SYd)oGV;GdblqWHyM w{f2}?viVGk43i%EZ2mU=V1G}muY5tszI>_G=gxe-I*;elp(375A5N430QOUn-2eap literal 0 HcmV?d00001 diff --git a/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem b/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem new file mode 100644 index 00000000000000..5c28c0a147b4a6 --- /dev/null +++ b/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIBsDCCAVagAwIBAgIIfQAKFyO+3wYwCgYIKoZIzj0EAwIwKTEnMCUGA1UEAwwe +TWF0dGVyIFRlc3QgUEFBIFRvIFJlc2lnbiBQQUlzMCAXDTIxMDYyODE0MjM0M1oY +Dzk5OTkxMjMxMjM1OTU5WjApMScwJQYDVQQDDB5NYXR0ZXIgVGVzdCBQQUEgVG8g +UmVzaWduIFBBSXMwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQQ7wKoGoe2gSH7 +qNMZePgHoxflCqioKERoKJFLkz3o7dSlw5yf9xpM42R/1/YmU7fSSV/LpMD0f4do +gAOeByBKo2YwZDASBgNVHRMBAf8ECDAGAQH/AgEBMA4GA1UdDwEB/wQEAwIBBjAd +BgNVHQ4EFgQUeFznBbhrj05vx5OqYMtD6mlogtUwHwYDVR0jBBgwFoAUeFznBbhr +j05vx5OqYMtD6mlogtUwCgYIKoZIzj0EAwIDSAAwRQIge2P1stiHl9JjsD+th707 +jIa88A+Zb6hz6P0vgGDCHW8CIQCS4Uyz9pfBj4yFTR9wVL5vGqvOzPPVngzSwnIM +svDIdg== +-----END CERTIFICATE----- diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.der b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.der new file mode 100644 index 0000000000000000000000000000000000000000..bb13cb0f7d8247bb52154313175c97aa02bb3758 GIT binary patch literal 465 zcmXqLVmxcm#8|w5nTe5!i6g1#_$n@8g}DY?Y#dr`9_MUXn3)VT4b=@)*_cCFn0e%U z6H7``ixfgqi%S#&932%x@)d$oi!;;nfIQD)0|jwjBSQl-BMUnF^FOOsD^nOiWms7acQ$LvM@F+s$pW}VR3VFGeQ$(;$g8cFfcTT zG!SNE2Ro685$aZEMs{W=1{NJQ8-?!e=j}Uh%qiHEaqrNFwVjgsO!`yZ*PbcTVr$4e zRb-mbyj`VSTCvP$lTWzdR=a=g|NI|pDHf4Fvyf#|@8UFr6re+xLuG{-8UM3z7_b2; zCPoGWK9CqcNDLS%jBEz7AU+?97>me-sM+a-3l~?-J~(&ki>M zO3X`b#gnJ@9iM&GSK^rrlS0{r=ki})1iZS-ex+Hi)a_#BwMW}-JUk}8CT!`Og&|B9 E0Ly-lJOBUy literal 0 HcmV?d00001 diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem new file mode 100644 index 00000000000000..b3620594118e4a --- /dev/null +++ b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIBzTCCAXOgAwIBAgIIYnLHqgoTIJ0wCgYIKoZIzj0EAwIwKTEnMCUGA1UEAwwe +TWF0dGVyIFRlc3QgUEFBIFRvIFJlc2lnbiBQQUlzMCAXDTIxMDYyODE0MjM0M1oY +Dzk5OTkxMjMxMjM1OTU5WjBGMRgwFgYDVQQDDA9NYXR0ZXIgVGVzdCBQQUkxFDAS +BgorBgEEAYKifAIBDARGRkYyMRQwEgYKKwYBBAGConwCAgwEODAwMTBZMBMGByqG +SM49AgEGCCqGSM49AwEHA0IABCwGPCCLt88/idiccLJo3sLwrYkZLwIvlUetzHIq +BoBpynI1YIO3JHcbIXZMskxXEbU+/of+T+C0cxQbzKEEso2jZjBkMBIGA1UdEwEB +/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTQWptncaGjepvB +nZXotduPQwC2OjAfBgNVHSMEGDAWgBR4XOcFuGuPTm/Hk6pgy0PqaWiC1TAKBggq +hkjOPQQDAgNIADBFAiEAnw1UN+kJn4U4ylMO6J0qs2QkXOkrIcnKvseb1U0Y5hwC +IHbQ5x/16FDq3QfUgx51RtF51uK22OHGF6xWpeyhVAI4 +-----END CERTIFICATE----- diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.der b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.der new file mode 100644 index 0000000000000000000000000000000000000000..89b0d9ded65a0b420c86edd3f63f0b3956b91284 GIT binary patch literal 464 zcmXqLVmxEe#8|w5nTe5!iNoLK(A|x)M@}1Xv2kd%d7QIlVP-PWG*mZGWn&IyVdjzZ zO)M!%Em8GqcU8w0GmAAo^PX59cbp?~_t)YygA|}cm_ucS85#exa2T)w zDJDh+13r)#KS&H1DvWFfvLHSmix`W@?ea^}$+;{R3n$4q1_{``dUV8^-9R2Bt;_=S zZi7fg%yZTq+5LX`$0x5!IPLr@Go$G$au_qaGZ?rqDX_{Ln1ua(&G`TClgjzOx7g-h z^hh=7x@JFV*XdIUCuB646aDJq{33c+V%Dh)xg9Je|av%@hmw~aN;8X DU9633 literal 0 HcmV?d00001 diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem new file mode 100644 index 00000000000000..3eed75c53562ae --- /dev/null +++ b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIBzDCCAXOgAwIBAgIITzzC3bEdxMswCgYIKoZIzj0EAwIwKTEnMCUGA1UEAwwe +TWF0dGVyIFRlc3QgUEFBIFRvIFJlc2lnbiBQQUlzMCAXDTIxMDYyODE0MjM0M1oY +Dzk5OTkxMjMxMjM1OTU5WjBGMRgwFgYDVQQDDA9NYXR0ZXIgVGVzdCBQQUkxFDAS +BgorBgEEAYKifAIBDARGRkYyMRQwEgYKKwYBBAGConwCAgwEODAwMTBZMBMGByqG +SM49AgEGCCqGSM49AwEHA0IABKH6SCo8kvOkZmOc4zVxOLakyd1EdhaOx+xcRQgr +3BvAbZuU00x53wXfxAsnEIBEC3qItDY4rEye5DnHQZwU3fqjZjBkMBIGA1UdEwEB +/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTbd9JbY20EOKGS +HEFSED7q4sQ7BzAfBgNVHSMEGDAWgBR4XOcFuGuPTm/Hk6pgy0PqaWiC1TAKBggq +hkjOPQQDAgNHADBEAiAFHzA0Vv3rAf/95Hmf+7Q9bdFIZTSK1j+SusvKYMgcKQIg +ERLDCvsqkvYALhR4OSA7Rdu4JVFhsP0M0F4MpMRwyPE= +-----END CERTIFICATE----- diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Key.der b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Key.der new file mode 100644 index 0000000000000000000000000000000000000000..b3791b55bb3686803eda260b38d29799f86f8265 GIT binary patch literal 121 zcmV-<0EYiCcLD(c1R&9_V*5?A1^%Oqqv=F+O&h?!`IM-1+{N{J7x=XpQ8l0n1_&yK zNX|V20SBQ(13~}|8|%E8H8vZJU(SOnKi0 b-^2?i5P(DrdWf_(IIK*bj*bc;`3ga)#hK}OK%Qr@fr2=%k)eT^k%gg&k+F$!lmx#e5EvR6 z1Cgnvsb!RbzoDXmJj5^wRKq->CZ(nriWms7acQ$LvM@F+s$pW}VR3VFGeQ$(;$g8c zFfcTTG!SNE2fLMt5$b4WMs{W=1{NJQ8-?!e=j}Uh%qiHEaqrNFwVjgsO!`yZ*PbcT zVr$4eRb-mbyj`VSTCvP$lTWzdR=a=g|NI|pDHf4Fvyf#|@8UFr6re+xLuG{-8UM3z z7_b2;CPoGWK9CqcNDLS}jBEz7AU+?97>me-sM+a-3l~?-J~(&ki>OwfwsDU_Mfv!@l)gX7q)^X0W#Y4E6Ay%*Ua-NdXhPYd2>s1FA9IQBJA5JL IrJ(*F0K|Kdj{pDw literal 0 HcmV?d00001 diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem new file mode 100644 index 00000000000000..3e28439c9a470f --- /dev/null +++ b/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1jCCAXygAwIBAgIIR+1jaCGXaTEwCgYIKoZIzj0EAwIwKTEnMCUGA1UEAwwe +TWF0dGVyIFRlc3QgUEFBIFRvIFJlc2lnbiBQQUlzMCAXDTIxMDYyODE0MjM0M1oY +Dzk5OTkxMjMxMjM1OTU5WjBPMSEwHwYDVQQDDBhNYXR0ZXIgVGVzdCBQQUkgUmVz +aWduZWQxFDASBgorBgEEAYKifAIBDARGRkYyMRQwEgYKKwYBBAGConwCAgwEODAw +MTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCwGPCCLt88/idiccLJo3sLwrYkZ +LwIvlUetzHIqBoBpynI1YIO3JHcbIXZMskxXEbU+/of+T+C0cxQbzKEEso2jZjBk +MBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTQ +WptncaGjepvBnZXotduPQwC2OjAfBgNVHSMEGDAWgBR4XOcFuGuPTm/Hk6pgy0Pq +aWiC1TAKBggqhkjOPQQDAgNIADBFAiEA6LLGEXBKVAZ5DMXIhzg4iQOcGO3yPV7i +VRUOD/R178kCIH8NlJHm5pHAVcugsEpykHaiWC+zueMKFb7D0FzpES/8 +-----END CERTIFICATE----- diff --git a/credentials/test/attestation/Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.der b/credentials/test/attestation/Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.der new file mode 100644 index 0000000000000000000000000000000000000000..8c7bc50d173b665fced0e0a61cb94415e37cbfa6 GIT binary patch literal 443 zcmXqLV%%=f#2CAPnTe5!i6fRP@_@Lvb*cdu8;4e#$2nUTW+nqoLv;gHHs(+kW*#}; z#FCQKB88CD;u3`bM@NN_e1)LY;>`3sAkVYdKtY_>$k4#d$imRX$k@ayk zfymU-)H2Gzz)-?K3}P5Rs$rgnA_hWiT-t1mER0QyYM2;#Slry)j0_?TgxT1^j$vYi zx{8^Ro!N~)!u*ia{mwi&qza1xD%F`99 z*%?%(csOsml|)Y1g;O_YZg4zQuyW&R`^9MnDL^ZkLuG{-8UM3z7_b2;CPoGWK9Cqc zNDSzIMm7Uk5TB1lj722T_CmX9+=uRUj8Bfu>OXF~rl>"$output_cstyle_file".h printf "$namespaces_open\n" >>"$output_cstyle_file".cpp printf "$namespaces_open\n" >>"$output_cstyle_file".h - for cert_file_pem in credentials/test/attestation/*Cert.pem; do + for cert_file_pem in "$dest_dir"/*Cert.pem; do params_prefix="${cert_file_pem/*Chip-Test/sTestCert}" params_prefix="${params_prefix//-/_}" params_prefix="${params_prefix/_Cert.pem/}" @@ -387,24 +418,31 @@ namespace TestCerts { printf "};\n\n" printf "extern const ByteSpan ${params_prefix}_SKID = ByteSpan(${params_prefix}_SKID_Array);\n\n" - printf "// \${chip_root}/$key_file_pem\n\n" + # Print key data if present + if test -f "$key_file_pem"; then + printf "// \${chip_root}/$key_file_pem\n\n" - printf "constexpr uint8_t ${params_prefix}_PublicKey_Array[] = {\n" - openssl ec -text -noout -in "$key_file_pem" | sed '0,/pub:$/d' | sed '/ASN1 OID:/,$d' | sed 's/:/ /g' | sed 's/\/,/g' | sed "s/^[ \t]*/ /" | sed 's/ *$//' - printf "};\n\n" - printf "extern const ByteSpan ${params_prefix}_PublicKey = ByteSpan(${params_prefix}_PublicKey_Array);\n\n" + printf "constexpr uint8_t ${params_prefix}_PublicKey_Array[] = {\n" + openssl ec -text -noout -in "$key_file_pem" | sed '0,/pub:$/d' | sed '/ASN1 OID:/,$d' | sed 's/:/ /g' | sed 's/\/,/g' | sed "s/^[ \t]*/ /" | sed 's/ *$//' + printf "};\n\n" + printf "extern const ByteSpan ${params_prefix}_PublicKey = ByteSpan(${params_prefix}_PublicKey_Array);\n\n" - printf "constexpr uint8_t ${params_prefix}_PrivateKey_Array[] = {\n" - openssl ec -text -noout -in "$key_file_pem" | sed '0,/priv:$/d' | sed '/pub:/,$d' | sed 's/:/ /g' | sed 's/\/,/g' | sed "s/^[ \t]*/ /" | sed 's/ *$//' - printf "};\n\n" - printf "extern const ByteSpan ${params_prefix}_PrivateKey = ByteSpan(${params_prefix}_PrivateKey_Array);\n\n" + printf "constexpr uint8_t ${params_prefix}_PrivateKey_Array[] = {\n" + openssl ec -text -noout -in "$key_file_pem" | sed '0,/priv:$/d' | sed '/pub:/,$d' | sed 's/:/ /g' | sed 's/\/,/g' | sed "s/^[ \t]*/ /" | sed 's/ *$//' + printf "};\n\n" + printf "extern const ByteSpan ${params_prefix}_PrivateKey = ByteSpan(${params_prefix}_PrivateKey_Array);\n\n" + fi } >>"$output_cstyle_file".cpp { printf "extern const ByteSpan ${params_prefix}_Cert;\n" printf "extern const ByteSpan ${params_prefix}_SKID;\n" - printf "extern const ByteSpan ${params_prefix}_PublicKey;\n" - printf "extern const ByteSpan ${params_prefix}_PrivateKey;\n\n" + # Print key data if present + if test -f "$key_file_pem"; then + printf "extern const ByteSpan ${params_prefix}_PublicKey;\n" + printf "extern const ByteSpan ${params_prefix}_PrivateKey;\n" + fi + printf "\n" } >>"$output_cstyle_file".h done diff --git a/src/credentials/tests/CHIPAttCert_test_vectors.cpp b/src/credentials/tests/CHIPAttCert_test_vectors.cpp index 0bb32b7b72f32a..82cda1285d8980 100644 --- a/src/credentials/tests/CHIPAttCert_test_vectors.cpp +++ b/src/credentials/tests/CHIPAttCert_test_vectors.cpp @@ -2596,6 +2596,40 @@ constexpr uint8_t sTestCert_PAA_NoVID_PrivateKey_Array[] = { extern const ByteSpan sTestCert_PAA_NoVID_PrivateKey = ByteSpan(sTestCert_PAA_NoVID_PrivateKey_Array); +// ${chip_root}/credentials/test/attestation/Chip-Test-PAA-NoVID-ToResignPAIs-Cert.pem + +constexpr uint8_t sTestCert_PAA_NoVID_ToResignPAIs_Cert_Array[] = { + 0x30, 0x82, 0x01, 0xb0, 0x30, 0x82, 0x01, 0x56, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x7d, 0x00, 0x0a, 0x17, 0x23, 0xbe, + 0xdf, 0x06, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, + 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, + 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, + 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, + 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x10, 0xef, 0x02, 0xa8, 0x1a, 0x87, 0xb6, + 0x81, 0x21, 0xfb, 0xa8, 0xd3, 0x19, 0x78, 0xf8, 0x07, 0xa3, 0x17, 0xe5, 0x0a, 0xa8, 0xa8, 0x28, 0x44, 0x68, 0x28, 0x91, 0x4b, + 0x93, 0x3d, 0xe8, 0xed, 0xd4, 0xa5, 0xc3, 0x9c, 0x9f, 0xf7, 0x1a, 0x4c, 0xe3, 0x64, 0x7f, 0xd7, 0xf6, 0x26, 0x53, 0xb7, 0xd2, + 0x49, 0x5f, 0xcb, 0xa4, 0xc0, 0xf4, 0x7f, 0x87, 0x68, 0x80, 0x03, 0x9e, 0x07, 0x20, 0x4a, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, + 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x01, 0x30, 0x0e, 0x06, + 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, + 0x16, 0x04, 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, 0x8f, 0x4e, 0x6f, 0xc7, 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, + 0x82, 0xd5, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, + 0x8f, 0x4e, 0x6f, 0xc7, 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, 0x82, 0xd5, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x7b, 0x63, 0xf5, 0xb2, 0xd8, 0x87, 0x97, 0xd2, 0x63, + 0xb0, 0x3f, 0xad, 0x87, 0xbd, 0x3b, 0x8c, 0x86, 0xbc, 0xf0, 0x0f, 0x99, 0x6f, 0xa8, 0x73, 0xe8, 0xfd, 0x2f, 0x80, 0x60, 0xc2, + 0x1d, 0x6f, 0x02, 0x21, 0x00, 0x92, 0xe1, 0x4c, 0xb3, 0xf6, 0x97, 0xc1, 0x8f, 0x8c, 0x85, 0x4d, 0x1f, 0x70, 0x54, 0xbe, 0x6f, + 0x1a, 0xab, 0xce, 0xcc, 0xf3, 0xd5, 0x9e, 0x0c, 0xd2, 0xc2, 0x72, 0x0c, 0xb2, 0xf0, 0xc8, 0x76, +}; + +extern const ByteSpan sTestCert_PAA_NoVID_ToResignPAIs_Cert = ByteSpan(sTestCert_PAA_NoVID_ToResignPAIs_Cert_Array); + +constexpr uint8_t sTestCert_PAA_NoVID_ToResignPAIs_SKID_Array[] = { + 0x78, 0x5C, 0xE7, 0x05, 0xB8, 0x6B, 0x8F, 0x4E, 0x6F, 0xC7, 0x93, 0xAA, 0x60, 0xCB, 0x43, 0xEA, 0x69, 0x68, 0x82, 0xD5, +}; + +extern const ByteSpan sTestCert_PAA_NoVID_ToResignPAIs_SKID = ByteSpan(sTestCert_PAA_NoVID_ToResignPAIs_SKID_Array); + // ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF1-8000-Cert.pem constexpr uint8_t sTestCert_PAI_FFF1_8000_Cert_Array[] = { @@ -2703,6 +2737,136 @@ constexpr uint8_t sTestCert_PAI_FFF2_8001_PrivateKey_Array[] = { extern const ByteSpan sTestCert_PAI_FFF2_8001_PrivateKey = ByteSpan(sTestCert_PAI_FFF2_8001_PrivateKey_Array); +// ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-Resigned-Cert.pem + +constexpr uint8_t sTestCert_PAI_FFF2_8001_Resigned_Cert_Array[] = { + 0x30, 0x82, 0x01, 0xcd, 0x30, 0x82, 0x01, 0x73, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x62, 0x72, 0xc7, 0xaa, 0x0a, 0x13, + 0x20, 0x9d, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, + 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, + 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x46, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x4d, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x49, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, + 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x32, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, + 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30, 0x13, 0x06, + 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, + 0x04, 0x2c, 0x06, 0x3c, 0x20, 0x8b, 0xb7, 0xcf, 0x3f, 0x89, 0xd8, 0x9c, 0x70, 0xb2, 0x68, 0xde, 0xc2, 0xf0, 0xad, 0x89, 0x19, + 0x2f, 0x02, 0x2f, 0x95, 0x47, 0xad, 0xcc, 0x72, 0x2a, 0x06, 0x80, 0x69, 0xca, 0x72, 0x35, 0x60, 0x83, 0xb7, 0x24, 0x77, 0x1b, + 0x21, 0x76, 0x4c, 0xb2, 0x4c, 0x57, 0x11, 0xb5, 0x3e, 0xfe, 0x87, 0xfe, 0x4f, 0xe0, 0xb4, 0x73, 0x14, 0x1b, 0xcc, 0xa1, 0x04, + 0xb2, 0x8d, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, + 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, + 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xd0, 0x5a, 0x9b, 0x67, 0x71, 0xa1, 0xa3, 0x7a, 0x9b, 0xc1, + 0x9d, 0x95, 0xe8, 0xb5, 0xdb, 0x8f, 0x43, 0x00, 0xb6, 0x3a, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, + 0x80, 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, 0x8f, 0x4e, 0x6f, 0xc7, 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, 0x82, + 0xd5, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, + 0x9f, 0x0d, 0x54, 0x37, 0xe9, 0x09, 0x9f, 0x85, 0x38, 0xca, 0x53, 0x0e, 0xe8, 0x9d, 0x2a, 0xb3, 0x64, 0x24, 0x5c, 0xe9, 0x2b, + 0x21, 0xc9, 0xca, 0xbe, 0xc7, 0x9b, 0xd5, 0x4d, 0x18, 0xe6, 0x1c, 0x02, 0x20, 0x76, 0xd0, 0xe7, 0x1f, 0xf5, 0xe8, 0x50, 0xea, + 0xdd, 0x07, 0xd4, 0x83, 0x1e, 0x75, 0x46, 0xd1, 0x79, 0xd6, 0xe2, 0xb6, 0xd8, 0xe1, 0xc6, 0x17, 0xac, 0x56, 0xa5, 0xec, 0xa1, + 0x54, 0x02, 0x38, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_Resigned_Cert = ByteSpan(sTestCert_PAI_FFF2_8001_Resigned_Cert_Array); + +constexpr uint8_t sTestCert_PAI_FFF2_8001_Resigned_SKID_Array[] = { + 0xD0, 0x5A, 0x9B, 0x67, 0x71, 0xA1, 0xA3, 0x7A, 0x9B, 0xC1, 0x9D, 0x95, 0xE8, 0xB5, 0xDB, 0x8F, 0x43, 0x00, 0xB6, 0x3A, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_Resigned_SKID = ByteSpan(sTestCert_PAI_FFF2_8001_Resigned_SKID_Array); + +// ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Cert.pem + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert_Array[] = { + 0x30, 0x82, 0x01, 0xcc, 0x30, 0x82, 0x01, 0x73, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x4f, 0x3c, 0xc2, 0xdd, 0xb1, 0x1d, + 0xc4, 0xcb, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, + 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, + 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x46, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x4d, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x49, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, + 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x32, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, + 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x02, 0x0c, 0x04, 0x38, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30, 0x13, 0x06, + 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, + 0x04, 0xa1, 0xfa, 0x48, 0x2a, 0x3c, 0x92, 0xf3, 0xa4, 0x66, 0x63, 0x9c, 0xe3, 0x35, 0x71, 0x38, 0xb6, 0xa4, 0xc9, 0xdd, 0x44, + 0x76, 0x16, 0x8e, 0xc7, 0xec, 0x5c, 0x45, 0x08, 0x2b, 0xdc, 0x1b, 0xc0, 0x6d, 0x9b, 0x94, 0xd3, 0x4c, 0x79, 0xdf, 0x05, 0xdf, + 0xc4, 0x0b, 0x27, 0x10, 0x80, 0x44, 0x0b, 0x7a, 0x88, 0xb4, 0x36, 0x38, 0xac, 0x4c, 0x9e, 0xe4, 0x39, 0xc7, 0x41, 0x9c, 0x14, + 0xdd, 0xfa, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, + 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, + 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xdb, 0x77, 0xd2, 0x5b, 0x63, 0x6d, 0x04, 0x38, 0xa1, 0x92, + 0x1c, 0x41, 0x52, 0x10, 0x3e, 0xea, 0xe2, 0xc4, 0x3b, 0x07, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, + 0x80, 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, 0x8f, 0x4e, 0x6f, 0xc7, 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, 0x82, + 0xd5, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x05, + 0x1f, 0x30, 0x34, 0x56, 0xfd, 0xeb, 0x01, 0xff, 0xfd, 0xe4, 0x79, 0x9f, 0xfb, 0xb4, 0x3d, 0x6d, 0xd1, 0x48, 0x65, 0x34, 0x8a, + 0xd6, 0x3f, 0x92, 0xba, 0xcb, 0xca, 0x60, 0xc8, 0x1c, 0x29, 0x02, 0x20, 0x11, 0x12, 0xc3, 0x0a, 0xfb, 0x2a, 0x92, 0xf6, 0x00, + 0x2e, 0x14, 0x78, 0x39, 0x20, 0x3b, 0x45, 0xdb, 0xb8, 0x25, 0x51, 0x61, 0xb0, 0xfd, 0x0c, 0xd0, 0x5e, 0x0c, 0xa4, 0xc4, 0x70, + 0xc8, 0xf1, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert = ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert_Array); + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_SKID_Array[] = { + 0xDB, 0x77, 0xD2, 0x5B, 0x63, 0x6D, 0x04, 0x38, 0xA1, 0x92, 0x1C, 0x41, 0x52, 0x10, 0x3E, 0xEA, 0xE2, 0xC4, 0x3B, 0x07, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_SKID = ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_SKID_Array); + +// ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSKIDDiff-Key.pem + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PublicKey_Array[] = { + 0x04, 0xa1, 0xfa, 0x48, 0x2a, 0x3c, 0x92, 0xf3, 0xa4, 0x66, 0x63, 0x9c, 0xe3, 0x35, 0x71, 0x38, 0xb6, + 0xa4, 0xc9, 0xdd, 0x44, 0x76, 0x16, 0x8e, 0xc7, 0xec, 0x5c, 0x45, 0x08, 0x2b, 0xdc, 0x1b, 0xc0, 0x6d, + 0x9b, 0x94, 0xd3, 0x4c, 0x79, 0xdf, 0x05, 0xdf, 0xc4, 0x0b, 0x27, 0x10, 0x80, 0x44, 0x0b, 0x7a, 0x88, + 0xb4, 0x36, 0x38, 0xac, 0x4c, 0x9e, 0xe4, 0x39, 0xc7, 0x41, 0x9c, 0x14, 0xdd, 0xfa, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PublicKey = + ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PublicKey_Array); + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PrivateKey_Array[] = { + 0xd1, 0xae, 0x62, 0xfb, 0x4d, 0xb3, 0x05, 0xfe, 0xa3, 0x8c, 0xa3, 0xe9, 0x44, 0x74, 0x4d, 0x1b, + 0xc0, 0xbf, 0xf9, 0x94, 0xa8, 0x74, 0xdc, 0xc5, 0xf5, 0x7a, 0x17, 0xf8, 0xb5, 0x18, 0x51, 0x35, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PrivateKey = + ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PrivateKey_Array); + +// ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-8001-ResignedSubjectDiff-Cert.pem + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert_Array[] = { + 0x30, 0x82, 0x01, 0xd6, 0x30, 0x82, 0x01, 0x7c, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x47, 0xed, 0x63, 0x68, 0x21, 0x97, + 0x69, 0x31, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, + 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, + 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x4f, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x18, 0x4d, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x49, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, + 0x65, 0x64, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, + 0x46, 0x46, 0x32, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x02, 0x0c, 0x04, + 0x38, 0x30, 0x30, 0x31, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, + 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x2c, 0x06, 0x3c, 0x20, 0x8b, 0xb7, 0xcf, 0x3f, 0x89, 0xd8, 0x9c, + 0x70, 0xb2, 0x68, 0xde, 0xc2, 0xf0, 0xad, 0x89, 0x19, 0x2f, 0x02, 0x2f, 0x95, 0x47, 0xad, 0xcc, 0x72, 0x2a, 0x06, 0x80, 0x69, + 0xca, 0x72, 0x35, 0x60, 0x83, 0xb7, 0x24, 0x77, 0x1b, 0x21, 0x76, 0x4c, 0xb2, 0x4c, 0x57, 0x11, 0xb5, 0x3e, 0xfe, 0x87, 0xfe, + 0x4f, 0xe0, 0xb4, 0x73, 0x14, 0x1b, 0xcc, 0xa1, 0x04, 0xb2, 0x8d, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d, + 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, + 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xd0, + 0x5a, 0x9b, 0x67, 0x71, 0xa1, 0xa3, 0x7a, 0x9b, 0xc1, 0x9d, 0x95, 0xe8, 0xb5, 0xdb, 0x8f, 0x43, 0x00, 0xb6, 0x3a, 0x30, 0x1f, + 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, 0x8f, 0x4e, 0x6f, 0xc7, + 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, 0x82, 0xd5, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, + 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x21, 0x00, 0xe8, 0xb2, 0xc6, 0x11, 0x70, 0x4a, 0x54, 0x06, 0x79, 0x0c, 0xc5, 0xc8, + 0x87, 0x38, 0x38, 0x89, 0x03, 0x9c, 0x18, 0xed, 0xf2, 0x3d, 0x5e, 0xe2, 0x55, 0x15, 0x0e, 0x0f, 0xf4, 0x75, 0xef, 0xc9, 0x02, + 0x20, 0x7f, 0x0d, 0x94, 0x91, 0xe6, 0xe6, 0x91, 0xc0, 0x55, 0xcb, 0xa0, 0xb0, 0x4a, 0x72, 0x90, 0x76, 0xa2, 0x58, 0x2f, 0xb3, + 0xb9, 0xe3, 0x0a, 0x15, 0xbe, 0xc3, 0xd0, 0x5c, 0xe9, 0x11, 0x2f, 0xfc, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert = + ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert_Array); + +constexpr uint8_t sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_SKID_Array[] = { + 0xD0, 0x5A, 0x9B, 0x67, 0x71, 0xA1, 0xA3, 0x7A, 0x9B, 0xC1, 0x9D, 0x95, 0xE8, 0xB5, 0xDB, 0x8F, 0x43, 0x00, 0xB6, 0x3A, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_SKID = + ByteSpan(sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_SKID_Array); + // ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-8004-FB-Cert.pem constexpr uint8_t sTestCert_PAI_FFF2_8004_FB_Cert_Array[] = { @@ -3129,5 +3293,40 @@ constexpr uint8_t sTestCert_PAI_FFF2_NoPID_FB_PrivateKey_Array[] = { extern const ByteSpan sTestCert_PAI_FFF2_NoPID_FB_PrivateKey = ByteSpan(sTestCert_PAI_FFF2_NoPID_FB_PrivateKey_Array); +// ${chip_root}/credentials/test/attestation/Chip-Test-PAI-FFF2-NoPID-Resigned-Cert.pem + +constexpr uint8_t sTestCert_PAI_FFF2_NoPID_Resigned_Cert_Array[] = { + 0x30, 0x82, 0x01, 0xb7, 0x30, 0x82, 0x01, 0x5d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x5d, 0x0a, 0x59, 0xc0, 0x17, 0x4b, + 0x3b, 0x65, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x29, 0x31, 0x27, 0x30, 0x25, 0x06, + 0x03, 0x55, 0x04, 0x03, 0x0c, 0x1e, 0x4d, 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x41, + 0x20, 0x54, 0x6f, 0x20, 0x52, 0x65, 0x73, 0x69, 0x67, 0x6e, 0x20, 0x50, 0x41, 0x49, 0x73, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, + 0x30, 0x36, 0x32, 0x38, 0x31, 0x34, 0x32, 0x33, 0x34, 0x33, 0x5a, 0x18, 0x0f, 0x39, 0x39, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, + 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5a, 0x30, 0x30, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x0f, 0x4d, + 0x61, 0x74, 0x74, 0x65, 0x72, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x41, 0x49, 0x31, 0x14, 0x30, 0x12, 0x06, 0x0a, 0x2b, + 0x06, 0x01, 0x04, 0x01, 0x82, 0xa2, 0x7c, 0x02, 0x01, 0x0c, 0x04, 0x46, 0x46, 0x46, 0x32, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, + 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, + 0xd8, 0xbf, 0x93, 0x47, 0x92, 0xcf, 0x8e, 0xae, 0xda, 0xc2, 0x4f, 0xfc, 0x96, 0x6c, 0x91, 0x76, 0x20, 0xfb, 0x97, 0x2f, 0xba, + 0xb9, 0x8e, 0xc6, 0xd5, 0x13, 0x14, 0xa0, 0x7a, 0xe9, 0x8e, 0x1a, 0x03, 0xfb, 0x41, 0x91, 0xd2, 0x6e, 0x2d, 0x12, 0x7c, 0xb9, + 0x52, 0x76, 0x21, 0xc3, 0x6e, 0x97, 0x3a, 0x18, 0x6c, 0x56, 0xd0, 0xca, 0xd9, 0x99, 0xb0, 0x41, 0xc2, 0x70, 0xa9, 0xb1, 0xcb, + 0x3f, 0xa3, 0x66, 0x30, 0x64, 0x30, 0x12, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x08, 0x30, 0x06, 0x01, 0x01, + 0xff, 0x02, 0x01, 0x00, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, + 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x61, 0x3d, 0xd0, 0x87, 0x35, 0x5e, 0xf0, 0x8b, 0xae, 0x01, 0xe4, + 0xc6, 0x9a, 0x8f, 0xc7, 0x3d, 0xac, 0x8c, 0x7d, 0xfd, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, + 0x14, 0x78, 0x5c, 0xe7, 0x05, 0xb8, 0x6b, 0x8f, 0x4e, 0x6f, 0xc7, 0x93, 0xaa, 0x60, 0xcb, 0x43, 0xea, 0x69, 0x68, 0x82, 0xd5, + 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x7e, 0x5f, + 0x9f, 0x5f, 0xff, 0x06, 0xeb, 0x39, 0xff, 0x13, 0x4f, 0x5a, 0xed, 0x7f, 0x3f, 0x96, 0x61, 0x3f, 0xe2, 0xf1, 0x7f, 0x4f, 0x7b, + 0xbf, 0x51, 0x24, 0x3e, 0x2a, 0x73, 0x53, 0x70, 0xf8, 0x02, 0x21, 0x00, 0xec, 0x54, 0x7d, 0x78, 0x73, 0xdb, 0x45, 0x80, 0xf1, + 0xe8, 0xd8, 0xe9, 0x2e, 0xca, 0xec, 0x24, 0x5d, 0x88, 0x0a, 0x88, 0x17, 0xfc, 0xd8, 0x1c, 0x67, 0xa8, 0xfa, 0xe4, 0x95, 0x8e, + 0xda, 0x82, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_NoPID_Resigned_Cert = ByteSpan(sTestCert_PAI_FFF2_NoPID_Resigned_Cert_Array); + +constexpr uint8_t sTestCert_PAI_FFF2_NoPID_Resigned_SKID_Array[] = { + 0x61, 0x3D, 0xD0, 0x87, 0x35, 0x5E, 0xF0, 0x8B, 0xAE, 0x01, 0xE4, 0xC6, 0x9A, 0x8F, 0xC7, 0x3D, 0xAC, 0x8C, 0x7D, 0xFD, +}; + +extern const ByteSpan sTestCert_PAI_FFF2_NoPID_Resigned_SKID = ByteSpan(sTestCert_PAI_FFF2_NoPID_Resigned_SKID_Array); + } // namespace TestCerts } // namespace chip diff --git a/src/credentials/tests/CHIPAttCert_test_vectors.h b/src/credentials/tests/CHIPAttCert_test_vectors.h index a38a48e6fe81cd..2419c6bfd578c3 100644 --- a/src/credentials/tests/CHIPAttCert_test_vectors.h +++ b/src/credentials/tests/CHIPAttCert_test_vectors.h @@ -258,6 +258,9 @@ extern const ByteSpan sTestCert_PAA_NoVID_SKID; extern const ByteSpan sTestCert_PAA_NoVID_PublicKey; extern const ByteSpan sTestCert_PAA_NoVID_PrivateKey; +extern const ByteSpan sTestCert_PAA_NoVID_ToResignPAIs_Cert; +extern const ByteSpan sTestCert_PAA_NoVID_ToResignPAIs_SKID; + extern const ByteSpan sTestCert_PAI_FFF1_8000_Cert; extern const ByteSpan sTestCert_PAI_FFF1_8000_SKID; extern const ByteSpan sTestCert_PAI_FFF1_8000_PublicKey; @@ -268,6 +271,17 @@ extern const ByteSpan sTestCert_PAI_FFF2_8001_SKID; extern const ByteSpan sTestCert_PAI_FFF2_8001_PublicKey; extern const ByteSpan sTestCert_PAI_FFF2_8001_PrivateKey; +extern const ByteSpan sTestCert_PAI_FFF2_8001_Resigned_Cert; +extern const ByteSpan sTestCert_PAI_FFF2_8001_Resigned_SKID; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert; +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_SKID; +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PublicKey; +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_PrivateKey; + +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert; +extern const ByteSpan sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_SKID; + extern const ByteSpan sTestCert_PAI_FFF2_8004_FB_Cert; extern const ByteSpan sTestCert_PAI_FFF2_8004_FB_SKID; extern const ByteSpan sTestCert_PAI_FFF2_8004_FB_PublicKey; @@ -308,5 +322,8 @@ extern const ByteSpan sTestCert_PAI_FFF2_NoPID_FB_SKID; extern const ByteSpan sTestCert_PAI_FFF2_NoPID_FB_PublicKey; extern const ByteSpan sTestCert_PAI_FFF2_NoPID_FB_PrivateKey; +extern const ByteSpan sTestCert_PAI_FFF2_NoPID_Resigned_Cert; +extern const ByteSpan sTestCert_PAI_FFF2_NoPID_Resigned_SKID; + } // namespace TestCerts } // namespace chip diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index e87400604d8a84..00733b7d9e7402 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -1492,6 +1492,29 @@ CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan **/ CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid); +/** + * @brief Checks for resigned version of the certificate in the list and returns it. + * + * The following conditions SHOULD be satisfied for the certificate to qualify as + * a resigned version of a reference certificate: + * - SKID of the candidate and the reference certificate should match. + * - SubjectDN of the candidate and the reference certificate should match. + * + * If no resigned version is found then reference certificate itself is returned. + * + * @param referenceCertificate A DER certificate. + * @param candidateCertificates A pointer to the list of DER Certificates, which should be searched + * for the resigned version of `referenceCertificate`. + * @param candidateCertificatesCount Number of certificates in the `candidateCertificates` list. + * @param outCertificate A reference to the certificate or it's resigned version if found. + * Note that it points to either `referenceCertificate` or one of + * `candidateCertificates`, but it doesn't copy data. + * + * @returns error if there is certificate parsing/format issue or CHIP_NO_ERROR otherwise. + **/ +CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates, + size_t candidateCertificatesCount, ByteSpan & outCertificate); + /** * Defines DN attribute types that can include endocing of VID/PID parameters. */ diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index 8a24fde3c54fd4..def307997f5e04 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -2045,5 +2045,65 @@ CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCe return err; } +CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates, + size_t candidateCertificatesCount, ByteSpan & outCertificate) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + X509 * x509ReferenceCertificate = nullptr; + X509 * x509CandidateCertificate = nullptr; + const uint8_t * pReferenceCertificate = referenceCertificate.data(); + X509_NAME * referenceSubject = nullptr; + X509_NAME * candidateSubject = nullptr; + uint8_t referenceSKIDBuf[kSubjectKeyIdentifierLength]; + uint8_t candidateSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan referenceSKID(referenceSKIDBuf); + MutableByteSpan candidateSKID(candidateSKIDBuf); + + ReturnErrorCodeIf(referenceCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + + outCertificate = referenceCertificate; + + ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); + + x509ReferenceCertificate = d2i_X509(nullptr, &pReferenceCertificate, static_cast(referenceCertificate.size())); + VerifyOrExit(x509ReferenceCertificate != nullptr, err = CHIP_ERROR_NO_MEMORY); + + referenceSubject = X509_get_subject_name(x509ReferenceCertificate); + VerifyOrExit(referenceSubject != nullptr, err = CHIP_ERROR_INTERNAL); + + for (size_t i = 0; i < candidateCertificatesCount; i++) + { + const ByteSpan candidateCertificate = candidateCertificates[i]; + const uint8_t * pCandidateCertificate = candidateCertificate.data(); + + VerifyOrExit(!candidateCertificate.empty(), err = CHIP_ERROR_INVALID_ARGUMENT); + + SuccessOrExit(err = ExtractSKIDFromX509Cert(candidateCertificate, candidateSKID)); + + x509CandidateCertificate = d2i_X509(nullptr, &pCandidateCertificate, static_cast(candidateCertificate.size())); + VerifyOrExit(x509CandidateCertificate != nullptr, err = CHIP_ERROR_NO_MEMORY); + + candidateSubject = X509_get_subject_name(x509CandidateCertificate); + VerifyOrExit(candidateSubject != nullptr, err = CHIP_ERROR_INTERNAL); + + if (referenceSKID.data_equal(candidateSKID) && X509_NAME_cmp(referenceSubject, candidateSubject) == 0) + { + outCertificate = candidateCertificate; + ExitNow(); + } + + X509_free(x509CandidateCertificate); + x509CandidateCertificate = nullptr; + } + +exit: + X509_free(x509ReferenceCertificate); + X509_free(x509CandidateCertificate); + + return err; +} + } // namespace Crypto } // namespace chip diff --git a/src/crypto/CHIPCryptoPALTinyCrypt.cpp b/src/crypto/CHIPCryptoPALTinyCrypt.cpp index b89bbcd22a76b3..dd6f875a58287b 100644 --- a/src/crypto/CHIPCryptoPALTinyCrypt.cpp +++ b/src/crypto/CHIPCryptoPALTinyCrypt.cpp @@ -1691,5 +1691,82 @@ CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCe return error; } +namespace { +#if defined(MBEDTLS_X509_CRT_PARSE_C) +CHIP_ERROR ExtractRawSubjectFromX509Cert(const ByteSpan & certificate, MutableByteSpan & subject) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbedCertificate; + + ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + + mbedtls_x509_crt_init(&mbedCertificate); + result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + len = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + p = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + + VerifyOrExit(len <= subject.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(subject.data(), p, len); + subject.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbedCertificate); + + return error; +} +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} // namespace + +CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates, + size_t candidateCertificatesCount, ByteSpan & outCertificate) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + constexpr size_t kMaxCertificateSubjectLength = 150; + uint8_t referenceSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t referenceSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan referenceSubject(referenceSubjectBuf); + MutableByteSpan referenceSKID(referenceSKIDBuf); + + outCertificate = referenceCertificate; + + ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(referenceCertificate, referenceSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); + + for (size_t i = 0; i < candidateCertificatesCount; i++) + { + const ByteSpan candidateCertificate = candidateCertificates[i]; + uint8_t candidateSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t candidateSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan candidateSubject(candidateSubjectBuf); + MutableByteSpan candidateSKID(candidateSKIDBuf); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(candidateCertificate, candidateSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(candidateCertificate, candidateSKID)); + + if (referenceSKID.data_equal(candidateSKID) && referenceSubject.data_equal(candidateSubject)) + { + outCertificate = candidateCertificate; + return CHIP_NO_ERROR; + } + } + + return CHIP_NO_ERROR; +#else + (void) referenceCertificate; + (void) candidateCertificates; + (void) candidateCertificatesCount; + (void) outCertificate; + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} + } // namespace Crypto } // namespace chip diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index 2ce3bc7aba8c30..ff42f9e3df411b 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -1836,5 +1836,82 @@ CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCe return error; } +namespace { +#if defined(MBEDTLS_X509_CRT_PARSE_C) +CHIP_ERROR ExtractRawSubjectFromX509Cert(const ByteSpan & certificate, MutableByteSpan & subject) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbedCertificate; + + ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + + mbedtls_x509_crt_init(&mbedCertificate); + result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + len = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + p = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + + VerifyOrExit(len <= subject.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(subject.data(), p, len); + subject.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbedCertificate); + + return error; +} +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} // namespace + +CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates, + size_t candidateCertificatesCount, ByteSpan & outCertificate) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + constexpr size_t kMaxCertificateSubjectLength = 150; + uint8_t referenceSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t referenceSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan referenceSubject(referenceSubjectBuf); + MutableByteSpan referenceSKID(referenceSKIDBuf); + + outCertificate = referenceCertificate; + + ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(referenceCertificate, referenceSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); + + for (size_t i = 0; i < candidateCertificatesCount; i++) + { + const ByteSpan candidateCertificate = candidateCertificates[i]; + uint8_t candidateSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t candidateSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan candidateSubject(candidateSubjectBuf); + MutableByteSpan candidateSKID(candidateSKIDBuf); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(candidateCertificate, candidateSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(candidateCertificate, candidateSKID)); + + if (referenceSKID.data_equal(candidateSKID) && referenceSubject.data_equal(candidateSubject)) + { + outCertificate = candidateCertificate; + return CHIP_NO_ERROR; + } + } + + return CHIP_NO_ERROR; +#else + (void) referenceCertificate; + (void) candidateCertificates; + (void) candidateCertificatesCount; + (void) outCertificate; + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} + } // namespace Crypto } // namespace chip diff --git a/src/crypto/tests/CHIPCryptoPALTest.cpp b/src/crypto/tests/CHIPCryptoPALTest.cpp index f79a967f652f74..c8b2810ddd0f40 100644 --- a/src/crypto/tests/CHIPCryptoPALTest.cpp +++ b/src/crypto/tests/CHIPCryptoPALTest.cpp @@ -2301,6 +2301,87 @@ static void TestVIDPID_x509Extraction(nlTestSuite * inSuite, void * inContext) } } +static void TestX509_ReplaceCertIfResignedCertFound(nlTestSuite * inSuite, void * inContext) +{ + using namespace TestCerts; + + HeapChecker heapChecker(inSuite); + + struct TestCase + { + ByteSpan referenceCert; + ByteSpan * candidateCertsList; + size_t candidateCertsCount; + ByteSpan expectedOutCert; + }; + + // clang-format off + ByteSpan TestCandidateCertsList1[] = { sTestCert_DAC_FFF1_8000_0004_Cert, + sTestCert_PAI_FFF2_8004_FB_Cert, + sTestCert_PAA_FFF1_Cert }; + ByteSpan TestCandidateCertsList2[] = { sTestCert_DAC_FFF1_8000_0004_Cert, + sTestCert_PAI_FFF2_NoPID_Resigned_Cert }; + ByteSpan TestCandidateCertsList3[] = { sTestCert_DAC_FFF1_8000_0004_Cert, + sTestCert_PAI_FFF2_8001_Resigned_Cert }; + ByteSpan TestCandidateCertsList4[] = { sTestCert_PAI_FFF2_8001_Resigned_Cert, + sTestCert_PAI_FFF1_8000_Cert }; + ByteSpan TestCandidateCertsList5[] = { sTestCert_PAI_FFF2_NoPID_Resigned_Cert, + sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert }; + ByteSpan TestCandidateCertsList6[] = { sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert, + sTestCert_DAC_FFF1_8000_0004_Cert }; + ByteSpan TestCandidateCertsList7[] = { sTestCert_PAA_NoVID_ToResignPAIs_Cert, + sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert, + sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert, + sTestCert_PAI_FFF2_8001_Resigned_Cert, + sTestCert_PAI_FFF2_NoPID_Resigned_Cert }; + ByteSpan TestCandidateCertsList8[] = { sTestCert_PAA_NoVID_ToResignPAIs_Cert, + sTestCert_PAI_FFF2_8001_Resigned_Cert, + ByteSpan(), + sTestCert_PAI_FFF2_8001_ResignedSKIDDiff_Cert, + sTestCert_PAI_FFF2_8001_ResignedSubjectDiff_Cert, + sTestCert_PAI_FFF2_NoPID_Resigned_Cert }; + + const TestCase kTestCases[] = { + { sTestCert_PAI_FFF2_8001_Cert, nullptr, 5, sTestCert_PAI_FFF2_8001_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList3, 0, sTestCert_PAI_FFF2_8001_Cert }, + { sTestCert_PAI_FFF1_8000_Cert, TestCandidateCertsList1, ArraySize(TestCandidateCertsList1), sTestCert_PAI_FFF1_8000_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList2, ArraySize(TestCandidateCertsList2), sTestCert_PAI_FFF2_8001_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList3, ArraySize(TestCandidateCertsList3), sTestCert_PAI_FFF2_8001_Resigned_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList4, ArraySize(TestCandidateCertsList4), sTestCert_PAI_FFF2_8001_Resigned_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList5, ArraySize(TestCandidateCertsList5), sTestCert_PAI_FFF2_8001_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList6, ArraySize(TestCandidateCertsList6), sTestCert_PAI_FFF2_8001_Cert }, + { sTestCert_PAI_FFF2_8001_Cert, TestCandidateCertsList7, ArraySize(TestCandidateCertsList7), sTestCert_PAI_FFF2_8001_Resigned_Cert }, + { sTestCert_PAI_FFF2_NoPID_Cert, TestCandidateCertsList7, ArraySize(TestCandidateCertsList7), sTestCert_PAI_FFF2_NoPID_Resigned_Cert }, + }; + // clang-format on + + for (const auto & testCase : kTestCases) + { + ByteSpan outCert; + CHIP_ERROR result = ReplaceCertIfResignedCertFound(testCase.referenceCert, testCase.candidateCertsList, + testCase.candidateCertsCount, outCert); + + NL_TEST_ASSERT(inSuite, result == CHIP_NO_ERROR); + NL_TEST_ASSERT(inSuite, outCert.data_equal(testCase.expectedOutCert)); + } + + // Error case: invalid input argument for referenceCertificate + { + ByteSpan outCert; + CHIP_ERROR result = + ReplaceCertIfResignedCertFound(ByteSpan(), TestCandidateCertsList7, ArraySize(TestCandidateCertsList7), outCert); + NL_TEST_ASSERT(inSuite, result == CHIP_ERROR_INVALID_ARGUMENT); + } + + // Error case: invalid input argument for one of the certificates in the candidateCertificates list + { + ByteSpan outCert; + CHIP_ERROR result = + ReplaceCertIfResignedCertFound(ByteSpan(), TestCandidateCertsList8, ArraySize(TestCandidateCertsList8), outCert); + NL_TEST_ASSERT(inSuite, result == CHIP_ERROR_INVALID_ARGUMENT); + } +} + static const uint8_t kCompressedFabricId[] = { 0x29, 0x06, 0xC9, 0x08, 0xD1, 0x15, 0xD3, 0x62 }; const uint8_t kEpochKeyBuffer1[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, @@ -2462,6 +2543,7 @@ static const nlTest sTests[] = { NL_TEST_DEF("Test Authority Key Id Extraction from x509 Certificate", TestAKID_x509Extraction), NL_TEST_DEF("Test Vendor ID and Product ID Extraction from Attribute String", TestVIDPID_StringExtraction), NL_TEST_DEF("Test Vendor ID and Product ID Extraction from x509 Attestation Certificate", TestVIDPID_x509Extraction), + NL_TEST_DEF("Test Replace Resigned Certificate Version if Found", TestX509_ReplaceCertIfResignedCertFound), NL_TEST_DEF("Test Group Operation Key Derivation", TestGroup_OperationalKeyDerivation), NL_TEST_DEF("Test Group Session ID Derivation", TestGroup_SessionIdDerivation), NL_TEST_DEF("Test Group Privacy Key Derivation", TestGroup_PrivacyKeyDerivation), diff --git a/src/platform/silabs/EFR32/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/EFR32/CHIPCryptoPALPsaEfr32.cpp index bcf252a86754de..184da071eeddce 100644 --- a/src/platform/silabs/EFR32/CHIPCryptoPALPsaEfr32.cpp +++ b/src/platform/silabs/EFR32/CHIPCryptoPALPsaEfr32.cpp @@ -1875,5 +1875,82 @@ CHIP_ERROR ExtractVIDPIDFromX509Cert(const ByteSpan & certificate, AttestationCe return error; } +namespace { +#if defined(MBEDTLS_X509_CRT_PARSE_C) +CHIP_ERROR ExtractRawSubjectFromX509Cert(const ByteSpan & certificate, MutableByteSpan & subject) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + int result = 0; + uint8_t * p = nullptr; + size_t len = 0; + mbedtls_x509_crt mbedCertificate; + + ReturnErrorCodeIf(certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); + + mbedtls_x509_crt_init(&mbedCertificate); + result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); + VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); + + len = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(len); + p = mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE_X509(subject_raw).CHIP_CRYPTO_PAL_PRIVATE_X509(p); + + VerifyOrExit(len <= subject.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(subject.data(), p, len); + subject.reduce_size(len); + +exit: + _log_mbedTLS_error(result); + mbedtls_x509_crt_free(&mbedCertificate); + + return error; +} +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} // namespace + +CHIP_ERROR ReplaceCertIfResignedCertFound(const ByteSpan & referenceCertificate, const ByteSpan * candidateCertificates, + size_t candidateCertificatesCount, ByteSpan & outCertificate) +{ +#if defined(MBEDTLS_X509_CRT_PARSE_C) + constexpr size_t kMaxCertificateSubjectLength = 150; + uint8_t referenceSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t referenceSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan referenceSubject(referenceSubjectBuf); + MutableByteSpan referenceSKID(referenceSKIDBuf); + + outCertificate = referenceCertificate; + + ReturnErrorCodeIf(candidateCertificates == nullptr || candidateCertificatesCount == 0, CHIP_NO_ERROR); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(referenceCertificate, referenceSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(referenceCertificate, referenceSKID)); + + for (size_t i = 0; i < candidateCertificatesCount; i++) + { + const ByteSpan candidateCertificate = candidateCertificates[i]; + uint8_t candidateSubjectBuf[kMaxCertificateSubjectLength]; + uint8_t candidateSKIDBuf[kSubjectKeyIdentifierLength]; + MutableByteSpan candidateSubject(candidateSubjectBuf); + MutableByteSpan candidateSKID(candidateSKIDBuf); + + ReturnErrorOnFailure(ExtractRawSubjectFromX509Cert(candidateCertificate, candidateSubject)); + ReturnErrorOnFailure(ExtractSKIDFromX509Cert(candidateCertificate, candidateSKID)); + + if (referenceSKID.data_equal(candidateSKID) && referenceSubject.data_equal(candidateSubject)) + { + outCertificate = candidateCertificate; + return CHIP_NO_ERROR; + } + } + + return CHIP_NO_ERROR; +#else + (void) referenceCertificate; + (void) candidateCertificates; + (void) candidateCertificatesCount; + (void) outCertificate; + return CHIP_ERROR_NOT_IMPLEMENTED; +#endif // defined(MBEDTLS_X509_CRT_PARSE_C) +} + } // namespace Crypto } // namespace chip From 3012b1826f5dd8a689f63e39fbbb5de3d2d69a72 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 5 Jan 2023 19:27:15 +0100 Subject: [PATCH 28/31] [third_party] Add libwebsockets to third_party with a lws_config.h file that makes it server only (#24280) --- .gitmodules | 4 + third_party/libwebsockets/BUILD.gn | 109 ++++++++++++++++++ third_party/libwebsockets/lws_config.h | 65 +++++++++++ .../libwebsockets/lws_config_private.h | 19 +++ third_party/libwebsockets/repo | 1 + 5 files changed, 198 insertions(+) create mode 100644 third_party/libwebsockets/BUILD.gn create mode 100644 third_party/libwebsockets/lws_config.h create mode 100644 third_party/libwebsockets/lws_config_private.h create mode 160000 third_party/libwebsockets/repo diff --git a/.gitmodules b/.gitmodules index f211ca385789ff..9e5b4f09f0fb39 100644 --- a/.gitmodules +++ b/.gitmodules @@ -290,3 +290,7 @@ url = https://github.com/bouffalolab/bl_iot_sdk_tiny.git branch = main platforms = bouffalolab +[submodule "third_party/libwebsockets/repo"] + path = third_party/libwebsockets/repo + url = https://github.com/warmcat/libwebsockets + platforms = linux,darwin diff --git a/third_party/libwebsockets/BUILD.gn b/third_party/libwebsockets/BUILD.gn new file mode 100644 index 00000000000000..8e759cc4dc601f --- /dev/null +++ b/third_party/libwebsockets/BUILD.gn @@ -0,0 +1,109 @@ +# Copyright (c) 2023 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. + +config("libwebsockets_config") { + include_dirs = [ + ".", + "repo/include", + ] + + cflags = [ + "-Wno-shadow", + "-Wno-unreachable-code", + "-Wno-format-nonliteral", + ] + + defines = [] +} + +source_set("libwebsockets") { + include_dirs = [ + "repo/lib/plat/windows", + "repo/lib/plat/freertos", + "repo/lib/plat/unix", + "repo/lib/secure-streams", + "repo/lib/event-libs", + "repo/lib/roles", + "repo/lib/roles/http", + "repo/lib/roles/h1", + "repo/lib/roles/h2", + "repo/lib/roles/ws", + "repo/lib/system/metrics", + "repo/lib/system/smd", + "repo/lib/system/async-dns", + "repo/lib/core", + "repo/lib/core-net", + ] + + sources = [ + "repo/lib/core-net/adopt.c", + "repo/lib/core-net/close.c", + "repo/lib/core-net/dummy-callback.c", + "repo/lib/core-net/network.c", + "repo/lib/core-net/output.c", + "repo/lib/core-net/pollfd.c", + "repo/lib/core-net/service.c", + "repo/lib/core-net/sorted-usec-list.c", + "repo/lib/core-net/vhost.c", + "repo/lib/core-net/wsi-timeout.c", + "repo/lib/core-net/wsi.c", + "repo/lib/core/alloc.c", + "repo/lib/core/buflist.c", + "repo/lib/core/context.c", + "repo/lib/core/libwebsockets.c", + "repo/lib/core/logs.c", + "repo/lib/core/lws_dll2.c", + "repo/lib/event-libs/poll/poll.c", + "repo/lib/misc/base64-decode.c", + "repo/lib/misc/sha-1.c", + "repo/lib/roles/h1/ops-h1.c", + "repo/lib/roles/http/date.c", + "repo/lib/roles/http/header.c", + "repo/lib/roles/http/parsers.c", + "repo/lib/roles/http/server/server.c", + "repo/lib/roles/listen/ops-listen.c", + "repo/lib/roles/pipe/ops-pipe.c", + "repo/lib/roles/raw-skt/ops-raw-skt.c", + "repo/lib/roles/ws/ops-ws.c", + "repo/lib/roles/ws/server-ws.c", + "repo/lib/system/system.c", + ] + + if (current_os == "freertos") { + sources += [ + "repo/lib/plat/freertos/freertos-fds.c", + "repo/lib/plat/freertos/freertos-init.c", + "repo/lib/plat/freertos/freertos-misc.c", + "repo/lib/plat/freertos/freertos-pipe.c", + "repo/lib/plat/freertos/freertos-service.c", + "repo/lib/plat/freertos/freertos-sockets.c", + ] + + cflags = [ "-DLWS_PLAT_FREERTOS" ] + } else { + sources += [ + "repo/lib/plat/unix/unix-caps.c", + "repo/lib/plat/unix/unix-fds.c", + "repo/lib/plat/unix/unix-init.c", + "repo/lib/plat/unix/unix-misc.c", + "repo/lib/plat/unix/unix-pipe.c", + "repo/lib/plat/unix/unix-service.c", + "repo/lib/plat/unix/unix-sockets.c", + ] + + cflags = [ "-DLWS_PLAT_UNIX" ] + } + + public_configs = [ ":libwebsockets_config" ] +} diff --git a/third_party/libwebsockets/lws_config.h b/third_party/libwebsockets/lws_config.h new file mode 100644 index 00000000000000..96ddcf8a6db7d9 --- /dev/null +++ b/third_party/libwebsockets/lws_config.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023 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 + +#define LWS_LIBRARY_VERSION "4.3.99" + +// +// Major individual features +// +#define LWS_WITH_NETWORK // "Compile with network-related code" - default: ON +#define LWS_ROLE_H1 // "Compile with support for http/1 (needed for ws)" - default: ON +#define LWS_ROLE_WS // "Compile with support for websockets" - default: ON +#define LWS_WITH_IPV6 // "Compile with support for ipv6" - default: OFF +#define LWS_UNIX_SOCK // "Compile with support for UNIX domain socket if OS supports it" - default: ON + +// +// Client / Server / Test Apps build control +// +#define LWS_WITHOUT_CLIENT // "Don't build the client part of the library" default - OFF + +// +// Extensions (permessage-deflate) +// +#define LWS_WITHOUT_EXTENSIONS // "Don't compile with extensions" - default: ON + +// +// Helpers + misc +// +#define LWS_WITHOUT_DAEMONIZE // "Don't build the daemonization api" - default: ON +#define LWS_LOGS_TIMESTAMP // "Timestamp at start of logs" - default: ON +#define LWS_LOG_TAG_LIFECYCLE // "Log tagged object lifecycle as NOTICE" - default: ON + +// +// Implied Options +// +#define LWS_WITH_POLL +#define LWS_MAX_SMP 1 + +#ifdef LWS_WITHOUT_DAEMONIZE +#define LWS_NO_DAEMONIZE +#endif + +#ifdef LWS_WITH_HTTP2 +#define LWS_ROLE_H2 +#endif + +#ifndef LWS_WITHOUT_SERVER +#define LWS_WITH_SERVER +#endif diff --git a/third_party/libwebsockets/lws_config_private.h b/third_party/libwebsockets/lws_config_private.h new file mode 100644 index 00000000000000..468bba9a126d4f --- /dev/null +++ b/third_party/libwebsockets/lws_config_private.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2023 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 diff --git a/third_party/libwebsockets/repo b/third_party/libwebsockets/repo new file mode 160000 index 00000000000000..ec6d5ac6d58d92 --- /dev/null +++ b/third_party/libwebsockets/repo @@ -0,0 +1 @@ +Subproject commit ec6d5ac6d58d92ac8c1a3d769d076cabd6aa4ac1 From e59000e042cf49c6b7fca4d34adc919a3d6b2fbd Mon Sep 17 00:00:00 2001 From: pankore <86098180+pankore@users.noreply.github.com> Date: Fri, 6 Jan 2023 04:21:44 +0800 Subject: [PATCH 29/31] use docker image 0.6.27 (#24273) * use docker image 0.6.27 * [mbedtls] Update filepath Fix CI error for new docker image. * Move cloudbuild and chef back to 0.6.18 for compilation until NRF is compatible with latest SDK * Do not update the telink docker image yet Co-authored-by: Andrei Litvin --- .devcontainer/devcontainer.json | 2 +- .github/workflows/bloat_check.yaml | 2 +- .github/workflows/build.yaml | 6 +++--- .github/workflows/chef.yaml | 5 +++-- .github/workflows/cirque.yaml | 4 ++-- .github/workflows/doxygen.yaml | 2 +- .github/workflows/examples-ameba.yaml | 2 +- .github/workflows/examples-bouffalolab.yaml | 2 +- .github/workflows/examples-cc13x2x7_26x2x7.yaml | 2 +- .github/workflows/examples-efr32.yaml | 2 +- .github/workflows/examples-esp32.yaml | 4 ++-- .github/workflows/examples-infineon.yaml | 2 +- .github/workflows/examples-k32w.yaml | 2 +- .github/workflows/examples-linux-arm.yaml | 2 +- .github/workflows/examples-linux-imx.yaml | 2 +- .github/workflows/examples-linux-standalone.yaml | 2 +- .github/workflows/examples-mbed.yaml | 2 +- .github/workflows/examples-mw320.yaml | 2 +- .github/workflows/examples-nrfconnect.yaml | 2 +- .github/workflows/examples-openiotsdk.yaml | 2 +- .github/workflows/examples-qpg.yaml | 2 +- .github/workflows/examples-telink.yaml | 1 + .github/workflows/examples-tizen.yaml | 2 +- .github/workflows/full-android.yaml | 2 +- .github/workflows/fuzzing-build.yaml | 2 +- .github/workflows/qemu.yaml | 2 +- .github/workflows/release_artifacts.yaml | 4 ++-- .github/workflows/smoketest-android.yaml | 2 +- .github/workflows/tests.yaml | 6 +++--- .github/workflows/unit_integration_test.yaml | 2 +- .github/workflows/zap_regeneration.yaml | 2 +- .github/workflows/zap_templates.yaml | 2 +- integrations/cloudbuild/build-all.yaml | 5 +++-- integrations/cloudbuild/build-coverage.yaml | 4 ++-- integrations/cloudbuild/chef.yaml | 6 +++--- integrations/cloudbuild/smoke-test.yaml | 13 +++++++------ third_party/ameba/mbedtls.cmake | 2 +- 37 files changed, 57 insertions(+), 53 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 95625da71a1e40..5ddef22276ed10 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -17,7 +17,7 @@ "build": { "dockerfile": "Dockerfile", "args": { - "BUILD_VERSION": "0.6.18" + "BUILD_VERSION": "0.6.27" } }, "remoteUser": "vscode", diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index b5325da5ec1ff3..ba734f22758ca9 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 443210b15c3c05..00ab192750e13f 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -138,7 +138,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 @@ -308,7 +308,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" options: --sysctl "net.ipv6.conf.all.disable_ipv6=0 diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index 3a7a91d60663e9..eca0463b31931a 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -29,7 +29,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 options: --user root steps: @@ -57,7 +57,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.18 + image: connectedhomeip/chip-build-esp32:0.6.27 options: --user root steps: @@ -85,6 +85,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: + # TODO: update this to connectedhomeip/chip-build-vscode:0.6.27 once we can compile with latest NRF image: connectedhomeip/chip-build-nrf-platform:0.6.18 options: --user root diff --git a/.github/workflows/cirque.yaml b/.github/workflows/cirque.yaml index c55e84b7a9273d..58fc8091a224df 100644 --- a/.github/workflows/cirque.yaml +++ b/.github/workflows/cirque.yaml @@ -29,7 +29,7 @@ jobs: timeout-minutes: 90 env: - DOCKER_RUN_VERSION: 0.6.18 + DOCKER_RUN_VERSION: 0.6.27 GITHUB_CACHE_PATH: /tmp/cirque-cache/ runs-on: ubuntu-latest @@ -38,7 +38,7 @@ jobs: # need to run with privilege, which isn't supported by job.XXX.contaner # https://github.com/actions/container-action/issues/2 # container: - # image: connectedhomeip/chip-build-cirque:0.6.18 + # image: connectedhomeip/chip-build-cirque:0.6.27 # volumes: # - "/tmp:/tmp" # - "/dev/pts:/dev/pts" diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index d5f84576ff0fc7..669efca5f6d4c7 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -82,7 +82,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build-doxygen:0.6.18 + image: connectedhomeip/chip-build-doxygen:0.6.27 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 6986e6b6bda00b..3b568a270aa0ae 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ameba:0.6.18 + image: connectedhomeip/chip-build-ameba:0.6.27 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index a62e0dad3c74dd..04331435bc6e14 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-bouffalolab:0.6.18 + image: connectedhomeip/chip-build-bouffalolab:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc13x2x7_26x2x7.yaml b/.github/workflows/examples-cc13x2x7_26x2x7.yaml index aa11433edd9fa6..99baf383bbaf3f 100644 --- a/.github/workflows/examples-cc13x2x7_26x2x7.yaml +++ b/.github/workflows/examples-cc13x2x7_26x2x7.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-ti:0.6.18 + image: connectedhomeip/chip-build-ti:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index 30374f090bfe96..90e0e397c82517 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-efr32:0.6.18 + image: connectedhomeip/chip-build-efr32:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index 61d9d032042c9d..13a025fe229767 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.18 + image: connectedhomeip/chip-build-esp32:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -140,7 +140,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32:0.6.18 + image: connectedhomeip/chip-build-esp32:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index 51d89d81c0b316..bb629fa999fcf2 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-infineon:0.6.18 + image: connectedhomeip/chip-build-infineon:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-k32w.yaml b/.github/workflows/examples-k32w.yaml index 76f8d8237f2d56..53b1aa46701771 100644 --- a/.github/workflows/examples-k32w.yaml +++ b/.github/workflows/examples-k32w.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-k32w:0.6.18 + image: connectedhomeip/chip-build-k32w:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 1a5b9c07395482..159960bef927a4 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-crosscompile:0.6.18 + image: connectedhomeip/chip-build-crosscompile:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index b8bfdc0c086c14..42f426bfa959b0 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-imx:0.6.18 + image: connectedhomeip/chip-build-imx:0.6.27 steps: - uses: Wandalen/wretry.action@v1.0.36 diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 2c09f5871e7f7f..11c913cfee488c 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mbed.yaml b/.github/workflows/examples-mbed.yaml index 3a9d522b1aa676..91f9f6f82a2097 100644 --- a/.github/workflows/examples-mbed.yaml +++ b/.github/workflows/examples-mbed.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-mbed-os:0.6.18 + image: connectedhomeip/chip-build-mbed-os:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index aedded0398df28..7fc6238cc81034 100755 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index 7d0c274dc2d029..1fa32d751037e8 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-nrf-platform:0.6.18 + image: connectedhomeip/chip-build-nrf-platform:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index f3b49f828704ff..7e043d58d98ee5 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -35,7 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-openiotsdk:0.6.18 + image: connectedhomeip/chip-build-openiotsdk:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" options: --privileged diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index c32dd590ddc930..35bc2987a4d10a 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index 2099621e165ed3..9e5737c84828f9 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -35,6 +35,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: + # TODO: update this to connectedhomeip/chip-build-vscode:0.6.27 once we can compile image: connectedhomeip/chip-build-telink:0.6.18 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index 259733a008237c..8f892c8c712f13 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -33,7 +33,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-tizen:0.6.18 + image: connectedhomeip/chip-build-tizen:0.6.27 options: --user root volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index 1173adaf7c82d5..8f87a48a9e6043 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.18 + image: connectedhomeip/chip-build-android:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index bd96ff35792e31..bfb1eac538a138 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -34,7 +34,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 1a0c88e28d47b3..965e69ae1f3576 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-esp32-qemu:0.6.18 + image: connectedhomeip/chip-build-esp32-qemu:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index 6b57156ba01f2d..5a6c13f85f8f14 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-esp32:0.6.18 + image: connectedhomeip/chip-build-esp32:0.6.27 steps: - uses: Wandalen/wretry.action@v1.0.36 @@ -75,7 +75,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build-efr32:0.6.18 + image: connectedhomeip/chip-build-efr32:0.6.27 steps: - uses: Wandalen/wretry.action@v1.0.36 name: Checkout diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index 04c4c8ecb77d2b..dc8ee425c28fca 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: connectedhomeip/chip-build-android:0.6.18 + image: connectedhomeip/chip-build-android:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 8f96c75a1e280b..e492cba4c6b360 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -47,7 +47,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -352,7 +352,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" @@ -426,7 +426,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index a0ea6842e24dc0..a6cb192b058a99 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -37,7 +37,7 @@ jobs: runs-on: ubuntu-latest container: - image: connectedhomeip/chip-build:0.6.18 + image: connectedhomeip/chip-build:0.6.27 volumes: - "/tmp/log_output:/tmp/test_logs" options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 19960d000c4fcb..1906613500816d 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -28,7 +28,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.25 + image: connectedhomeip/chip-build:0.6.27 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index e35ad0d7495d16..b7459e76d53996 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.25 + image: connectedhomeip/chip-build:0.6.27 defaults: run: shell: sh diff --git a/integrations/cloudbuild/build-all.yaml b/integrations/cloudbuild/build-all.yaml index 5a80129f54496b..863a7105c23290 100644 --- a/integrations/cloudbuild/build-all.yaml +++ b/integrations/cloudbuild/build-all.yaml @@ -6,7 +6,7 @@ steps: - "--init" - "--recursive" id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -21,7 +21,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -76,6 +76,7 @@ steps: --target k32w-shell build --create-archives /workspace/artifacts/ + # TODO: update this to connectedhomeip/chip-build-vscode:0.6.27 once we can compile with latest NRF - name: "connectedhomeip/chip-build-vscode:0.6.18" env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/integrations/cloudbuild/build-coverage.yaml b/integrations/cloudbuild/build-coverage.yaml index 3973c85147a623..8beb8b6d18f19c 100644 --- a/integrations/cloudbuild/build-coverage.yaml +++ b/integrations/cloudbuild/build-coverage.yaml @@ -7,7 +7,7 @@ steps: - "--recursive" id: Submodules - - name: "connectedhomeip/chip-build:0.6.18" + - name: "connectedhomeip/chip-build:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -22,7 +22,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build:0.6.17" + - name: "connectedhomeip/chip-build:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/chef.yaml b/integrations/cloudbuild/chef.yaml index 0cfebde9cf97ea..494869a38e318e 100644 --- a/integrations/cloudbuild/chef.yaml +++ b/integrations/cloudbuild/chef.yaml @@ -1,5 +1,5 @@ steps: - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -12,7 +12,7 @@ steps: path: /pwenv timeout: 2700s - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -26,7 +26,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 47145edfc2aabc..c2f34ea5f72cdc 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -1,5 +1,5 @@ steps: - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" git submodule update --init --recursive id: Submodules - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -22,7 +22,7 @@ steps: path: /pwenv timeout: 900s - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" id: ESP32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -41,6 +41,7 @@ steps: - name: pwenv path: /pwenv + # TODO: update this to connectedhomeip/chip-build-vscode:0.6.27 once we can compile with latest NRF - name: "connectedhomeip/chip-build-vscode:0.6.18" id: NRFConnect env: @@ -62,7 +63,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" id: EFR32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -84,7 +85,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" id: Linux env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -142,7 +143,7 @@ steps: - name: pwenv path: /pwenv - - name: "connectedhomeip/chip-build-vscode:0.6.18" + - name: "connectedhomeip/chip-build-vscode:0.6.27" id: Android env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/third_party/ameba/mbedtls.cmake b/third_party/ameba/mbedtls.cmake index 454358141d5df9..107e29a591df08 100755 --- a/third_party/ameba/mbedtls.cmake +++ b/third_party/ameba/mbedtls.cmake @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.6) project(mbedtls) -set(dir "${sdk_root}/component/common/network/ssl/mbedtls-matter") +set(dir "${sdk_root}/component/common/application/matter/mbedtls") set(dir_mbedtlschip "${ameba_matter_root}/third_party/mbedtls/repo/library") list( From fbaa1fe47894ab79435053d48c10eb7e774eef41 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 5 Jan 2023 15:31:16 -0500 Subject: [PATCH 30/31] Update ZAP to tip. (#24286) Moves list of weakly typed enums out of the ZAP helper code. --- integrations/docker/images/chip-build/Dockerfile | 2 +- integrations/docker/images/chip-build/version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/docker/images/chip-build/Dockerfile b/integrations/docker/images/chip-build/Dockerfile index 57eb0030689518..9d8b2ebdd9d8da 100644 --- a/integrations/docker/images/chip-build/Dockerfile +++ b/integrations/docker/images/chip-build/Dockerfile @@ -178,7 +178,7 @@ RUN set -x \ # Install a known ZAP release # Only keep the cli version, since `zap` is 143MB and not usable (UI) -ENV ZAP_VERSION=v2022.12.20-nightly +ENV ZAP_VERSION=v2023.01.05-nightly RUN set -x \ && mkdir -p /opt/zap-${ZAP_VERSION} \ && cd /opt/zap-${ZAP_VERSION} \ diff --git a/integrations/docker/images/chip-build/version b/integrations/docker/images/chip-build/version index bcccaaff02e138..2c5730e10a8e14 100644 --- a/integrations/docker/images/chip-build/version +++ b/integrations/docker/images/chip-build/version @@ -1 +1 @@ -0.6.27 Version bump reason: [Telink] Update Telink Docker image (Zephyr update) +0.6.28 Version bump reason: Updating ZAP to v2023.01.05-nightly From 7f668cd586d1b4b239a7498909682d3fd8416f73 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 5 Jan 2023 19:03:01 -0500 Subject: [PATCH 31/31] Preserve acronyms in Darwin names of enum/bitmap values. (#24293) --- .github/workflows/zap_regeneration.yaml | 2 +- .github/workflows/zap_templates.yaml | 2 +- .../Framework/CHIP/templates/MTRBaseClusters.zapt | 12 ++++++------ .../Framework/CHIP/templates/availability.yaml | 9 +++++++++ .../CHIP/zap-generated/MTRBaseClusters.h | 15 ++++++++++++--- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 1906613500816d..72cdc5fbc47808 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -28,7 +28,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.27 + image: connectedhomeip/chip-build:0.6.28 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index b7459e76d53996..4a53d2b180a1df 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -29,7 +29,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: connectedhomeip/chip-build:0.6.27 + image: connectedhomeip/chip-build:0.6.28 defaults: run: shell: sh diff --git a/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt b/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt index 99a43ecc41aadc..f7c229a0fbb14e 100644 --- a/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt +++ b/src/darwin/Framework/CHIP/templates/MTRBaseClusters.zapt @@ -84,13 +84,13 @@ subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptio {{#*inline "enumDef"}} typedef NS_ENUM({{asUnderlyingZclType name}}, {{objCEnumName clusterName enumName}}) { {{#zcl_enum_items}} - {{objCEnumName ../clusterName ../enumName}}{{objCEnumItemLabel label}} {{availability ../clusterName enum=../enumName enumValue=(objCEnumItemLabel label) deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex value 2}}, + {{objCEnumName ../clusterName ../enumName}}{{asUpperCamelCase label preserveAcronyms=true}} {{availability ../clusterName enum=../enumName enumValue=(asUpperCamelCase label preserveAcronyms=true) deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (asUpperCamelCase label preserveAcronyms=true))}} = {{asHex value 2}}, {{#*inline "oldNameItemDecl"}} {{#if oldItemName}} - {{objCEnumName ../clusterName ../enumName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName enum=../enumName enumValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex value 2}}, + {{objCEnumName ../clusterName ../enumName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName enum=../enumName enumValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (asUpperCamelCase label preserveAcronyms=true))}} = {{asHex value 2}}, {{/if}} {{/inline}} - {{> oldNameItemDecl oldItemName=(oldName ../clusterName enum=../enumName enumValue=(objCEnumItemLabel label))}} + {{> oldNameItemDecl oldItemName=(oldName ../clusterName enum=../enumName enumValue=(asUpperCamelCase label preserveAcronyms=true))}} {{/zcl_enum_items}} } {{/inline}} @@ -118,13 +118,13 @@ typedef NS_ENUM({{asUnderlyingZclType name}}, {{objCEnumName clusterName enumNam {{#*inline "bitmapDef"}} typedef NS_OPTIONS({{asUnderlyingZclType name}}, {{objCEnumName clusterName bitmapName}}) { {{#zcl_bitmap_items}} - {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel label}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=(objCEnumItemLabel label) deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex mask}}, + {{objCEnumName ../clusterName ../bitmapName}}{{asUpperCamelCase label preserveAcronyms=true}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=(asUpperCamelCase label preserveAcronyms=true) deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (asUpperCamelCase label preserveAcronyms=true))}} = {{asHex mask}}, {{#*inline "oldNameItemDecl"}} {{#if oldItemName}} - {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (objCEnumItemLabel label))}} = {{asHex mask}}, + {{objCEnumName ../clusterName ../bitmapName}}{{objCEnumItemLabel oldItemName}} {{availability ../clusterName bitmap=../bitmapName bitmapValue=oldItemName deprecationMessage=(concat "Please use " (objCEnumName (asUpperCamelCase ../../name preserveAcronyms=true) ../label) (asUpperCamelCase label preserveAcronyms=true))}} = {{asHex mask}}, {{/if}} {{/inline}} - {{> oldNameItemDecl oldItemName=(oldName ../clusterName bitmap=../bitmapName bitmapValue=(objCEnumItemLabel label))}} + {{> oldNameItemDecl oldItemName=(oldName ../clusterName bitmap=../bitmapName bitmapValue=(asUpperCamelCase label preserveAcronyms=true))}} {{/zcl_bitmap_items}} } {{/inline}} diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index fb9685f8ad5539..79510e723f9877 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -5208,6 +5208,9 @@ NetworkCommissioning: WiFiSecurity: - WEP + - WPAPersonal + - WPA2Personal + - WPA3Personal deprecated: clusters: - OtaSoftwareUpdateProvider @@ -5276,6 +5279,9 @@ NetworkCommissioning: WiFiSecurity: - WepPersonal + - WpaPersonal + - Wpa2Personal + - Wpa3Personal apis: - Timed Invoke for server to client commands - Deprecated global attribute names @@ -5358,3 +5364,6 @@ NetworkCommissioning: WiFiSecurity: WEP: WepPersonal + WPAPersonal: WpaPersonal + WPA2Personal: Wpa2Personal + WPA3Personal: Wpa3Personal diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index 0387e8cc9334ac..0934f592496b57 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -17526,9 +17526,18 @@ typedef NS_OPTIONS(uint8_t, MTRNetworkCommissioningWiFiSecurity) { MTRNetworkCommissioningWiFiSecurityWepPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) MTR_NEWLY_DEPRECATED("Please use MTRNetworkCommissioningWiFiSecurityWEP") = 0x2, - MTRNetworkCommissioningWiFiSecurityWpaPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x4, - MTRNetworkCommissioningWiFiSecurityWpa2Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x8, - MTRNetworkCommissioningWiFiSecurityWpa3Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x10, + MTRNetworkCommissioningWiFiSecurityWPAPersonal MTR_NEWLY_AVAILABLE = 0x4, + MTRNetworkCommissioningWiFiSecurityWpaPersonal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRNetworkCommissioningWiFiSecurityWPAPersonal") + = 0x4, + MTRNetworkCommissioningWiFiSecurityWPA2Personal MTR_NEWLY_AVAILABLE = 0x8, + MTRNetworkCommissioningWiFiSecurityWpa2Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRNetworkCommissioningWiFiSecurityWPA2Personal") + = 0x8, + MTRNetworkCommissioningWiFiSecurityWPA3Personal MTR_NEWLY_AVAILABLE = 0x10, + MTRNetworkCommissioningWiFiSecurityWpa3Personal API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) + MTR_NEWLY_DEPRECATED("Please use MTRNetworkCommissioningWiFiSecurityWPA3Personal") + = 0x10, } API_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRDiagnosticLogsLogsIntent) {