diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index afce8a64d88abb..5dd2cb413ed854 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -58,7 +58,7 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl602dk-light-mfd-littlefs-rpc-115200 \ + --target bouffalolab-bl602dk-light-wifi-littlefs-mfd-rpc \ build \ --copy-artifacts-to out/artifacts \ " @@ -66,7 +66,7 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl602 bl602+mfd+littlefs+rpc lighting-app \ - out/artifacts/bouffalolab-bl602dk-light-mfd-littlefs-rpc-115200/chip-bl602-lighting-example.out \ + out/artifacts/bouffalolab-bl602dk-light-wifi-littlefs-mfd-rpc/chip-bl602-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out @@ -77,7 +77,7 @@ jobs: "./scripts/build/build_examples.py \ --target bouffalolab-bl706dk-light-ethernet-easyflash \ --target bouffalolab-bl706dk-light-wifi-littlefs \ - --target bouffalolab-bl706dk-light-mfd-rpc-littlefs-115200 \ + --target bouffalolab-bl706dk-light-thread-littlefs-mfd-rpc \ build \ --copy-artifacts-to out/artifacts \ " @@ -93,7 +93,7 @@ jobs: /tmp/bloat_reports/ .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl702 bl706+mfd+rpc+littlefs lighting-app \ - out/artifacts/bouffalolab-bl706dk-light-mfd-rpc-littlefs-115200/chip-bl702-lighting-example.out \ + out/artifacts/bouffalolab-bl706dk-light-thread-littlefs-mfd-rpc/chip-bl702-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out @@ -103,7 +103,7 @@ jobs: run: | ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target bouffalolab-bl704ldk-light-mfd-littlefs \ + --target bouffalolab-bl704ldk-light-thread-littlefs-mfd \ build \ --copy-artifacts-to out/artifacts \ " @@ -111,7 +111,7 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ bl702l bl702l+mfd+littlefs lighting-app \ - out/artifacts/bouffalolab-bl704ldk-light-mfd-littlefs/chip-bl702l-lighting-example.out \ + out/artifacts/bouffalolab-bl704ldk-light-thread-littlefs-mfd/chip-bl702l-lighting-example.out \ /tmp/bloat_reports/ - name: Clean out build output run: rm -rf ./out diff --git a/config/bouffalolab/toolchain/riscv_toolchain.gni b/config/bouffalolab/toolchain/riscv_toolchain.gni index db46fc1a98f4fa..9035a6c0b48831 100644 --- a/config/bouffalolab/toolchain/riscv_toolchain.gni +++ b/config/bouffalolab/toolchain/riscv_toolchain.gni @@ -17,13 +17,18 @@ import("//build_overrides/chip.gni") import("//build_overrides/bouffalolab_iot_sdk.gni") import("${build_root}/toolchain/gcc_toolchain.gni") +import("${chip_root}/src/platform/device.gni") template("riscv_toolchain") { gcc_toolchain(target_name) { _tool_name_root = "" if ("linux" == host_os) { - _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-" + if (chip_device_platform == "bl616") { + _tool_name_root = "${bouffalolab_sdk_root}/toolchain/t-head-riscv/gcc_t-head_v2.6.1/bin/riscv64-unknown-elf-" + } else { + _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-" + } } else if ("mac" == host_os || "darwin" == host_os) { _tool_name_root = "${bouffalolab_sdk_root}/toolchain/riscv/Darwin/bin/riscv64-unknown-elf-" } diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn index 6fc584fa8eeade..e9c45f338a81ef 100644 --- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn @@ -107,7 +107,6 @@ bouffalolab_executable("lighting_app") { defines += [ "BOOT_PIN_RESET=8" ] } - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] diff --git a/examples/lighting-app/bouffalolab/bl616/.gn b/examples/lighting-app/bouffalolab/bl616/.gn new file mode 100644 index 00000000000000..27a24ca4db236b --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/build.gni") + +# The location of the build configuration file. +buildconfig = "${build_root}/config/BUILDCONFIG.gn" + +# CHIP uses angle bracket includes. +check_system_includes = true + +default_args = { + target_cpu = "riscv" + target_os = "freertos" + + import("//args.gni") +} diff --git a/examples/lighting-app/bouffalolab/bl616/BUILD.gn b/examples/lighting-app/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..6671db3f9f7a6d --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,293 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/build.gni") +import("//build_overrides/chip.gni") + +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/common/bouffalolab_executable.gni") +import("${build_root}/config/defaults.gni") +import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/src/platform/bouffalolab/common/args.gni") +import("${chip_root}/src/platform/device.gni") + +import("${chip_root}/src/app/chip_data_model.gni") + +if (chip_enable_pw_rpc) { + import("//build_overrides/pigweed.gni") + import("$dir_pw_build/target_types.gni") +} + +assert(current_os == "freertos") + +example_dir = "${chip_root}/examples/lighting-app/bouffalolab" +examples_plat_dir = "${chip_root}/examples/platform/bouffalolab" + +declare_args() { + # Dump memory usage at link time. + chip_print_memory_usage = true + + # OTA periodic query timeout in seconds + ota_periodic_query_timeout_seconds = 86400 + + # reboot delay in seconds to apply new OTA image + ota_auto_reboot_delay_seconds = 5 + + enable_heap_monitoring = false + enable_reset_counter = false + + setupPinCode = 20202021 + setupDiscriminator = 3840 + + board = "BL616DK" + module_type = "BL616" + baudrate = 2000000 +} + +bouffalo_sdk("sdk") { + include_dirs = [ + "${example_dir}/bl616", + "${examples_plat_dir}/bl616", + "${examples_plat_dir}/common/route_hook", + "${chip_root}/src/platform/bouffalolab/BL616", + "${chip_root}/src/platform/bouffalolab/common", + ] + + defines = [ + "INCLUDE_xSemaphoreGetMutexHolder=1", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE=${setupPinCode}", + "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setupDiscriminator}", + "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_seconds}", + "OTA_AUTO_REBOOT_DELAY=${ota_auto_reboot_delay_seconds}", + "CHIP_UART_BAUDRATE=${baudrate}", + ] + + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + include_dirs += [ "${examples_plat_dir}/common/rpc" ] + defines += [ "PW_RPC_ENABLED=1" ] + defines += [ "DISABLE_PRINT=1" ] + } else if (chip_build_libshell) { + include_dirs += [ "${examples_plat_dir}/common/plat" ] + } + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/bl616/lwipopts" ] + } +} + +chip_data_model("bouffalolab-lighting") { + if (chip_enable_openthread) { + zap_file = "${example_dir}/data_model/lighting-app-thread.zap" + } else if (chip_enable_wifi) { + zap_file = "${example_dir}/data_model/lighting-app-wifi.zap" + } else { + zap_file = "${example_dir}/data_model/lighting-app-ethernet.zap" + } + is_server = true +} + +bouffalolab_executable("lighting_app") { + output_name = "chip-bl616-lighting-example.out" + bl_plat_name = "bl616" + + defines = [ + "APP_TASK_STACK_SIZE=4096", + "CHIP_UART_BAUDRATE=${baudrate}", + "BL616_ENABLE", + "START_ENTRY=main", + ] + + defines += + [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] + + if (chip_config_network_layer_ble) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=1" ] + } + + if (false == enable_reset_counter) { + defines += [ "BOOT_PIN_RESET=2" ] + } + + defines += [ "BL616DK" ] + + sources = [ + "${chip_root}/examples/providers/DeviceInfoProviderImpl.cpp", + "${example_dir}/common/AppTask.cpp", + "${example_dir}/common/ZclCallbacks.cpp", + "${examples_plat_dir}/common/bouffalo_sdk/demo_pwm.c", + "${examples_plat_dir}/common/bouffalo_sdk/platform_port.cpp", + "${examples_plat_dir}/common/plat/LEDWidget.cpp", + "${examples_plat_dir}/common/plat/OTAConfig.cpp", + "${examples_plat_dir}/common/plat/main.cpp", + "${examples_plat_dir}/common/plat/platform.cpp", + ] + + deps = [ + ":bouffalolab-lighting", + ":sdk", + "${chip_root}/examples/providers:device_info_provider", + "${chip_root}/src/lib", + "${chip_root}/src/setup_payload", + ] + + include_dirs = [ + "${chip_root}/src/platform/bouffalolab/BL616", + "${example_dir}/common", + "${example_dir}/bl616", + "${examples_plat_dir}/common/plat", + "${examples_plat_dir}/common/bouffalo_sdk", + ] + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/bl616/lwipopts" ] + } + + if (chip_enable_wifi || chip_enable_ethernet) { + include_dirs += [ "${examples_plat_dir}/common/route_hook" ] + + if (chip_enable_wifi) { + defines += [ "CHIP_DEVICE_CONFIG_ENABLE_WIFI" ] + } + + sources += [ + "${examples_plat_dir}/common/route_hook/bl_route_hook.c", + "${examples_plat_dir}/common/route_hook/bl_route_table.c", + ] + } + + if (chip_enable_openthread) { + import("//build_overrides/openthread.gni") + + deps += [ + "${chip_root}/third_party/openthread/platforms:libopenthread-platform", + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + ] + + if (chip_openthread_ftd) { + defines += [ "CHIP_DEVICE_CONFIG_THREAD_FTD=1" ] + deps += [ + "${openthread_root}:libopenthread-cli-ftd", + "${openthread_root}:libopenthread-ftd", + ] + } else { + defines += [ "CHIP_DEVICE_CONFIG_THREAD_FTD=0" ] + deps += [ + "${openthread_root}:libopenthread-cli-mtd", + "${openthread_root}:libopenthread-mtd", + ] + } + } + + defines += [ "CONFIG_ENABLE_CHIP_SHELL=${chip_build_libshell}" ] + defines += [ "PW_RPC_ENABLED=${chip_enable_pw_rpc}" ] + if (chip_enable_pw_rpc) { + defines += [ + "PW_RPC_ENABLED", + "PW_RPC_ATTRIBUTE_SERVICE=1", + "PW_RPC_BUTTON_SERVICE=1", + "PW_RPC_DESCRIPTOR_SERVICE=1", + "PW_RPC_DEVICE_SERVICE=1", + "PW_RPC_LIGHTING_SERVICE=1", + + #"PW_RPC_TRACING_SERVICE=1", + ] + + sources += [ + "${chip_root}/examples/common/pigweed/RpcService.cpp", + "${chip_root}/examples/common/pigweed/bouffalolab/PigweedLoggerMutex.cpp", + "${examples_plat_dir}/common/rpc/PigweedLogger.cpp", + "${examples_plat_dir}/common/rpc/Rpc.cpp", + ] + + deps += [ + "$dir_pw_hdlc:rpc_channel_output", + "$dir_pw_kvs:crc16", + "$dir_pw_log", + "$dir_pw_stream:sys_io_stream", + + #"$dir_pw_trace", + #"$dir_pw_trace_tokenized", + #"$dir_pw_trace_tokenized:trace_rpc_service", + "${chip_root}/config/bouffalolab/common/lib/pw_rpc:pw_rpc", + "${chip_root}/examples/common/pigweed:attributes_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:button_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:descriptor_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:device_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:lighting_service.nanopb_rpc", + "${examples_plat_dir}/common/rpc/pw_sys_io:pw_sys_io", + ] + + if (chip_enable_openthread) { + deps += [ + "${chip_root}/examples/common/pigweed:ot_cli_service.nanopb_rpc", + "${chip_root}/examples/common/pigweed:thread_service.nanopb_rpc", + ] + } + + deps += pw_build_LINK_DEPS + + include_dirs += [ + "${chip_root}/examples/common", + "${chip_root}/examples/common/pigweed/bouffalolab", + ] + } else if (chip_build_libshell) { + if (chip_build_libshell) { + include_dirs += [ + "${chip_root}/src/lib/shell", + "${chip_root}/examples/shell/shell_common/include", + ] + + deps += [ "${chip_root}/examples/shell/shell_common:shell_common" ] + } + } + + defines += [ "HEAP_MONITORING=${enable_heap_monitoring}" ] + if (enable_heap_monitoring) { + sources += [ "${examples_plat_dir}/common/plat/MemMonitoring.cpp" ] + } + + if (bouffalo_sdk_component_easyflash_enabled) { + defines += [ "BOUFFALO_SDK_COMPONENTS_EASYFLASH_ENABLED=1" ] + } else { + defines += [ "BOUFFALO_SDK_COMPONENTS_EASYFLASH_ENABLED=0" ] + } + + print("bouffalo_sdk_root=${bouffalo_sdk_root}") + cflags_c = [ "-Wno-sign-compare" ] + ldscript = "${bouffalo_sdk_root}/bsp/board/bl616dk/bl616_flash.ld" + + ldflags = [ "-T" + rebase_path(ldscript, root_build_dir) ] + + inputs = [ ldscript ] + + if (chip_print_memory_usage) { + ldflags += [ + "--specs=nano.specs", + "-Wl,--print-memory-usage", + "-fstack-usage", + ] + } + + output_dir = root_out_dir +} + +group("bl616") { + deps = [ ":lighting_app" ] +} + +group("default") { + deps = [ ":bl616" ] +} diff --git a/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h b/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h new file mode 100644 index 00000000000000..51430ca4e69d92 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/CHIPProjectConfig.h @@ -0,0 +1,116 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Example project configuration file for CHIP. + * + * This is a place to put application or project-specific overrides + * to the default configuration values for general CHIP features. + * + */ + +#pragma once + +// Use a default pairing code if one hasn't been provisioned in flash. +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE 20202021 +#endif + +#ifndef CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR 0xF00 +#endif +// For convenience, Chip Security Test Mode can be enabled and the +// requirement for authentication in various protocols can be disabled. +// +// WARNING: These options make it possible to circumvent basic Chip security functionality, +// including message encryption. Because of this they MUST NEVER BE ENABLED IN PRODUCTION BUILDS. +// +#define CHIP_CONFIG_SECURITY_TEST_MODE 0 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID + * + */ +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID 0xFFF1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID + * + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID 0x8005 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION + * + * The hardware version number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software versions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION 1 + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING + * + * A string identifying the software version running on the device. + * CHIP service currently expects the software version to be in the format + * {MAJOR_VERSION}.0d{MINOR_VERSION} + */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING "0.1ALPHA" +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION + * + * A uint32_t identifying the software version running on the device. + */ +/* The SoftwareVersion attribute of the Basic cluster. */ +#ifndef CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION 0x0001 +#endif + +/** + * CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION + * + * The product revision number assigned to device or product by the device vendor. This + * number is scoped to the device product id, and typically corresponds to a revision of the + * physical device, a change to its packaging, and/or a change to its marketing presentation. + * This value is generally *not* incremented for device software revisions. + */ +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_REVISION 1 + +/** + * CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER + * + * Enables the use of a hard-coded default serial number if none + * is found in Chip NV storage. + */ +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER "TEST_SN" + +/** + * CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE + * + * A size, in bytes, of the individual debug event logging buffer. + */ +#define CHIP_DEVICE_CONFIG_EVENT_LOGGING_DEBUG_BUFFER_SIZE (512) + +#define CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY 1 + +#define CHIP_BLE_DEVICE_NAME "MatterLight" diff --git a/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h b/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h new file mode 100644 index 00000000000000..609c13605a90a7 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/FreeRTOSConfig.h @@ -0,0 +1,142 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ +#include +#include + +#define configMTIME_BASE_ADDRESS (0xE0000000UL + 0xBFF8UL) +#define configMTIMECMP_BASE_ADDRESS (0xE0000000UL + 0x4000UL) + +#define configSUPPORT_STATIC_ALLOCATION 1 +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 0 +#define configUSE_TICK_HOOK 0 +#define configCPU_CLOCK_HZ ((uint32_t) (1 * 1000 * 1000)) +#define configTICK_RATE_HZ ((TickType_t) 1000) +#define configMAX_PRIORITIES (32) +#define configMINIMAL_STACK_SIZE \ + ((unsigned short) 128) /* Only needs to be this high as some demo tasks also use this constant. In production only the idle \ + task would use this. */ +#define configTOTAL_HEAP_SIZE ((size_t) 100 * 1024) +#define configMAX_TASK_NAME_LEN (16) +#define configUSE_TRACE_FACILITY 1 +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 0 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 8 +#define configCHECK_FOR_STACK_OVERFLOW 2 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 1 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configGENERATE_RUN_TIME_STATS 1 +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 +#define configUSE_TICKLESS_IDLE 0 +#define configUSE_POSIX_ERRNO 1 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES (2) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY (configMAX_PRIORITIES - 1) +#define configTIMER_QUEUE_LENGTH 4 +#define configTIMER_TASK_STACK_DEPTH (1024) + +/* Task priorities. Allow these to be overridden. */ +#ifndef uartPRIMARY_PRIORITY +#define uartPRIMARY_PRIORITY (configMAX_PRIORITIES - 3) +#endif + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_eTaskGetState 1 +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_xTaskAbortDelay 1 +#define INCLUDE_xTaskGetHandle 1 +#define INCLUDE_xSemaphoreGetMutexHolder 1 + +/* Normal assert() semantics without relying on the provision of an assert.h +header file. */ +void vApplicationMallocFailedHook(void); + +#if __cplusplus +extern "C" void vAssertCalled(void); +#else +void vAssertCalled(void); +#endif +#define configASSERT(x) \ + if ((x) == 0) \ + { \ + printf("file [%s]\r\n", __FILE__); \ + printf("func [%s]\r\n", __FUNCTION__); \ + printf("line [%d]\r\n", __LINE__); \ + printf("%s\r\n", (const char *) (#x)); \ + vAssertCalled(); \ + } + +#if (configUSE_TICKLESS_IDLE != 0) +void vApplicationSleep(uint32_t xExpectedIdleTime); +#define portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime) vApplicationSleep(xExpectedIdleTime) +#endif + +// #define portUSING_MPU_WRAPPERS + +#if (configGENERATE_RUN_TIME_STATS == 1) +#ifdef __cplusplus +extern "C" uint64_t bflb_mtimer_get_time_us(); +#else +extern uint64_t bflb_mtimer_get_time_us(); +#endif +#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() ((void) 0) +#define portGET_RUN_TIME_COUNTER_VALUE() bflb_mtimer_get_time_us() +#endif + +#endif /* FREERTOS_CONFIG_H */ diff --git a/examples/lighting-app/bouffalolab/bl616/args.gni b/examples/lighting-app/bouffalolab/bl616/args.gni new file mode 100644 index 00000000000000..d031a4b769ec88 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/args.gni @@ -0,0 +1,34 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") +import("${chip_root}/config/standalone/args.gni") +import("${chip_root}/src/platform/bouffalolab/BL616/args.gni") + +bouffalo_sdk_target = get_label_info(":sdk", "label_no_toolchain") + +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" + +chip_detail_logging = true + +# use -Os instead of -Og +is_debug = false + +pw_build_LINK_DEPS = [ + "$dir_pw_assert:impl", + "$dir_pw_log:impl", +] diff --git a/examples/lighting-app/bouffalolab/bl616/build_overrides b/examples/lighting-app/bouffalolab/bl616/build_overrides new file mode 120000 index 00000000000000..995884e6163eb5 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/build_overrides @@ -0,0 +1 @@ +../../../build_overrides \ No newline at end of file diff --git a/examples/lighting-app/bouffalolab/bl616/mboard.h b/examples/lighting-app/bouffalolab/bl616/mboard.h new file mode 100644 index 00000000000000..c025609d89472e --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/mboard.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes dev borad compile-time configuration constants for BL602. + * + */ + +#pragma once + +#define CHIP_UART_PORT 0 +#define CHIP_UART_RX_BUFFSIZE 256 + +#define LED_B_PWM_CH 0 +#define LED_B_PIN 0 + +#define LED_R_PWM_CH 1 +#define LED_R_PIN 1 + +#define LED_G_PWM_CH 2 +#define LED_G_PIN 30 + +#define MAX_PWM_CHANNEL 3 + +#define CHIP_UART_PIN_RX 7 +#define CHIP_UART_PIN_TX 16 diff --git a/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip b/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip new file mode 120000 index 00000000000000..59307833b4fee9 --- /dev/null +++ b/examples/lighting-app/bouffalolab/bl616/third_party/connectedhomeip @@ -0,0 +1 @@ +../../../../.. \ No newline at end of file diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn index 209e473e693869..d441eb118205bd 100644 --- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn @@ -135,7 +135,6 @@ bouffalolab_executable("lighting_app") { "START_ENTRY=bl702_main", ] - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] if (chip_config_network_layer_ble) { diff --git a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn index 50d2bd417a2ba4..036b31479dab05 100644 --- a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn +++ b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn @@ -112,7 +112,6 @@ bouffalolab_executable("lighting_app") { "START_ENTRY=bl702_main", ] - defines += [ "CONF_ENABLE_FRAME_PTR=${enable_debug_frame_ptr}" ] defines += [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ] if (chip_config_network_layer_ble) { diff --git a/examples/lighting-app/bouffalolab/bl702l/mboard.h b/examples/lighting-app/bouffalolab/bl702l/mboard.h index 62ee3648eede00..e83529bc168440 100644 --- a/examples/lighting-app/bouffalolab/bl702l/mboard.h +++ b/examples/lighting-app/bouffalolab/bl702l/mboard.h @@ -1,85 +1,85 @@ -/* - * Copyright (c) 2018, The OpenThread Authors. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holder nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/** - * @file - * This file includes dev borad compile-time configuration constants for BL702L. - * - */ - -#pragma once - -#define CHIP_UART_PORT 0 -#define CHIP_UART_RX_BUFFSIZE 256 - -#ifdef BL706_NIGHT_LIGHT - -#define LED_B_PIN_PORT 2 -#define LED_B_PIN 12 - -#define LED_R_PIN_PORT 0 -#define LED_R_PIN 10 - -#define LED_G_PIN_PORT 1 -#define LED_G_PIN 16 - -#define MAX_PWM_CHANNEL 3 - -#elif defined(XT_ZB6_DevKit) - -// #define LED_B_PIN_PORT 3 -// #define LED_B_PIN 18 - -// #define LED_R_PIN_PORT 4 -// #define LED_R_PIN 19 - -// #define LED_G_PIN_PORT 0 -// #define LED_G_PIN 20 - -#define LED_PIN_PORT 3 -#define LED_PIN 18 - -#define MAX_PWM_CHANNEL 1 - -#else - -#define LED_PIN_PORT 2 -#define LED_PIN 22 - -#define MAX_PWM_CHANNEL 1 - -#endif - -#define SPI_WIFI_MISO_PIN 4 -#define SPI_WIFI_MOSI_PIN 5 -#define SPI_WIFI_CLK_PIN 3 -#define SPI_WIFI_CS_PIN 6 -#define SPI_WIFI_IRQ_PIN 10 - -#define CHIP_UART_PIN_RX 15 -#define CHIP_UART_PIN_TX 14 +/* + * Copyright (c) 2018, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file includes dev borad compile-time configuration constants for BL702L. + * + */ + +#pragma once + +#define CHIP_UART_PORT 0 +#define CHIP_UART_RX_BUFFSIZE 256 + +#ifdef BL706_NIGHT_LIGHT + +#define LED_B_PIN_PORT 2 +#define LED_B_PIN 12 + +#define LED_R_PIN_PORT 0 +#define LED_R_PIN 10 + +#define LED_G_PIN_PORT 1 +#define LED_G_PIN 16 + +#define MAX_PWM_CHANNEL 3 + +#elif defined(XT_ZB6_DevKit) + +// #define LED_B_PIN_PORT 3 +// #define LED_B_PIN 18 + +// #define LED_R_PIN_PORT 4 +// #define LED_R_PIN 19 + +// #define LED_G_PIN_PORT 0 +// #define LED_G_PIN 20 + +#define LED_PIN_PORT 3 +#define LED_PIN 18 + +#define MAX_PWM_CHANNEL 1 + +#else + +#define LED_PIN_PORT 2 +#define LED_PIN 22 + +#define MAX_PWM_CHANNEL 1 + +#endif + +#define SPI_WIFI_MISO_PIN 4 +#define SPI_WIFI_MOSI_PIN 5 +#define SPI_WIFI_CLK_PIN 3 +#define SPI_WIFI_CS_PIN 6 +#define SPI_WIFI_IRQ_PIN 10 + +#define CHIP_UART_PIN_RX 15 +#define CHIP_UART_PIN_TX 14 diff --git a/examples/lighting-app/bouffalolab/common/AppTask.cpp b/examples/lighting-app/bouffalolab/common/AppTask.cpp index 5fc74391f05af0..aa2039bf4e8620 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.cpp +++ b/examples/lighting-app/bouffalolab/common/AppTask.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -46,11 +47,17 @@ #include #include +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#ifdef BOOT_PIN_RESET +#include +#endif +#else extern "C" { #include #include #include } +#endif #include "AppTask.h" #include "mboard.h" @@ -66,7 +73,7 @@ using namespace chip::Shell; namespace { -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) ColorLEDWidget sLightLED; #else DimmableLEDWidget sLightLED; @@ -97,6 +104,18 @@ void StartAppTask(void) } #if CONFIG_ENABLE_CHIP_SHELL +#if CHIP_DEVICE_LAYER_TARGET_BL616 +CHIP_ERROR AppTask::StartAppShellTask() +{ + Engine::Root().Init(); + + cmd_misc_init(); + + Engine::Root().RunMainLoop(); + + return CHIP_NO_ERROR; +} +#else void AppTask::AppShellTask(void * args) { Engine::Root().RunMainLoop(); @@ -115,6 +134,7 @@ CHIP_ERROR AppTask::StartAppShellTask() return CHIP_NO_ERROR; } #endif +#endif void AppTask::PostEvent(app_event_t event) { @@ -142,25 +162,11 @@ void AppTask::AppTaskMain(void * pvParameter) #ifdef BOOT_PIN_RESET ButtonInit(); #else - /** Without RESET PIN defined, factory reset will be executed if power cycle count(resetCnt) >= APP_REBOOT_RESET_COUNT */ - uint32_t resetCnt = 0; - size_t saved_value_len = 0; - ef_get_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt), &saved_value_len); - - if (resetCnt > APP_REBOOT_RESET_COUNT) - { - resetCnt = 0; - /** To share with RESET PIN logic, mButtonPressedTime is used to recorded resetCnt increased. - * +1 makes sure mButtonPressedTime is not zero; - * a power cycle during factory reset confirm time APP_BUTTON_PRESS_LONG will cancel factoryreset */ - GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count() + 1; - } - else - { - resetCnt++; - GetAppTask().mButtonPressedTime = 0; - } - ef_set_env_blob(APP_REBOOT_RESET_COUNT_KEY, &resetCnt, sizeof(resetCnt)); + uint32_t resetCnt = 0; + Internal::BLConfig::ReadConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + Internal::BLConfig::WriteConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count(); + ChipLogProgress(NotSpecified, "AppTaskMain %lld, resetCnt %ld", GetAppTask().mButtonPressedTime, resetCnt); #endif GetAppTask().sTimer = @@ -221,6 +227,18 @@ void AppTask::AppTaskMain(void * pvParameter) /** Turn off light to indicate button long press for factory reset is confirmed */ sLightLED.SetOnoff(false); } + +#else + if (APP_EVENT_RESET_CNT & appEvent) + { + if (resetCnt >= APP_REBOOT_RESET_COUNT) + { + GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); + } + ChipLogProgress(NotSpecified, "APP_REBOOT_RESET_COUNT_KEY resetCnt %ld", resetCnt); + resetCnt = 0; + Internal::BLConfig::WriteConfigValue(APP_REBOOT_RESET_COUNT_KEY, resetCnt); + } #endif if (APP_EVENT_IDENTIFY_MASK & appEvent) { @@ -286,7 +304,7 @@ void AppTask::LightingUpdate(app_event_t status) { v.SetNonNull(254); } -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) sLightLED.SetColor(v.Value(), hue, sat); #else sLightLED.SetLevel(v.Value()); @@ -296,7 +314,7 @@ void AppTask::LightingUpdate(app_event_t status) } else { -#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) +#if defined(BL706_NIGHT_LIGHT) || defined(BL602_NIGHT_LIGHT) || defined(BL616DK) /** show yellow to indicate not-provision state for extended color light */ sLightLED.SetColor(254, 35, 254); #else @@ -339,12 +357,12 @@ void AppTask::TimerCallback(TimerHandle_t xTimer) void AppTask::TimerEventHandler(app_event_t event) { +#ifdef BOOT_PIN_RESET uint32_t pressedTime = 0; if (GetAppTask().mButtonPressedTime) { pressedTime = System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime; -#ifdef BOOT_PIN_RESET if (ButtonPressed()) { if (pressedTime > APP_BUTTON_PRESS_LONG) @@ -353,7 +371,7 @@ void AppTask::TimerEventHandler(app_event_t event) } else if (pressedTime >= APP_BUTTON_PRESS_SHORT) { -#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) +#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) || defined(BL616DK) /** change color to indicate to wait factory reset confirm */ sLightLED.SetColor(254, 0, 210); #else @@ -380,26 +398,7 @@ void AppTask::TimerEventHandler(app_event_t event) GetAppTask().mTimerIntvl = APP_BUTTON_PRESSED_ITVL; GetAppTask().mButtonPressedTime = 0; } -#else - if (pressedTime > APP_BUTTON_PRESS_LONG) - { - /** factory reset confirm timeout */ - GetAppTask().mButtonPressedTime = 0; - GetAppTask().PostEvent(APP_EVENT_FACTORY_RESET); - } - else - { -#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) - /** change color to indicate to wait factory reset confirm */ - sLightLED.SetColor(254, 0, 210); -#else - /** toggle led to indicate to wait factory reset confirm */ - sLightLED.Toggle(); -#endif - } -#endif } -#ifdef BOOT_PIN_RESET else { if (ButtonPressed()) @@ -408,6 +407,21 @@ void AppTask::TimerEventHandler(app_event_t event) GetAppTask().mButtonPressedTime = System::SystemClock().GetMonotonicMilliseconds64().count(); } } +#else + if (GetAppTask().mButtonPressedTime && + System::SystemClock().GetMonotonicMilliseconds64().count() - GetAppTask().mButtonPressedTime > APP_BUTTON_PRESS_LONG) + { +#if defined(BL602_NIGHT_LIGHT) || defined(BL706_NIGHT_LIGHT) || defined(BL616DK) + /** change color to indicate to wait factory reset confirm */ + sLightLED.SetColor(254, 0, 210); +#else + /** toggle led to indicate to wait factory reset confirm */ + sLightLED.Toggle(); +#endif + /** factory reset confirm timeout */ + GetAppTask().mButtonPressedTime = 0; + GetAppTask().PostEvent(APP_EVENT_RESET_CNT); + } #endif StartTimer(); @@ -453,23 +467,52 @@ void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction) } #ifdef BOOT_PIN_RESET +#if CHIP_DEVICE_LAYER_TARGET_BL616 +static struct bflb_device_s * app_task_gpio_var = NULL; +static void app_task_gpio_isr(int irq, void * arg) +{ + bool intstatus = bflb_gpio_get_intstatus(app_task_gpio_var, BOOT_PIN_RESET); + if (intstatus) + { + bflb_gpio_int_clear(app_task_gpio_var, BOOT_PIN_RESET); + } + + GetAppTask().ButtonEventHandler(arg); +} +#else static hosal_gpio_dev_t gpio_key = { .port = BOOT_PIN_RESET, .config = INPUT_HIGH_IMPEDANCE, .priv = NULL }; +#endif void AppTask::ButtonInit(void) { GetAppTask().mButtonPressedTime = 0; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + app_task_gpio_var = bflb_device_get_by_name("gpio"); + + bflb_gpio_init(app_task_gpio_var, BOOT_PIN_RESET, GPIO_INPUT); + bflb_gpio_int_init(app_task_gpio_var, BOOT_PIN_RESET, GPIO_INT_TRIG_MODE_SYNC_FALLING_RISING_EDGE); + bflb_gpio_int_mask(app_task_gpio_var, BOOT_PIN_RESET, false); + + bflb_irq_attach(app_task_gpio_var->irq_num, app_task_gpio_isr, app_task_gpio_var); + bflb_irq_enable(app_task_gpio_var->irq_num); +#else hosal_gpio_init(&gpio_key); hosal_gpio_irq_set(&gpio_key, HOSAL_IRQ_TRIG_POS_PULSE, GetAppTask().ButtonEventHandler, NULL); +#endif } bool AppTask::ButtonPressed(void) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + return bflb_gpio_read(app_task_gpio_var, BOOT_PIN_RESET); +#else uint8_t val = 1; hosal_gpio_input_get(&gpio_key, &val); return val == 1; +#endif } void AppTask::ButtonEventHandler(void * arg) diff --git a/examples/lighting-app/bouffalolab/common/AppTask.h b/examples/lighting-app/bouffalolab/common/AppTask.h index bcc9dbaec7a4b5..37f8678e0505eb 100644 --- a/examples/lighting-app/bouffalolab/common/AppTask.h +++ b/examples/lighting-app/bouffalolab/common/AppTask.h @@ -63,11 +63,13 @@ class AppTask APP_EVENT_FACTORY_RESET = 0x00000040, APP_EVENT_BTN_LONG = 0x00000080, APP_EVENT_BTN_ISR = 0x00000100, + APP_EVENT_RESET_CNT = 0x00000200, - APP_EVENT_LIGHTING_ONOFF = 0x00010000, - APP_EVENT_LIGHTING_LEVEL = 0x00020000, - APP_EVENT_LIGHTING_COLOR = 0x00040000, - APP_EVENT_LIGHTING_MASK = APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR, + APP_EVENT_LIGHTING_ONOFF = 0x00010000, + APP_EVENT_LIGHTING_LEVEL = 0x00020000, + APP_EVENT_LIGHTING_COLOR = 0x00040000, + APP_EVENT_LIGHTING_MASK = APP_EVENT_LIGHTING_ONOFF | APP_EVENT_LIGHTING_LEVEL | APP_EVENT_LIGHTING_COLOR, + APP_EVENT_COMMISSION_COMPLETE = APP_EVENT_LIGHTING_MASK, APP_EVENT_IDENTIFY_START = 0x01000000, APP_EVENT_IDENTIFY_IDENTIFY = 0x02000000, @@ -75,7 +77,7 @@ class AppTask APP_EVENT_IDENTIFY_MASK = APP_EVENT_IDENTIFY_START | APP_EVENT_IDENTIFY_IDENTIFY | APP_EVENT_IDENTIFY_STOP, APP_EVENT_ALL_MASK = APP_EVENT_LIGHTING_MASK | APP_EVENT_TIMER | APP_EVENT_BTN_SHORT | APP_EVENT_BTN_LONG | - APP_EVENT_BTN_ISR | APP_EVENT_IDENTIFY_MASK, + APP_EVENT_BTN_ISR | APP_EVENT_RESET_CNT | APP_EVENT_IDENTIFY_MASK, }; void SetEndpointId(EndpointId endpointId) diff --git a/examples/platform/bouffalolab/bl616/BUILD.gn b/examples/platform/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..0a5b997ab0ba7a --- /dev/null +++ b/examples/platform/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") + +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + +config("chip_examples_project_config") { + include_dirs = [ "project_include" ] +} diff --git a/examples/platform/bouffalolab/bl616/args.gni b/examples/platform/bouffalolab/bl616/args.gni new file mode 100644 index 00000000000000..bbab38b1a34ff2 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/args.gni @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +chip_ble_project_config_include = "" +chip_device_project_config_include = "" +chip_project_config_include = "" +chip_inet_project_config_include = "" +chip_system_project_config_include = "" diff --git a/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h b/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h new file mode 100644 index 00000000000000..86b297b66fa8fc --- /dev/null +++ b/examples/platform/bouffalolab/bl616/bl616_lwip_hooks.h @@ -0,0 +1,15 @@ +#ifndef _LWIP_DEFAULT_HOOKS_H_ +#define _LWIP_DEFAULT_HOOKS_H_ +#include "lwip/arch.h" +#include "lwip/err.h" +#include "lwip/ip_addr.h" + +#include "lwiphooks.h" + +extern struct netif * lwip_hook_ip6_route(const ip6_addr_t * src, const ip6_addr_t * dest); +#define LWIP_HOOK_IP6_ROUTE lwip_hook_ip6_route + +extern const ip6_addr_t * lwip_hook_nd6_get_gw(struct netif * netif, const ip6_addr_t * dest); +#define LWIP_HOOK_ND6_GET_GW lwip_hook_nd6_get_gw + +#endif /* _LWIP_DEFAULT_HOOKS_H_ */ diff --git a/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml b/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml new file mode 100644 index 00000000000000..c6fa8320dda795 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/flash_config/partition_cfg_4M.toml @@ -0,0 +1,141 @@ +[pt_table] +#partition table is 4K in size +address0 = 0xE000 +address1 = 0xF000 +# If version is 2, It will use dynamic mode. +version = 2 + +[[pt_entry]] +type = 16 +name = "Boot2" +device = 0 +address0 = 0 +size0 = 0xE000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 0 +name = "FW" +device = 0 +address0 = 0x10000 +size0 = 0x200000 +address1 = 0x210000 +size1 = 0x168000 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 10 +name = "mfg" +device = 0 +address0 = 0x210000 +size0 = 0x168000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 1 +# If header is 1 and security is 1, It will be encrypted. +security = 1 + +[[pt_entry]] +type = 2 +name = "media" +device = 0 +address0 = 0x378000 +size0 = 0x71000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 3 +name = "PSM" +device = 0 +address0 = 0x3E9000 +size0 = 0x8000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 4 +name = "KEY" +device = 0 +address0 = 0x3F1000 +size0 = 0x2000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 5 +name = "DATA" +device = 0 +address0 = 0x3F1000 +size0 = 0x5000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 6 +name = "factory" +device = 0 +address0 = 0x3F6000 +size0 = 0x8000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 + +[[pt_entry]] +type = 7 +name = "MFD" +device = 0 +address0 = 0x3FE000 +size0 = 0x1000 +address1 = 0 +size1 = 0 +# compressed image must set len,normal image can left it to 0 +len = 0 +# If header is 1, it will add the header. +header = 0 +# If header is 1 and security is 1, It will be encrypted. +security = 0 diff --git a/examples/platform/bouffalolab/bl616/lwipopts.h b/examples/platform/bouffalolab/bl616/lwipopts.h new file mode 100644 index 00000000000000..91d779fb9356e5 --- /dev/null +++ b/examples/platform/bouffalolab/bl616/lwipopts.h @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_LWIPOPTS_H__ +#define LWIP_HDR_LWIPOPTS_H__ + +#include "arch/sys_arch.h" +#include "rtos_def.h" +#include + +#if defined(__cplusplus) +extern "C" long random(void); +extern "C" int * __errno(void); +extern "C" uint16_t fhost_ip_chksum(const void * dataptr, int len); +extern "C" sys_mutex_t lock_tcpip_core; +extern "C" int sys_is_inside_interrupt(void); +extern "C" int sys_mutex_is_locked(sys_mutex_t * mutex); +extern "C" int sys_current_is_tcpip(void); +#else +extern long random(void); +extern int * __errno(void); +extern uint16_t fhost_ip_chksum(const void * dataptr, int len); +extern sys_mutex_t lock_tcpip_core; +extern int sys_is_inside_interrupt(void); +extern int sys_mutex_is_locked(sys_mutex_t * mutex); +extern int sys_current_is_tcpip(void); +extern const int fhost_tcpip_priority; +#endif + +#define LWIP_TCPIP_CORE_LOCKING 1 +#define IP_DEFAULT_TTL 64 + +#if defined(CONFIG_HIGH_PERFORMANCE) && (CONFIG_HIGH_PERFORMANCE == 1) +#define LWIP_ASSERT_CORE_LOCKED() +#define LWIP_NOASSERT +#else +#if LWIP_TCPIP_CORE_LOCKING +#define LWIP_ASSERT_CORE_LOCKED() \ + do \ + { \ + if (lock_tcpip_core) \ + { \ + LWIP_ASSERT("api must call with lwip core lock", !sys_is_inside_interrupt() && sys_mutex_is_locked(&lock_tcpip_core)); \ + } \ + } while (0) +#else +#define LWIP_ASSERT_CORE_LOCKED() \ + do \ + { \ + LWIP_ASSERT("api must call inside lwip task", !sys_is_inside_interrupt() && sys_current_is_tcpip()); \ + } while (0) +#endif +#endif + +#define LWIP_NETIF_API 1 +#define LWIP_DEBUG 1 +#define LWIP_STATS_DISPLAY 1 +#define SOCKETS_DEBUG LWIP_DBG_OFF +#ifdef BL616_DHCP_DEBUG +#define DHCP_DEBUG LWIP_DBG_ON +#else +#define DHCP_DEBUG LWIP_DBG_OFF +#endif +#define ICMP_DEBUG LWIP_DBG_OFF +#define ETHARP_DEBUG LWIP_DBG_OFF +#define LWIP_MULTICAST_PING 1 +#define LWIP_BROADCAST_PING 1 + +#define TCPIP_MBOX_SIZE 64 +#define TCPIP_THREAD_STACKSIZE FHOST_TCPIP_STACK_SIZE +#define TCPIP_THREAD_PRIO fhost_tcpip_priority + +#define DEFAULT_THREAD_STACKSIZE 1024 +#define DEFAULT_THREAD_PRIO 1 +#define DEFAULT_RAW_RECVMBOX_SIZE 32 +#define DEFAULT_UDP_RECVMBOX_SIZE 64 +#define DEFAULT_TCP_RECVMBOX_SIZE 64 +#define DEFAULT_ACCEPTMBOX_SIZE 32 + +#define LWIP_NETIF_LOOPBACK 1 +#define LWIP_HAVE_LOOPIF 1 +#define LWIP_LOOPBACK_MAX_PBUFS 0 + +#define LWIP_CHKSUM_ALGORITHM 3 +#define LWIP_CHKSUM fhost_ip_chksum +#define LWIP_TCPIP_CORE_LOCKING_INPUT 1 + +#define PBUF_LINK_ENCAPSULATION_HLEN 388 + +#define MEMP_NUM_NETBUF 32 +#define MEMP_NUM_NETCONN 16 +#define MEMP_NUM_UDP_PCB 16 +#define MEMP_NUM_REASSDATA LWIP_MIN((IP_REASS_MAX_PBUFS), 5) + +#define PBUF_POOL_SIZE 0 +#define MEM_ALIGNMENT 4 +#define MEM_SIZE 30720 +#define PBUF_POOL_BUFSIZE (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + 1280) +#define MEMP_MEM_MALLOC 1 + +// #define LWIP_HOOK_FILENAME "lwiphooks.h" +#define LWIP_HOOK_FILENAME "bl616_lwip_hooks.h" + +#define LWIP_RAW 1 +#define LWIP_MULTICAST_TX_OPTIONS 1 + +#define LWIP_TIMEVAL_PRIVATE \ + 0 // use sys/time.h for struct timeval + // +// #define LWIP_PROVIDE_ERRNO 1 +#ifndef PLATFORM_PRIVDE_ERRNO +#define LWIP_PROVIDE_ERRNO 1 +#else +#define LWIP_ERRNO_STDINCLUDE 1 +#define LWIP_SOCKET_SET_ERRNO 1 +#endif + +#define LWIP_DHCP 1 +#define LWIP_DNS 1 +#define LWIP_IGMP 1 +#define LWIP_SO_RCVTIMEO 1 +#define LWIP_SO_SNDTIMEO 1 +#define SO_REUSE 1 +#define LWIP_TCP_KEEPALIVE 1 +#define LWIP_SO_RCVBUF 1 + +#define LWIP_IPV6 1 +#define LWIP_IPV6_DHCP6 1 +#define LWIP_IPV6_SCOPES 0 +#define LWIP_IPV6_MLD 1 +#define MEMP_NUM_MLD6_GROUP 10 + +#define MEMP_NUM_SYS_TIMEOUT (LWIP_NUM_SYS_TIMEOUT_INTERNAL + 8 + 3) + +#define LWIP_NETIF_STATUS_CALLBACK 1 +#define LWIP_NETIF_API 1 +#define LWIP_NETIF_EXT_STATUS_CALLBACK 1 + +#define ETHARP_SUPPORT_STATIC_ENTRIES 1 + +#define LWIP_SUPPORT_CUSTOM_PBUF 1 +#ifdef HIGH_PERFORMANCE_PBUF +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#else +#define LWIP_NETIF_TX_SINGLE_PBUF 1 +#endif +#define LWIP_RAND() ((u32_t) rand()) +#undef LWIP_DECLARE_MEMORY_ALIGNED +#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) \ + u8_t variable_name[size] __attribute__((aligned(4))) __attribute__((section("SHAREDRAM"))) + +#endif /* LWIP_HDR_LWIPOPTS_H__ */ diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c b/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c new file mode 100644 index 00000000000000..98d1201af8391e --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/demo_pwm.c @@ -0,0 +1,157 @@ +/** + * Copyright (c) 2016-2021 Bouffalolab Co., Ltd. + * + * Contact information: + * web site: https://www.bouffalolab.com/ + */ +#include +#include +#include +#include + +#include "demo_pwm.h" +#include "mboard.h" + +#if MAX_PWM_CHANNEL == 3 +static const uint32_t rgb_pwm[MAX_PWM_CHANNEL][2] = { + { LED_B_PIN, LED_B_PWM_CH }, + { LED_R_PIN, LED_R_PWM_CH }, + { LED_G_PIN, LED_G_PWM_CH }, +}; +#else +static const uint32_t rgb_pwm[][2] = { + { LED_PIN, LED_PIN_PWM_CH }, +}; +#endif + +struct bflb_device_s * bflb_device_pwm = NULL; + +void demo_pwm_init(void) +{ + struct bflb_pwm_v2_config_s cfg = { + .clk_source = BFLB_SYSTEM_PBCLK, + .clk_div = 40, + .period = 1000, + }; + struct bflb_device_s * gpio = bflb_device_get_by_name("gpio"); + + bflb_device_pwm = bflb_device_get_by_name("pwm_v2_0"); + + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_gpio_init(gpio, rgb_pwm[i][0], GPIO_FUNC_PWM0 | GPIO_ALTERNATE | GPIO_PULLDOWN | GPIO_SMT_EN | GPIO_DRV_1); + } + + bflb_pwm_v2_init(bflb_device_pwm, &cfg); +} + +void demo_pwm_start(void) +{ + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_pwm_v2_channel_positive_start(bflb_device_pwm, rgb_pwm[i][1]); + } + + bflb_pwm_v2_start(bflb_device_pwm); +} + +void demo_pwm_stop(void) +{ + bflb_pwm_v2_stop(bflb_device_pwm); +} + +void set_level(uint8_t currLevel) +{ + int period; + + if (currLevel <= 5 && currLevel >= 1) + { + currLevel = 5; // avoid demo off + } + period = (int) currLevel * 1000 / 254; + + for (int i = 0; i < sizeof(rgb_pwm) / sizeof(rgb_pwm[0]); i++) + { + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[i][1], 0, period); + } +} + +void set_color_red(uint8_t currLevel) +{ + set_color(currLevel, 0, 254); +} + +void set_color_green(uint8_t currLevel) +{ + set_color(currLevel, 84, 254); +} + +void set_color_yellow(uint8_t currLevel) +{ + set_color(currLevel, 42, 254); +} + +void set_color(uint8_t currLevel, uint8_t currHue, uint8_t currSat) +{ +#if MAX_PWM_CHANNEL == 3 + uint16_t hue = (uint16_t) currHue * 360 / 254; + uint8_t sat = (uint16_t) currSat * 100 / 254; + + if (currLevel <= 5 && currLevel >= 1) + { + currLevel = 5; // avoid demo off + } + + if (sat > 100) + { + sat = 100; + } + + uint16_t i = hue / 60; + uint16_t rgb_max = currLevel; + uint16_t rgb_min = rgb_max * (100 - sat) / 100; + uint16_t diff = hue % 60; + uint16_t rgb_adj = (rgb_max - rgb_min) * diff / 60; + uint32_t red, green, blue; + + switch (i) + { + case 0: + red = rgb_max; + green = rgb_min + rgb_adj; + blue = rgb_min; + break; + case 1: + red = rgb_max - rgb_adj; + green = rgb_max; + blue = rgb_min; + break; + case 2: + red = rgb_min; + green = rgb_max; + blue = rgb_min + rgb_adj; + break; + case 3: + red = rgb_min; + green = rgb_max - rgb_adj; + blue = rgb_max; + break; + case 4: + red = rgb_min + rgb_adj; + green = rgb_min; + blue = rgb_max; + break; + default: + red = rgb_max; + green = rgb_min; + blue = rgb_max - rgb_adj; + break; + } + + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[0][1], 0, blue * 1000 / 254); + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[1][1], 0, red * 1000 / 254); + bflb_pwm_v2_channel_set_threshold(bflb_device_pwm, rgb_pwm[2][1], 0, green * 1000 / 254); +#else + set_level(currLevel); +#endif +} diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp new file mode 100644 index 00000000000000..f92b527b410d3a --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp @@ -0,0 +1,63 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +extern "C" { +#include +#include +} +#include + +extern "C" void __libc_init_array(void); +extern "C" void shell_init_with_task(struct bflb_device_s * shell); + +void platform_port_init(void) +{ + /*if need use xtal 32k please enable next API */ + board_init(); +#if CONFIG_ENABLE_CHIP_SHELL + struct bflb_device_s * uart0 = bflb_device_get_by_name("uart0"); + shell_init_with_task(uart0); +#endif + + __libc_init_array(); + + bflb_mtd_init(); +} + +extern "C" void vAssertCalled(void) +{ + void * ra = (void *) __builtin_return_address(0); + + taskDISABLE_INTERRUPTS(); + if (xPortIsInsideInterrupt()) + { + printf("vAssertCalled, ra = %p in ISR\r\n", (void *) ra); + } + else + { + printf("vAssertCalled, ra = %p in task %s\r\n", (void *) ra, pcTaskGetName(NULL)); + } + + while (true) + ; +} + +extern "C" void bflb_assert(void) __attribute__((weak, alias("vAssertCalled"))); diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c new file mode 100644 index 00000000000000..ef763dd286982d --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.c @@ -0,0 +1,228 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may nCHIP use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include + +#ifdef CFG_USB_CDC_ENABLE +#include +#include +#include +#include +#include +#include +#include +#else +#include +#include +extern hosal_uart_dev_t uart_stdio; +#endif + +#if CONFIG_ENABLE_CHIP_SHELL || PW_RPC_ENABLED + +#define CHIP_UART_RX_TIMER_ID 1 +#define MAX_BUFFER_SIZE 256 + +typedef struct _chipUart +{ + SemaphoreHandle_t sema; + StaticSemaphore_t mutx; + uint32_t head; + uint32_t tail; + uint8_t rxbuf[MAX_BUFFER_SIZE]; +} chipUart_t; + +static chipUart_t chipUart_var; + +#ifndef CFG_USB_CDC_ENABLE +static int uartTxCallback(void * p_arg) +{ + hosal_uart_ioctl(&uart_stdio, HOSAL_UART_TX_TRIGGER_OFF, NULL); + + return 0; +} + +static int uartRxCallback(void * p_arg) +{ + uint32_t len = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + } + } + else + { + chipUart_var.head += + hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } + + return 0; +} +#else +void aosUartRxCallback(int fd, void * param) +{ + uint32_t len = 0, readlen = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + readlen = len = aos_read(fd, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + len = aos_read(fd, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + readlen += len; + } + } + else + { + readlen = aos_read(fd, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + chipUart_var.head += readlen; + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } +} +#endif + +// bl_iot_sdk +#else +static int uartTxCallback(void * p_arg) +{ + + return 0; +} + +static int uartRxCallback(void * p_arg) +{ + uint32_t len = 0; + BaseType_t xHigherPriorityTaskWoken = 1; + + if (chipUart_var.head >= chipUart_var.tail) + { + if (chipUart_var.head < MAX_BUFFER_SIZE) + { + // len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head); + chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE; + } + + if (0 == chipUart_var.head) + { + // len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf, chipUart_var.tail - 1); + chipUart_var.head += len; + } + } + else + { + chipUart_var.head += + // hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1); + } + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken); + } + + return 0; +} + +void uartInit(void) +{ + memset(&chipUart_var, 0, offsetof(chipUart_t, rxbuf)); + + chipUart_var.sema = xSemaphoreCreateBinaryStatic(&chipUart_var.mutx); + +#ifndef CFG_USB_CDC_ENABLE + hosal_uart_finalize(&uart_stdio); + hosal_uart_init(&uart_stdio); + hosal_uart_callback_set(&uart_stdio, HOSAL_UART_RX_CALLBACK, uartRxCallback, NULL); + hosal_uart_callback_set(&uart_stdio, HOSAL_UART_TX_CALLBACK, uartTxCallback, NULL); + hosal_uart_ioctl(&uart_stdio, HOSAL_UART_MODE_SET, (void *) HOSAL_UART_MODE_INT); +#endif +} + +int16_t uartRead(char * Buf, uint16_t NbBytesToRead) +{ + int16_t len = 0; + + xSemaphoreTake(chipUart_var.sema, portMAX_DELAY); + + taskENTER_CRITICAL(); + + for (len = 0; len < NbBytesToRead && chipUart_var.head != chipUart_var.tail; len++) + { + Buf[len] = chipUart_var.rxbuf[chipUart_var.tail]; + chipUart_var.tail = (chipUart_var.tail + 1) % MAX_BUFFER_SIZE; + } + + taskEXIT_CRITICAL(); + + if (chipUart_var.head != chipUart_var.tail) + { + xSemaphoreGive(chipUart_var.sema); + } + + return len; +} +#endif + +#ifndef CFG_USB_CDC_ENABLE +int16_t uartWrite(const char * Buf, uint16_t BufLength) +{ + return hosal_uart_send(&uart_stdio, Buf, BufLength); +} +#else +int16_t uartWrite(const char * Buf, uint16_t BufLength) +{ + uint16_t sent = 0; + do + { + extern int vfs_fd; + if (vfs_fd >= 0) + { + sent += (uint8_t) aos_write(vfs_fd, Buf + sent, BufLength - sent); + } + } while (sent < BufLength); + return sent; +} +#endif diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h new file mode 100644 index 00000000000000..44d49ac24f60ff --- /dev/null +++ b/examples/platform/bouffalolab/common/bouffalo_sdk/uart.h @@ -0,0 +1,37 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void uartInit(void); +int16_t uartWrite(const char * Buf, uint16_t BufLength); +int16_t uartRead(char * Buf, uint16_t NbBytesToRead); + +#ifdef CFG_USB_CDC_ENABLE +void aosUartRxCallback(int fd, void * param); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp index 50dccc666c2a9a..6c457b6443101e 100644 --- a/examples/platform/bouffalolab/common/plat/platform.cpp +++ b/examples/platform/bouffalolab/common/plat/platform.cpp @@ -159,7 +159,7 @@ void ChipEventHandler(const ChipDeviceEvent * event, intptr_t arg) break; case DeviceEventType::kCommissioningComplete: ChipLogProgress(NotSpecified, "Commissioning complete"); - GetAppTask().PostEvent(AppTask::APP_EVENT_LIGHTING_MASK); + GetAppTask().PostEvent(AppTask::APP_EVENT_COMMISSION_COMPLETE); break; default: break; diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index e6c166efba9897..807a89b379a926 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -15,7 +15,7 @@ from builders.ameba import AmebaApp, AmebaBoard, AmebaBuilder from builders.android import AndroidApp, AndroidBoard, AndroidBuilder, AndroidProfile from builders.asr import ASRApp, ASRBoard, ASRBuilder -from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder +from builders.bouffalolab import BouffalolabApp, BouffalolabBoard, BouffalolabBuilder, BouffalolabThreadType from builders.cc32xx import cc32xxApp, cc32xxBuilder from builders.cyw30739 import Cyw30739App, Cyw30739Board, Cyw30739Builder from builders.efr32 import Efr32App, Efr32Board, Efr32Builder @@ -692,40 +692,46 @@ def BuildBouffalolabTarget(): # Boards target.AppendFixedTargets([ TargetPart('BL602DK', - board=BouffalolabBoard.BL602_IoT_Matter_V1, module_type="BL602"), + board=BouffalolabBoard.BL602DK, module_type="BL602"), + TargetPart('BL616DK', board=BouffalolabBoard.BL616DK, module_type="BL616"), TargetPart('BL704LDK', board=BouffalolabBoard.BL704LDK, module_type="BL704L"), TargetPart('BL706DK', board=BouffalolabBoard.BL706DK, module_type="BL706C-22"), TargetPart('BL602-NIGHT-LIGHT', - board=BouffalolabBoard.BL602_NIGHT_LIGHT, module_type="BL602"), + board=BouffalolabBoard.BL602_NIGHT_LIGHT, module_type="BL602", enable_resetCnt=True), TargetPart('BL706-NIGHT-LIGHT', - board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL706C-22"), + board=BouffalolabBoard.BL706_NIGHT_LIGHT, module_type="BL706C-22", enable_resetCnt=True), TargetPart('BL602-IoT-Matter-V1', board=BouffalolabBoard.BL602_IoT_Matter_V1, module_type="BL602"), TargetPart('XT-ZB6-DevKit', board=BouffalolabBoard.XT_ZB6_DevKit, module_type="BL706C-22"), ]) - # Apps target.AppendFixedTargets([ TargetPart('light', app=BouffalolabApp.LIGHT), ]) - target.AppendModifier('ethernet', enable_ethernet=True) - target.AppendModifier('wifi', enable_wifi=True) - target.AppendModifier('thread', enable_thread=True) - target.AppendModifier('easyflash', enable_easyflash=True) - target.AppendModifier('littlefs', enable_littlefs=True) + target.AppendFixedTargets([ + TargetPart('ethernet', enable_ethernet=True), + TargetPart('wifi', enable_wifi=True), + TargetPart('thread', enable_thread_type=BouffalolabThreadType.THREAD_FTD), + TargetPart('thread-ftd', enable_thread_type=BouffalolabThreadType.THREAD_FTD), + TargetPart('thread-mtd', enable_thread_type=BouffalolabThreadType.THREAD_MTD), + ]) + + target.AppendFixedTargets([ + TargetPart('easyflash', enable_easyflash=True), + TargetPart('littlefs', enable_littlefs=True), + ]) + target.AppendModifier('shell', enable_shell=True) target.AppendModifier('mfd', enable_mfd=True) target.AppendModifier('rotating_device_id', enable_rotating_device_id=True) - target.AppendModifier('rpc', enable_rpcs=True) - target.AppendModifier('cdc', enable_cdc=True) - target.AppendModifier('mot', use_matter_openthread=True) - target.AppendModifier('resetCnt', enable_resetCnt=True) + target.AppendModifier('rpc', enable_rpcs=True, baudrate=115200).OnlyIfRe('-(bl602dk|bl704ldk|bl706dk)') + target.AppendModifier('cdc', enable_cdc=True).OnlyIfRe('-(bl706dk)') + target.AppendModifier('mot', use_matter_openthread=True).OnlyIfRe('-(thread)') target.AppendModifier('memmonitor', enable_heap_monitoring=True) - target.AppendModifier('115200', baudrate=115200) - target.AppendModifier('fp', enable_frame_ptr=True) + target.AppendModifier('coredump', enable_debug_coredump=True) return target diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py index 09d5f250f5b221..049cacbb97eb7b 100644 --- a/scripts/build/builders/bouffalolab.py +++ b/scripts/build/builders/bouffalolab.py @@ -14,6 +14,7 @@ import logging import os +import time from enum import Enum, auto from .builder import BuilderOutput @@ -22,6 +23,7 @@ class BouffalolabApp(Enum): LIGHT = auto() + CONTACT = auto() def ExampleName(self): if self == BouffalolabApp.LIGHT: @@ -32,26 +34,33 @@ def ExampleName(self): def AppNamePrefix(self, chip_name): if self == BouffalolabApp.LIGHT: return ('chip-%s-lighting-example' % chip_name) - else: - raise Exception('Unknown app type: %r' % self) - - def FlashBundleName(self): - if self == BouffalolabApp.LIGHT: - return 'lighting_app.flashbundle.txt' + elif self == BouffalolabApp.CONTACT: + return ('chip-%s-contact-example' % chip_name) else: raise Exception('Unknown app type: %r' % self) class BouffalolabBoard(Enum): + BL602DK = auto() + BL616DK = auto() + BL704LDK = auto() + BL706DK = auto() BL602_IoT_Matter_V1 = auto() BL602_NIGHT_LIGHT = auto() XT_ZB6_DevKit = auto() BL706_NIGHT_LIGHT = auto() - BL706DK = auto() - BL704LDK = auto() def GnArgName(self): - if self == BouffalolabBoard.BL602_IoT_Matter_V1: + + if self == BouffalolabBoard.BL602DK: + return 'BL602DK' + elif self == BouffalolabBoard.BL616DK: + return 'BL616DK' + elif self == BouffalolabBoard.BL704LDK: + return 'BL704LDK' + elif self == BouffalolabBoard.BL706DK: + return 'BL706DK' + elif self == BouffalolabBoard.BL602_IoT_Matter_V1: return 'BL602-IoT-Matter-V1' elif self == BouffalolabBoard.BL602_NIGHT_LIGHT: return 'BL602-NIGHT-LIGHT' @@ -59,14 +68,16 @@ def GnArgName(self): return 'XT-ZB6-DevKit' elif self == BouffalolabBoard.BL706_NIGHT_LIGHT: return 'BL706-NIGHT-LIGHT' - elif self == BouffalolabBoard.BL706DK: - return 'BL706DK' - elif self == BouffalolabBoard.BL704LDK: - return 'BL704LDK' else: raise Exception('Unknown board #: %r' % self) +class BouffalolabThreadType(Enum): + NONE = auto() + THREAD_FTD = auto() + THREAD_MTD = auto() + + class BouffalolabBuilder(GnBuilder): def __init__(self, @@ -84,12 +95,12 @@ def __init__(self, enable_mfd: bool = False, enable_ethernet: bool = False, enable_wifi: bool = False, - enable_thread: bool = False, - enable_frame_ptr: bool = False, + enable_thread_type: BouffalolabThreadType = BouffalolabThreadType.NONE, enable_heap_monitoring: bool = False, use_matter_openthread: bool = False, enable_easyflash: bool = False, - enable_littlefs: bool = False + enable_littlefs: bool = False, + enable_debug_coredump: bool = False, ): if 'BL602' == module_type: @@ -98,6 +109,8 @@ def __init__(self, bouffalo_chip = 'bl702l' elif "BL70" in module_type: bouffalo_chip = 'bl702' + elif "BL616" == module_type: + bouffalo_chip = "bl616" else: raise Exception(f"module_type {module_type} is not supported") @@ -120,6 +133,8 @@ def __init__(self, self.argsOpt.append(f'board="{self.board.GnArgName()}"') self.argsOpt.append(f'baudrate="{baudrate}"') + enable_thread = False if enable_thread_type == BouffalolabThreadType.NONE else True + if not (enable_wifi or enable_thread or enable_ethernet): # decide default connectivity for each chip if bouffalo_chip == "bl602": @@ -128,6 +143,8 @@ def __init__(self, enable_wifi, enable_thread, enable_ethernet = False, True, False elif bouffalo_chip == "bl702l": enable_wifi, enable_thread, enable_ethernet = False, True, False + elif bouffalo_chip == "bl616": + raise Exception("Must select one of wifi and thread to build.") if [enable_wifi, enable_thread, enable_ethernet].count(True) > 1: raise Exception('Currently, only one of wifi, thread and ethernet supports.') @@ -144,15 +161,15 @@ def __init__(self, elif bouffalo_chip == "bl702l": if enable_ethernet or enable_wifi: raise Exception(f"SoC {bouffalo_chip} does NOT support connectivity Ethernet/Wi-Fi currently.") + elif bouffalo_chip == "bl616": + if enable_ethernet: + raise Exception(f"SoC {bouffalo_chip} does NOT support connectivity Ethernet currently.") if enable_thread: chip_mdns = "platform" elif enable_ethernet or enable_wifi: chip_mdns = "minimal" - if enable_frame_ptr and bouffalo_chip == "bl616": - raise Exception("BL616 does NOT support frame pointer for debug purpose.") - self.argsOpt.append(f'chip_enable_ethernet={str(enable_ethernet).lower()}') self.argsOpt.append(f'chip_enable_wifi={str(enable_wifi).lower()}') self.argsOpt.append(f'chip_enable_openthread={str(enable_thread).lower()}') @@ -165,25 +182,37 @@ def __init__(self, if enable_easyflash and enable_littlefs: raise Exception("Only one of easyflash and littlefs can be enabled.") - - if not enable_easyflash and not enable_littlefs: - logging.fatal('*' * 80) - logging.fatal('littlefs is added to support for flash storage access.') - logging.fatal('Please consider and select one of easyflash and littlefs to use.') - logging.fatal('*' * 80) - raise Exception("None of easyflash and littlefs select to build.") + if bouffalo_chip == "bl616": + if not enable_easyflash: + enable_littlefs = True + else: + if not enable_easyflash and not enable_littlefs: + logging.fatal('*' * 80) + logging.fatal('littlefs is added to support for flash storage access.') + logging.fatal('Please consider and select one of easyflash and littlefs to use.') + logging.fatal('*' * 80) + raise Exception("None of easyflash and littlefs select to build.") self.argsOpt.append(f'bouffalo_sdk_component_easyflash_enabled={"false" if enable_littlefs else "true"}') if enable_thread: + self.argsOpt.append('chip_system_config_use_open_thread_inet_endpoints=true') self.argsOpt.append('chip_with_lwip=false') self.argsOpt.append(f'openthread_project_core_config_file="{bouffalo_chip}-openthread-core-bl-config.h"') self.argsOpt.append(f'openthread_package_version="7e32165be"') + if enable_thread_type == BouffalolabThreadType.THREAD_FTD: + self.argsOpt.append(f'chip_openthread_ftd=true') + else: + self.argsOpt.append(f'chip_openthread_ftd=false') + if not use_matter_openthread: if bouffalo_chip in {"bl702", "bl702l"}: self.argsOpt.append( 'openthread_root="//third_party/connectedhomeip/third_party/bouffalolab/repo/components/network/thread/openthread"') + else: + self.argsOpt.append( + 'openthread_root="//third_party/connectedhomeip/third_party/bouffalolab/bouffalo_sdk/components/wireless/thread/openthread"') if enable_cdc: if bouffalo_chip != "bl702": @@ -208,9 +237,12 @@ def __init__(self, if enable_mfd: self.argsOpt.append("chip_enable_factory_data=true") - self.enable_frame_ptr = enable_frame_ptr - self.argsOpt.append(f"enable_debug_frame_ptr={str(enable_frame_ptr).lower()}") self.argsOpt.append(f"enable_heap_monitoring={str(enable_heap_monitoring).lower()}") + if enable_debug_coredump: + self.argsOpt.append(f"enable_debug_coredump=true") + self.argsOpt.append(f"coredump_binary_id={int(time.time())}") + + self.argsOpt.append(f"chip_generate_link_map_file=true") try: self.argsOpt.append('bouffalolab_sdk_root="%s"' % os.environ['BOUFFALOLAB_SDK_ROOT']) @@ -229,11 +261,7 @@ def print_enviroment_error(self): logging.fatal('*' * 80) def GnBuildArgs(self): - if self.enable_frame_ptr: - debug_output_file = os.path.join(self.output_dir, '%s.out' % self.app.AppNamePrefix(self.chip_name)) - return self.argsOpt + [f'debug_output_file="{debug_output_file}"'] - else: - return self.argsOpt + return self.argsOpt def build_outputs(self): extensions = ["out"] @@ -251,8 +279,12 @@ def PreBuildCommand(self): def PostBuildCommand(self): + bouffalo_sdk_chips = ["bl616"] abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin") + if self.chip_name not in bouffalo_sdk_chips: + abs_path_fw_raw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw") + if os.path.isfile(abs_path_fw): target_dir = self.output_dir.replace(self.chip_dir, "").strip("/") diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 4b49560e64a837..38ae7cccdf3560 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -1,7 +1,7 @@ ameba-amebad-{all-clusters,all-clusters-minimal,light,light-switch,pigweed} asr-{asr582x,asr595x,asr550x}-{all-clusters,all-clusters-minimal,lighting,light-switch,lock,bridge,temperature-measurement,thermostat,ota-requestor,dishwasher,refrigerator}[-ota][-shell][-no_logging][-factory][-rotating_id][-rio] android-{arm,arm64,x86,x64,androidstudio-arm,androidstudio-arm64,androidstudio-x86,androidstudio-x64}-{chip-tool,chip-test,tv-server,tv-casting-app,java-matter-controller,kotlin-matter-controller,virtual-device-app}[-no-debug] -bouffalolab-{bl602dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-light[-ethernet][-wifi][-thread][-easyflash][-littlefs][-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-resetcnt][-memmonitor][-115200][-fp] +bouffalolab-{bl602dk,bl616dk,bl704ldk,bl706dk,bl602-night-light,bl706-night-light,bl602-iot-matter-v1,xt-zb6-devkit}-light-{ethernet,wifi,thread,thread-ftd,thread-mtd}-{easyflash,littlefs}[-shell][-mfd][-rotating_device_id][-rpc][-cdc][-mot][-memmonitor][-coredump] cc32xx-{lock,air-purifier} ti-cc13x4_26x4-{lighting,lock,pump,pump-controller}[-mtd][-ftd] cyw30739-{cyw30739b2_p5_evk_01,cyw30739b2_p5_evk_02,cyw30739b2_p5_evk_03,cyw930739m2evb_01,cyw930739m2evb_02}-{light,light-switch,lock,thermostat} diff --git a/scripts/flashing/bouffalolab_firmware_utils.py b/scripts/flashing/bouffalolab_firmware_utils.py index 2c4e1cca4c5789..e6ca898609102f 100755 --- a/scripts/flashing/bouffalolab_firmware_utils.py +++ b/scripts/flashing/bouffalolab_firmware_utils.py @@ -14,6 +14,7 @@ # limitations under the License. import binascii +import configparser import logging import os import pathlib @@ -224,6 +225,7 @@ class Flasher(firmware_utils.Flasher): args = {} work_dir = None + bouffalo_sdk_chips = ["bl616"] def __init__(self, **options): super().__init__(platform=None, module=__name__, **options) @@ -500,6 +502,150 @@ def exe_prog_cmd(flashtool_exe, mfd_addr): exe_gen_ota_image_cmd(flashtool_exe) exe_prog_cmd(flashtool_exe, mfd_addr) + def bouffalo_sdk_prog(self): + + def int_to_lhex(intvalue): + lhex = ((intvalue & 0xff000000) >> 24) | ((intvalue & 0xff0000) >> 8) + lhex |= ((intvalue & 0xff00) << 8) | ((intvalue & 0xff) << 24) + + return "%08x" % lhex + + def get_tools(): + bflb_tools = os.path.join(MATTER_ROOT, "third_party/bouffalolab/bouffalo_sdk/tools/bflb_tools") + bflb_tools_dict = { + "linux": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc-ubuntu", "flash_tool": "bouffalo_flash_cube/BLFlashCommand-ubuntu"}, + "win32": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc.exe", "flash_tool": "bouffalo_flash_cube/BLFlashCommand.exe"}, + "darwin": {"fw_proc": "bflb_fw_post_proc/bflb_fw_post_proc-macos", "flash_tool": "bouffalo_flash_cube/BLFlashCommand-macos"}, + } + + try: + fw_proc_exe = os.path.join(bflb_tools, bflb_tools_dict[sys.platform]["fw_proc"]) + flashtool_exe = os.path.join(bflb_tools, bflb_tools_dict[sys.platform]["flash_tool"]) + except Exception: + raise Exception("Do NOT support {} operating system to program firmware.".format(sys.platform)) + + if not os.path.exists(flashtool_exe) or not os.path.exists(fw_proc_exe): + logging.fatal('*' * 80) + logging.error("Expecting tools as below:") + logging.error(fw_proc_exe) + logging.error(flashtool_exe) + raise Exception("Flashtool or fw tool doesn't contain in SDK") + + return fw_proc_exe, flashtool_exe + + def prog_config(configDir, output, isErase=False): + + partition_file = self.find_file(configDir, r'^partition.+\.toml$') + if len(partition_file) != 1: + raise Exception("No partition file or one more partition file found.") + + partition_file = partition_file[0] + with open(partition_file, 'r') as file: + partition_config = toml.load(file) + + part_addr0 = partition_config["pt_table"]["address0"] + part_addr1 = partition_config["pt_table"]["address1"] + + config = configparser.ConfigParser() + + config.add_section('cfg') + config.set('cfg', 'erase', '2' if isErase else '1') + config.set('cfg', 'skip_mode', '0x0, 0x0') + config.set('cfg', 'boot2_isp_mode', '0') + + config.add_section('boot2') + config.set('boot2', 'filedir', os.path.join(self.work_dir, "boot2*.bin")) + config.set('boot2', 'address', '0x000000') + + config.add_section('partition') + config.set('partition', 'filedir', os.path.join(self.work_dir, "partition*.bin")) + config.set('partition', 'address', hex(part_addr0)) + + config.add_section('partition1') + config.set('partition1', 'filedir', os.path.join(self.work_dir, "partition*.bin")) + config.set('partition1', 'address', hex(part_addr1)) + + config.add_section('FW') + config.set('FW', 'filedir', self.args["firmware"]) + config.set('FW', 'address', '@partition') + + if self.args["mfd"]: + config.add_section("MFD") + config.set('MFD', 'filedir', self.args["mfd"]) + config.set('MFD', 'address', '@partition') + + with open(output, 'w') as configfile: + config.write(configfile) + + def exe_proc_cmd(fw_proc_exe): + + os.system("rm -rf {}/ota_images".format(self.work_dir)) + + fw_proc_cmd = [ + fw_proc_exe, + "--chipname", self.args["chipname"], + "--brdcfgdir", os.path.join(self.work_dir, "config"), + "--imgfile", self.args["firmware"], + ] + + if self.args["sk"]: + fw_proc_cmd += [ + "--privatekey", self.args["sk"], + ] + + if self.args["key"]: + lock0 = int_to_lhex((1 << 30) | (1 << 20)) + lock1 = int_to_lhex((1 << 25) | (1 << 15)) + fw_proc_cmd += [ + "--edata", "0x80,{};0x7c,{};0xfc,{}".format(self.args["key"], lock0, lock1) + ] + + logging.info("firmware process command: {}".format(" ".join(fw_proc_cmd))) + process = subprocess.Popen(fw_proc_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + while process.poll() is None: + line = process.stdout.readline().decode('utf-8').rstrip() + if line: + logging.info(line) + + os.system("mkdir -p {}/ota_images".format(self.work_dir)) + os.system("mv {}/*.ota {}/ota_images/".format(self.work_dir, self.work_dir)) + + def exe_prog_cmd(flashtool_exe): + prog_cmd = [ + flashtool_exe, + "--chipname", self.args["chipname"], + "--baudrate", str(self.args["baudrate"]), + "--config", self.args["config"] + ] + + if self.args["sk"] or (self.args["key"] and self.args["iv"]): + prog_cmd += [ + "--efuse", os.path.join(self.work_dir, "efusedata.bin") + ] + + if self.args["port"]: + prog_config(os.path.join(self.work_dir, "config"), os.path.join( + self.work_dir, "flash_prog_cfg.ini"), self.option.erase) + + prog_cmd += [ + "--port", self.args["port"], + ] + + logging.info("firwmare programming: {}".format(" ".join(prog_cmd))) + process = subprocess.Popen(prog_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + while process.poll() is None: + line = process.stdout.readline().decode('utf-8').rstrip() + if line: + logging.info(line) + + fw_proc_exe, flashtool_exe = get_tools() + os.chdir(self.work_dir) + + self.parse_mfd() + + exe_proc_cmd(fw_proc_exe) + exe_prog_cmd(flashtool_exe) + def gen_ota_image(self): sys.path.insert(0, os.path.join(MATTER_ROOT, 'src', 'app')) import ota_image_tool @@ -547,6 +693,13 @@ def actions(self): """Perform actions on the device according to self.option.""" self.log(3, 'Options:', self.option) + # is_for_ota_image_building = None + # is_for_programming = False + # has_private_key = False + # has_public_key = False + # ota_output_folder = None + # options_keys = BOUFFALO_OPTIONS["configuration"].keys() + if platform.machine() not in ["x86_64"]: raise Exception("Only support x86_64 CPU machine to program firmware.") @@ -573,9 +726,12 @@ def actions(self): if self.args["port"]: raise Exception("Do not generate OTA image with firmware programming.") - if self.args["mfd"] and self.args["mfd_str"]: - raise Exception("Cannot use option mfd and mfd-str together.") - self.iot_sdk_prog() + if self.args["chipname"] in self.bouffalo_sdk_chips: + self.bouffalo_sdk_prog() + else: + if self.args["mfd"] and self.args["mfd_str"]: + raise Exception("Cannot use option mfd and mfd-str together.") + self.iot_sdk_prog() if self.args["build_ota"]: self.gen_ota_image() diff --git a/src/lib/shell/BUILD.gn b/src/lib/shell/BUILD.gn index 8a9f6233a476f6..fed0dfa5b8bbcb 100644 --- a/src/lib/shell/BUILD.gn +++ b/src/lib/shell/BUILD.gn @@ -88,11 +88,14 @@ static_library("shell") { ] } else if (chip_device_platform == "bl602" || chip_device_platform == "bl702" || - chip_device_platform == "bl702l") { - sources += [ - "MainLoopDefault.cpp", - "streamer_bouffalolab.cpp", - ] + chip_device_platform == "bl702l" || + chip_device_platform == "bl616") { + sources += [ "streamer_bouffalolab.cpp" ] + if (chip_device_platform == "bl616") { + sources += [ "MainLoopBouffalolab.cpp" ] + } else { + sources += [ "MainLoopDefault.cpp" ] + } } else if (chip_device_platform == "cc13x4_26x4") { sources += [ "MainLoopDefault.cpp", diff --git a/src/lib/shell/MainLoopBouffalolab.cpp b/src/lib/shell/MainLoopBouffalolab.cpp new file mode 100644 index 00000000000000..098f3809cc8c0c --- /dev/null +++ b/src/lib/shell/MainLoopBouffalolab.cpp @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +extern "C" { +#include +} + +using chip::Shell::Engine; + +void cmd_matter(size_t argc, char ** argv) +{ + Engine::Root().ExecCommand(argc - 1, argv + 1); +} + +SHELL_CMD_EXPORT_ALIAS(cmd_matter, matter, matter command); + +namespace chip { +namespace Shell { + +void Engine::RunMainLoop() +{ + // Intentionally empty as Zephyr has own thread handling shell +} + +} // namespace Shell +} // namespace chip diff --git a/src/lib/shell/streamer_bouffalolab.cpp b/src/lib/shell/streamer_bouffalolab.cpp index 9a7b669ae47088..d7e168ead571eb 100644 --- a/src/lib/shell/streamer_bouffalolab.cpp +++ b/src/lib/shell/streamer_bouffalolab.cpp @@ -1,66 +1,106 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * Source implementation of an input / output stream for Bouffalo Lab targets. - */ - -#include -#include -#include - -#include -#include -#include - -namespace chip { -namespace Shell { -namespace { - -int streamer_iot_sdk_init(streamer_t * streamer) -{ - (void) streamer; - return 0; -} - -ssize_t streamer_iot_sdk_read(streamer_t * streamer, char * buffer, size_t length) -{ - (void) streamer; - return (ssize_t) uartRead(buffer, (uint16_t) length); -} - -ssize_t streamer_iot_sdk_write(streamer_t * streamer, const char * buffer, size_t length) -{ - (void) streamer; - return uartWrite(buffer, (uint16_t) length); -} - -static streamer_t streamer_iot_sdk = { - .init_cb = streamer_iot_sdk_init, - .read_cb = streamer_iot_sdk_read, - .write_cb = streamer_iot_sdk_write, -}; - -} // namespace -streamer_t * streamer_get(void) -{ - return &streamer_iot_sdk; -} - -} // namespace Shell -} // namespace chip +/* + * + * Copyright (c) 2020 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * Source implementation of an input / output stream for Bouffalo Lab targets. + */ + +#include +#include +#include + +#if !CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#include +#include +#endif + +namespace chip { +namespace Shell { + +#if CHIP_DEVICE_LAYER_TARGET_BL616 +namespace { +int streamer_bouffalo_sdk_init(streamer_t * streamer) +{ + (void) streamer; + return 0; +} + +ssize_t streamer_bouffalo_sdk_read(streamer_t * streamer, char * buffer, size_t length) +{ + (void) (streamer); + return 0; +} + +ssize_t streamer_bouffalo_sdk_write(streamer_t * streamer, const char * buffer, size_t length) +{ + (void) (streamer); + + printf("%s", buffer); + return 0; +} + +static streamer_t streamer_bouffalo_sdk = { + .init_cb = streamer_bouffalo_sdk_init, + .read_cb = streamer_bouffalo_sdk_read, + .write_cb = streamer_bouffalo_sdk_write, +}; +} // namespace + +streamer_t * streamer_get(void) +{ + return &streamer_bouffalo_sdk; +} + +#else + +namespace { + +int streamer_iot_sdk_init(streamer_t * streamer) +{ + (void) streamer; + return 0; +} + +ssize_t streamer_iot_sdk_read(streamer_t * streamer, char * buffer, size_t length) +{ + (void) streamer; + return (ssize_t) uartRead(buffer, (uint16_t) length); +} + +ssize_t streamer_iot_sdk_write(streamer_t * streamer, const char * buffer, size_t length) +{ + (void) streamer; + return uartWrite(buffer, (uint16_t) length); +} + +static streamer_t streamer_iot_sdk = { + .init_cb = streamer_iot_sdk_init, + .read_cb = streamer_iot_sdk_read, + .write_cb = streamer_iot_sdk_write, +}; + +} // namespace +streamer_t * streamer_get(void) +{ + return &streamer_iot_sdk; +} +#endif + +} // namespace Shell +} // namespace chip diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index 78657a635a4268..0bffafeb5afc5a 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -32,9 +32,10 @@ assert(lwip_platform == "external" || lwip_platform == "standalone" || lwip_platform == "nxp" || lwip_platform == "silabs" || lwip_platform == "qpg" || lwip_platform == "mbed" || lwip_platform == "psoc6" || lwip_platform == "cyw30739" || - lwip_platform == "bl602" || lwip_platform == "mw320" || - lwip_platform == "bl702" || lwip_platform == "bl702l" || - lwip_platform == "mt793x" || lwip_platform == "asr", + lwip_platform == "mw320" || lwip_platform == "bl602" || + lwip_platform == "bl616" || lwip_platform == "bl702" || + lwip_platform == "bl702l" || lwip_platform == "mt793x" || + lwip_platform == "asr", "Unsupported lwIP platform: ${lwip_platform}") if (lwip_platform != "external") { @@ -59,6 +60,9 @@ if (lwip_platform == "cc13xx_26xx") { import("//build_overrides/cyw30739_sdk.gni") } else if (lwip_platform == "bl602") { import("//build_overrides/bouffalolab_iot_sdk.gni") +} else if (lwip_platform == "bl616") { + import("//build_overrides/bouffalolab_iot_sdk.gni") + import("${chip_root}/src/platform/device.gni") } else if (lwip_platform == "bl702") { import("//build_overrides/bouffalolab_iot_sdk.gni") import("${chip_root}/src/platform/device.gni") @@ -149,6 +153,16 @@ if (current_os == "zephyr" || current_os == "mbed") { public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl602:bl_iot_sdk" ] } + group("all") { + deps = [ ":lwip" ] + } +} else if (lwip_platform == "bl616" && defined(chip_enable_openthread) && + chip_enable_openthread == false) { + group("lwip") { + public_deps = [ ":lwip_buildconfig" ] + public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + } + group("all") { deps = [ ":lwip" ] } diff --git a/src/platform/BUILD.gn b/src/platform/BUILD.gn index 7f0b7ff87a1b16..bc7f10f430e661 100644 --- a/src/platform/BUILD.gn +++ b/src/platform/BUILD.gn @@ -148,7 +148,8 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { if (chip_device_platform == "linux" || chip_device_platform == "darwin" || chip_device_platform == "tizen" || chip_device_platform == "android" || chip_device_platform == "webos" || chip_device_platform == "bl602" || - chip_device_platform == "bl702" || chip_device_platform == "bl702l") { + chip_device_platform == "bl702" || chip_device_platform == "bl702l" || + chip_device_platform == "bl616") { defines += [ "CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE=${chip_enable_ble}" ] } @@ -249,6 +250,12 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", ] + } else if (chip_device_platform == "bl616") { + device_layer_target_define = "BL616" + defines += [ + "CHIP_DEVICE_LAYER_TARGET=bouffalolab/common", + "CHIP_DEVICE_CONFIG_ENABLE_WIFI=${chip_enable_wifi}", + ] } else if (chip_device_platform == "bl702") { device_layer_target_define = "BL702" defines += [ @@ -346,6 +353,7 @@ if (chip_device_platform != "none" && chip_device_platform != "external") { "TELINK", "MBED", "BL602", + "BL616", "BL702", "BL702L", "FAKE", @@ -576,6 +584,8 @@ if (chip_device_platform != "none") { _platform_target = "webos" } else if (chip_device_platform == "bl602") { _platform_target = "bouffalolab/BL602" + } else if (chip_device_platform == "bl616") { + _platform_target = "bouffalolab/BL616" } else if (chip_device_platform == "bl702") { _platform_target = "bouffalolab/BL702" } else if (chip_device_platform == "bl702l") { diff --git a/src/platform/bouffalolab/BL602/BUILD.gn b/src/platform/bouffalolab/BL602/BUILD.gn index d4cd04c739c6cd..7e4877490de172 100644 --- a/src/platform/bouffalolab/BL602/BUILD.gn +++ b/src/platform/bouffalolab/BL602/BUILD.gn @@ -39,6 +39,7 @@ static_library("BL602") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -73,5 +74,6 @@ static_library("BL602") { "${chip_root}/src/lib/dnssd:platform_header", "${chip_root}/src/platform/logging:headers", ] + public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp index 4d8bd35af57380..87136268afd0d2 100644 --- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp +++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp @@ -15,7 +15,7 @@ * limitations under the License. */ #include -#include +#include #include #include @@ -405,6 +405,10 @@ void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg) case kWiFiOnScanDone: BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(); break; + case kWiFiOnConnecting: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; case kWiFiOnConnected: BLWiFiDriver::GetInstance().OnNetworkStatusChange(); break; @@ -447,6 +451,10 @@ extern "C" void wifi_event_handler(uint32_t code) event.Type = kWiFiOnScanDone; PlatformMgr().PostEventOrDie(&event); break; + case CODE_WIFI_ON_CONNECTING: + event.Type = kWiFiOnConnecting; + PlatformMgr().PostEventOrDie(&event); + break; case CODE_WIFI_ON_CONNECTED: event.Type = kWiFiOnConnected; PlatformMgr().PostEventOrDie(&event); diff --git a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp index 3c7b35941128c7..ade4d468dff8a3 100644 --- a/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL602/PlatformManagerImpl.cpp @@ -46,8 +46,6 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) // Initialize LwIP. tcpip_init(NULL, NULL); - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); SuccessOrExit(err); diff --git a/src/platform/bouffalolab/BL616/BUILD.gn b/src/platform/bouffalolab/BL616/BUILD.gn new file mode 100644 index 00000000000000..f77216b48b68f8 --- /dev/null +++ b/src/platform/bouffalolab/BL616/BUILD.gn @@ -0,0 +1,107 @@ +# Copyright (c) 2022 Project CHIP Authors +# All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/chip.gni") + +import("${chip_root}/src/platform/device.gni") + +import("${chip_root}/src/platform/bouffalolab/common/args.gni") + +assert(chip_device_platform == "bl616") + +if (chip_enable_openthread) { + import("//build_overrides/openthread.gni") +} + +static_library("BL616") { + sources = [ + "DiagnosticDataProviderImpl.cpp", + "PlatformManagerImpl.cpp", + ] + + sources += [ + "../../FreeRTOS/SystemTimeSupport.cpp", + "../../SingletonConfigurationManager.cpp", + "../common/ConfigurationManagerImpl.cpp", + "../common/ConnectivityManagerImpl.cpp", + "../common/DiagnosticDataProviderImpl.cpp", + "../common/KeyValueStoreManagerImpl.cpp", + "../common/PlatformManagerImpl.cpp", + ] + + if (chip_enable_ota_requestor) { + sources += [ "../common/OTAImageProcessorImpl_bflb.cpp" ] + } + + if (chip_enable_ble) { + sources += [ + "../common/BLEManagerImpl.cpp", + "../common/BLEManagerImpl.h", + ] + } + + if (chip_enable_factory_data) { + sources += [ + "../common/FactoryDataProvider.cpp", + "../common/FactoryDataProvider.h", + ] + } + + if (bouffalo_sdk_component_easyflash_enabled) { + sources += [ "../common/BLConfig.cpp" ] + } else { + sources += [ "../common/BLConfig_littlefs.cpp" ] + } + + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + + if (chip_enable_wifi) { + sources += [ + "ConfigurationManagerImpl.cpp", + "ConnectivityManagerImpl.cpp", + "NetworkCommissioningDriver.cpp", + "wifi_mgmr_portable.c", + ] + + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + + if (chip_enable_openthread) { + # needed for MTD/FTD + + import("//build_overrides/bouffalolab_iot_sdk.gni") + import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + deps += [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + + sources += [ + "../../OpenThread/OpenThreadUtils.cpp", + "ThreadStackManagerImpl.cpp", + ] + + if (chip_mdns == "platform") { + sources += [ + "../../OpenThread/DnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.cpp", + "../../OpenThread/OpenThreadDnssdImpl.h", + ] + deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] + } + } + + public_deps = [ "${chip_root}/src/platform:platform_base" ] +} diff --git a/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp b/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp new file mode 100644 index 00000000000000..0e04b79a1cbfe6 --- /dev/null +++ b/src/platform/bouffalolab/BL616/CHIPMem-Platform.cpp @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2019 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * + * Copyright (c) 2020-2021 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file implements heap memory allocation APIs for CHIP. These functions are platform + * specific and might be C Standard Library heap functions re-direction in most of cases. + * + */ + +#include + +#include + +#if CHIP_CONFIG_MEMORY_MGMT_PLATFORM +namespace chip { +namespace Platform { + +CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize) +{ + return CHIP_NO_ERROR; +} + +void MemoryAllocatorShutdown() {} + +void * MemoryAlloc(size_t size) +{ + return kmalloc(size); +} + +void * MemoryCalloc(size_t num, size_t size) +{ + return kcalloc(size, num); +} + +void * MemoryRealloc(void * p, size_t size) +{ + return realloc(p, size); +} + +void MemoryFree(void * p) +{ + kfree(p); +} + +bool MemoryInternalCheckPointer(const void * p, size_t min_size) +{ + return (p != nullptr); +} + +} // namespace Platform +} // namespace chip + +#endif // CHIP_CONFIG_MEMORY_MGMT_PLATFORM diff --git a/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp new file mode 100644 index 00000000000000..f0b65b34bd896b --- /dev/null +++ b/src/platform/bouffalolab/BL616/ConfigurationManagerImpl.cpp @@ -0,0 +1,46 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include + +#include +#include + +#include +#include + +extern "C" { +#include +} + +namespace chip { +namespace DeviceLayer { + +CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf) +{ + bflb_efuse_read_mac_address_opt(0, buf, 1); + + return CHIP_NO_ERROR; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp new file mode 100644 index 00000000000000..77dfca05ca66e4 --- /dev/null +++ b/src/platform/bouffalolab/BL616/ConnectivityManagerImpl.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include + +#include +#include + +#include + +using namespace ::chip; + +namespace chip { +namespace DeviceLayer { + +void ConnectivityManagerImpl::OnWiFiStationDisconnected() +{ + NetworkCommissioning::BLWiFiDriver::GetInstance().SetLastDisconnectReason(NULL); + uint16_t reason = NetworkCommissioning::BLWiFiDriver::GetInstance().GetLastDisconnectReason(); + uint8_t associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kUnknown); + WiFiDiagnosticsDelegate * delegate = GetDiagnosticDataProvider().GetWiFiDiagnosticsDelegate(); + + ChipLogError(DeviceLayer, "WiFi station disconnect, reason %d.", reason); + + switch (reason) + { + case WLAN_FW_TX_ASSOC_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_ASSOCIATE_FAIILURE: + case WLAN_FW_4WAY_HANDSHAKE_ERROR_PSK_TIMEOUT_FAILURE: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kAssociationFailed); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_TX_AUTH_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_AUTHENTICATION_FAIILURE: + case WLAN_FW_AUTH_ALGO_FAIILURE: + case WLAN_FW_DEAUTH_BY_AP_WHEN_NOT_CONNECTION: + case WLAN_FW_DEAUTH_BY_AP_WHEN_CONNECTION: + case WLAN_FW_4WAY_HANDSHAKE_TX_DEAUTH_FRAME_TRANSMIT_FAILURE: + case WLAN_FW_4WAY_HANDSHAKE_TX_DEAUTH_FRAME_ALLOCATE_FAIILURE: + case WLAN_FW_AUTH_OR_ASSOC_RESPONSE_TIMEOUT_FAILURE: + case WLAN_FW_DISCONNECT_BY_USER_WITH_DEAUTH: + case WLAN_FW_DISCONNECT_BY_USER_NO_DEAUTH: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kAuthenticationFailed); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_SCAN_NO_BSSID_AND_CHANNEL: + associationFailureCause = + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::AssociationFailureCauseEnum::kSsidNotFound); + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + case WLAN_FW_BEACON_LOSS: + case WLAN_FW_DISCONNECT_BY_FW_PS_TX_NULLFRAME_FAILURE: + case WLAN_FW_CREATE_CHANNEL_CTX_FAILURE_WHEN_JOIN_NETWORK: + case WLAN_FW_ADD_STA_FAILURE: + case WLAN_FW_JOIN_NETWORK_FAILURE: + break; + + default: + if (delegate) + { + delegate->OnAssociationFailureDetected(associationFailureCause, reason); + } + break; + } + + if (delegate) + { + delegate->OnDisconnectionDetected(reason); + delegate->OnConnectionStatusChanged( + chip::to_underlying(chip::app::Clusters::WiFiNetworkDiagnostics::ConnectionStatusEnum::kNotConnected)); + } +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp new file mode 100644 index 00000000000000..f62ae3762183ab --- /dev/null +++ b/src/platform/bouffalolab/BL616/DiagnosticDataProviderImpl.cpp @@ -0,0 +1,139 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include + +extern "C" { +#include +} +#include +#endif + +namespace chip { +namespace DeviceLayer { + +CHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason) +{ + bootReason = BootReasonType::kUnspecified; + return CHIP_NO_ERROR; +} + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(MutableByteSpan & BssId) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (ConnectivityMgrImpl()._IsWiFiStationConnected() && 0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + return CopySpanToMutableSpan(ByteSpan(statInfo.bssid), BssId); + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(app::Clusters::WiFiNetworkDiagnostics::SecurityTypeEnum & securityType) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(app::Clusters::WiFiNetworkDiagnostics::WiFiVersionEnum & wifiVersion) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (ConnectivityMgrImpl()._IsWiFiStationConnected() && 0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + channelNumber = statInfo.channel; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) +{ + int tmp_rssi; + if (ConnectivityMgrImpl()._IsWiFiStationConnected()) + { + wifi_mgmr_sta_rssi_get(&tmp_rssi); + rssi = (int8_t) tmp_rssi; + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_READ_FAILED; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts() +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxCount) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} +#endif + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp new file mode 100644 index 00000000000000..dc5c22dcd0f1b0 --- /dev/null +++ b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.cpp @@ -0,0 +1,463 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include +#include +#include +#include +extern "C" { +#include +} +#include + +using namespace ::chip; +using namespace ::chip::DeviceLayer::Internal; +using namespace ::chip::Platform; + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +CHIP_ERROR BLWiFiDriver::Init(NetworkStatusChangeCallback * networkStatusChangeCallback) +{ + CHIP_ERROR err; + size_t ssidLen = 0; + size_t credentialsLen = 0; + + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiPassword, mSavedNetwork.credentials, + sizeof(mSavedNetwork.credentials), &credentialsLen); + SuccessOrExit(err); + err = PersistedStorage::KeyValueStoreMgr().Get(BLConfig::kConfigKey_WiFiSSID, mSavedNetwork.ssid, sizeof(mSavedNetwork.ssid), + &ssidLen); + SuccessOrExit(err); + mSavedNetwork.credentialsLen = credentialsLen; + mSavedNetwork.ssidLen = ssidLen; + + mStagingNetwork = mSavedNetwork; + mpScanCallback = nullptr; + mpConnectCallback = nullptr; + mpStatusChangeCallback = networkStatusChangeCallback; + +exit: + if (err == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND) + { + /** Not commissioned, SSID and Network Password not found. */ + return CHIP_NO_ERROR; + } + + return err; +} + +void BLWiFiDriver::Shutdown() +{ + mpStatusChangeCallback = nullptr; +} + +CHIP_ERROR BLWiFiDriver::CommitConfiguration() +{ + ChipLogProgress(NetworkProvisioning, "BLWiFiDriver::CommitConfiguration"); + ReturnErrorOnFailure( + PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiSSID, mStagingNetwork.ssid, mStagingNetwork.ssidLen)); + ReturnErrorOnFailure(PersistedStorage::KeyValueStoreMgr().Put(BLConfig::kConfigKey_WiFiPassword, mStagingNetwork.credentials, + mStagingNetwork.credentialsLen)); + mSavedNetwork = mStagingNetwork; + return CHIP_NO_ERROR; +} + +CHIP_ERROR BLWiFiDriver::RevertConfiguration() +{ + mStagingNetwork = mSavedNetwork; + return CHIP_NO_ERROR; +} + +bool BLWiFiDriver::NetworkMatch(const WiFiNetwork & network, ByteSpan networkId) +{ + return networkId.size() == network.ssidLen && memcmp(networkId.data(), network.ssid, network.ssidLen) == 0; +} + +Status BLWiFiDriver::AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(mStagingNetwork.ssidLen == 0 || NetworkMatch(mStagingNetwork, ssid), Status::kBoundsExceeded); + VerifyOrReturnError(credentials.size() <= sizeof(mStagingNetwork.credentials), Status::kOutOfRange); + VerifyOrReturnError(ssid.size() <= sizeof(mStagingNetwork.ssid), Status::kOutOfRange); + + memcpy(mStagingNetwork.credentials, credentials.data(), credentials.size()); + mStagingNetwork.credentialsLen = static_cast(credentials.size()); + + memcpy(mStagingNetwork.ssid, ssid.data(), ssid.size()); + mStagingNetwork.ssidLen = static_cast(ssid.size()); + + return Status::kSuccess; +} + +Status BLWiFiDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) +{ + outDebugText.reduce_size(0); + outNetworkIndex = 0; + + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + + // Use empty ssid for representing invalid network + mStagingNetwork.ssidLen = 0; + return Status::kSuccess; +} + +Status BLWiFiDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) +{ + outDebugText.reduce_size(0); + + // Only one network is supported now + VerifyOrReturnError(index == 0, Status::kOutOfRange); + VerifyOrReturnError(NetworkMatch(mStagingNetwork, networkId), Status::kNetworkIDNotFound); + return Status::kSuccess; +} + +CHIP_ERROR BLWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen) +{ + wifi_mgmr_sta_connect_params_t conn_param = { 0 }; + + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + + strncpy((char *) conn_param.ssid, ssid, ssidLen); + conn_param.ssid_len = ssidLen; + + if (keyLen) + { + strncpy((char *) conn_param.key, key, keyLen); + conn_param.key_len = keyLen; + } + conn_param.freq1 = 0; + conn_param.freq2 = 0; + conn_param.use_dhcp = 1; + conn_param.pmf_cfg = 1; + conn_param.quick_connect = 1; + conn_param.timeout_ms = -1; + + wifi_mgmr_sta_connect(&conn_param); + + return CHIP_NO_ERROR; +} + +void BLWiFiDriver::OnConnectWiFiNetwork(bool isConnected) +{ + if (mpConnectCallback) + { + if (isConnected) + { + mpConnectCallback->OnResult(Status::kSuccess, CharSpan(), 0); + } + else + { + mpConnectCallback->OnResult(Status::kUnknownError, CharSpan(), 0); + } + mpConnectCallback = nullptr; + } +} + +void BLWiFiDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + Status networkingStatus = Status::kSuccess; + + VerifyOrExit(NetworkMatch(mStagingNetwork, networkId), networkingStatus = Status::kNetworkIDNotFound); + VerifyOrExit(mpConnectCallback == nullptr, networkingStatus = Status::kUnknownError); + ChipLogProgress(NetworkProvisioning, "BL NetworkCommissioningDelegate: SSID: %.*s", static_cast(networkId.size()), + networkId.data()); + + err = ConnectWiFiNetwork(reinterpret_cast(mStagingNetwork.ssid), mStagingNetwork.ssidLen, + reinterpret_cast(mStagingNetwork.credentials), mStagingNetwork.credentialsLen); + mpConnectCallback = callback; + +exit: + if (err != CHIP_NO_ERROR) + { + networkingStatus = Status::kUnknownError; + } + if (networkingStatus != Status::kSuccess) + { + ChipLogError(NetworkProvisioning, "Failed to connect to WiFi network:%s", chip::ErrorStr(err)); + mpConnectCallback = nullptr; + callback->OnResult(networkingStatus, CharSpan(), 0); + } +} + +void BLWiFiDriver::ScanNetworks(ByteSpan ssid, WiFiDriver::ScanCallback * callback) +{ + if (callback != nullptr) + { + mpScanCallback = nullptr; + if (0 == wifi_start_scan(ssid.data(), ssid.size())) + { + mpScanCallback = callback; + } + else + { + callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); + } + } +} + +void BLWiFiDriver::OnScanWiFiNetworkDone() +{ + uint32_t nums = wifi_mgmr_sta_scanlist_nums_get(); + if (nums) + { + wifi_mgmr_scan_item_t * pScanList = (wifi_mgmr_scan_item_t *) MemoryAlloc(nums * sizeof(wifi_mgmr_scan_item_t)); + + if (NULL == pScanList || 0 == wifi_mgmr_sta_scanlist_dump(pScanList, nums)) + { + mpScanCallback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); + mpScanCallback = nullptr; + } + else + { + + if (CHIP_NO_ERROR == DeviceLayer::SystemLayer().ScheduleLambda([nums, pScanList]() { + BLScanResponseIterator iter(nums, pScanList); + if (GetInstance().mpScanCallback) + { + GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter); + GetInstance().mpScanCallback = nullptr; + } + else + { + ChipLogError(DeviceLayer, "can't find the ScanCallback function"); + } + })) + { + MemoryFree(pScanList); + } + } + } + else + { + ChipLogProgress(DeviceLayer, "No AP found"); + if (mpScanCallback != nullptr) + { + mpScanCallback->OnFinished(Status::kNetworkNotFound, CharSpan(), nullptr); + mpScanCallback = nullptr; + } + } +} + +CHIP_ERROR GetConfiguredNetwork(Network & network) +{ + wifi_mgmr_connect_ind_stat_info_t statInfo; + + memset(&statInfo, 0, sizeof(wifi_mgmr_connect_ind_stat_info_t)); + if (0 == wifi_mgmr_sta_connect_ind_stat_get(&statInfo)) + { + memcpy(network.networkID, statInfo.ssid, strlen(statInfo.ssid)); + network.networkIDLen = strlen(statInfo.ssid); + return CHIP_NO_ERROR; + } + + return CHIP_ERROR_INTERNAL; +} + +void BLWiFiDriver::OnNetworkStatusChange() +{ + Network configuredNetwork; + + VerifyOrReturn(mpStatusChangeCallback != nullptr); + if (GetConfiguredNetwork(configuredNetwork) != CHIP_NO_ERROR) + { + return; + } + + if (ConnectivityManagerImpl().GetWiFiStationState() == ConnectivityManager::kWiFiStationState_Connected) + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kSuccess, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), NullOptional); + } + else + { + mpStatusChangeCallback->OnNetworkingStatusChange( + Status::kUnknownError, MakeOptional(ByteSpan(configuredNetwork.networkID, configuredNetwork.networkIDLen)), + MakeOptional(GetLastDisconnectReason())); + } +} + +CHIP_ERROR BLWiFiDriver::SetLastDisconnectReason(const ChipDeviceEvent * event) +{ + mLastDisconnectedReason = wifi_mgmr_sta_info_status_code_get(); + + return CHIP_NO_ERROR; +} + +int32_t BLWiFiDriver::GetLastDisconnectReason() +{ + return mLastDisconnectedReason; +} + +size_t BLWiFiDriver::WiFiNetworkIterator::Count() +{ + return mDriver->mStagingNetwork.ssidLen == 0 ? 0 : 1; +} + +bool BLWiFiDriver::WiFiNetworkIterator::Next(Network & item) +{ + if (mExhausted || mDriver->mStagingNetwork.ssidLen == 0) + { + return false; + } + memcpy(item.networkID, mDriver->mStagingNetwork.ssid, mDriver->mStagingNetwork.ssidLen); + item.networkIDLen = mDriver->mStagingNetwork.ssidLen; + item.connected = false; + mExhausted = true; + + Network connectedNetwork; + CHIP_ERROR err = GetConfiguredNetwork(connectedNetwork); + if (err == CHIP_NO_ERROR) + { + if (connectedNetwork.networkIDLen == item.networkIDLen && + memcmp(connectedNetwork.networkID, item.networkID, item.networkIDLen) == 0) + { + item.connected = true; + } + } + return true; +} + +void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg) +{ + if (!(DeviceEventType::IsPlatformSpecific(event->Type) && DeviceEventType::IsPublic(event->Type))) + { + return; + } + + switch (event->Type) + { + case kWiFiOnInitDone: + break; + case kWiFiOnScanDone: + BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(); + break; + case kWiFiOnConnecting: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kWiFiOnConnected: + BLWiFiDriver::GetInstance().OnNetworkStatusChange(); + break; + case kGotIpAddress: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManagerImpl::kWiFiStationState_Connected); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kGotIpv6Address: + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManagerImpl::kWiFiStationState_Connected); + ConnectivityMgrImpl().OnConnectivityChanged(deviceInterface_getNetif()); + break; + case kWiFiOnDisconnected: + if (ConnectivityManager::kWiFiStationState_Connecting == ConnectivityMgrImpl().GetWiFiStationState()) + { + ConnectivityMgrImpl().ChangeWiFiStationState(ConnectivityManager::kWiFiStationState_Connecting_Failed); + } + break; + default: + ChipLogProgress(DeviceLayer, "Undefined network commission event type %x.\r\n", event->Type); + break; + } +} + +static wifi_conf_t conf = { + .country_code = "CN", +}; + +extern "C" void wifi_event_handler(uint32_t code) +{ + ChipDeviceEvent event; + + memset(&event, 0, sizeof(ChipDeviceEvent)); + + switch (code) + { + case CODE_WIFI_ON_INIT_DONE: + wifi_mgmr_init(&conf); + break; + case CODE_WIFI_ON_MGMR_DONE: + wifi_mgmr_sta_autoconnect_enable(); + break; + case CODE_WIFI_ON_SCAN_DONE: + event.Type = kWiFiOnScanDone; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_CONNECTING: + event.Type = kWiFiOnConnecting; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_CONNECTED: + event.Type = kWiFiOnConnected; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_GOT_IP: + event.Type = kGotIpAddress; + PlatformMgr().PostEventOrDie(&event); + break; + case CODE_WIFI_ON_DISCONNECT: + event.Type = kWiFiOnDisconnected; + PlatformMgr().PostEventOrDie(&event); + break; + default: { + ChipLogProgress(DeviceLayer, "[APP] [EVT] Unknown code %lu \r\n", code); + } + } +} + +extern "C" void network_netif_ext_callback(struct netif * nif, netif_nsc_reason_t reason, const netif_ext_callback_args_t * args) +{ + ChipDeviceEvent event; + + memset(&event, 0, sizeof(ChipDeviceEvent)); + + if (((LWIP_NSC_IPV6_ADDR_STATE_CHANGED | LWIP_NSC_IPV6_SET) & reason) && args) + { + + if (args->ipv6_addr_state_changed.addr_index >= LWIP_IPV6_NUM_ADDRESSES || + ip6_addr_islinklocal(netif_ip6_addr(nif, args->ipv6_addr_state_changed.addr_index))) + { + return; + } + + if (netif_ip6_addr_state(nif, args->ipv6_addr_state_changed.addr_index) != args->ipv6_addr_state_changed.old_state && + ip6_addr_ispreferred(netif_ip6_addr_state(nif, args->ipv6_addr_state_changed.addr_index))) + { + event.Type = kGotIpv6Address; + PlatformMgr().PostEventOrDie(&event); + } + } + + if ((LWIP_NSC_IPV4_SETTINGS_CHANGED & reason) && args) + { + if (!ip4_addr_isany(netif_ip4_addr(nif)) && !ip4_addr_isany(netif_ip4_gw(nif))) + { + event.Type = kGotIpAddress; + PlatformMgr().PostEventOrDie(&event); + } + } +} + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip +// #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h new file mode 100644 index 00000000000000..5a8cc7a1096d03 --- /dev/null +++ b/src/platform/bouffalolab/BL616/NetworkCommissioningDriver.h @@ -0,0 +1,150 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + +#pragma once +extern "C" { +#include +} +#include + +namespace chip { +namespace DeviceLayer { +namespace NetworkCommissioning { + +void NetworkEventHandler(const ChipDeviceEvent * event, intptr_t arg); + +namespace { +constexpr uint8_t kMaxWiFiNetworks = 1; +constexpr uint8_t kWiFiScanNetworksTimeOutSeconds = 10; +constexpr uint8_t kWiFiConnectNetworkTimeoutSeconds = 20; +} // namespace + +class BLScanResponseIterator : public Iterator +{ +public: + BLScanResponseIterator(const size_t size, const wifi_mgmr_scan_item_t * scanResults) : mSize(size), mpScanResults(scanResults) + {} + size_t Count() override { return mSize; } + bool Next(WiFiScanResponse & item) override + { + if (mIternum >= mSize) + { + return false; + } + + item.security.SetRaw(mpScanResults[mIternum].auth); + item.ssidLen = (uint32_t) (mpScanResults[mIternum].ssid_len) < chip::DeviceLayer::Internal::kMaxWiFiSSIDLength + ? mpScanResults[mIternum].ssid_len + : chip::DeviceLayer::Internal::kMaxWiFiSSIDLength; + item.channel = mpScanResults[mIternum].channel; + item.wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4; + item.rssi = mpScanResults[mIternum].rssi; + memcpy(item.ssid, mpScanResults[mIternum].ssid, item.ssidLen); + memcpy(item.bssid, mpScanResults[mIternum].bssid, 6); + + mIternum++; + return true; + } + void Release() override {} + +private: + const size_t mSize; + const wifi_mgmr_scan_item_t * mpScanResults; + size_t mIternum = 0; +}; + +class BLWiFiDriver final : public WiFiDriver +{ +public: + class WiFiNetworkIterator final : public NetworkIterator + { + public: + WiFiNetworkIterator(BLWiFiDriver * aDriver) : mDriver(aDriver) {} + size_t Count() override; + bool Next(Network & item) override; + void Release() override { delete this; } + ~WiFiNetworkIterator() = default; + + private: + BLWiFiDriver * mDriver; + bool mExhausted = false; + }; + + struct WiFiNetwork + { + char ssid[DeviceLayer::Internal::kMaxWiFiSSIDLength]; + uint8_t ssidLen = 0; + char credentials[DeviceLayer::Internal::kMaxWiFiKeyLength]; + uint8_t credentialsLen = 0; + }; + + // BaseDriver + NetworkIterator * GetNetworks() override { return new WiFiNetworkIterator(this); } + CHIP_ERROR Init(NetworkStatusChangeCallback * networkStatusChangeCallback) override; + void Shutdown(); + + // WirelessDriver + uint8_t GetMaxNetworks() override { return kMaxWiFiNetworks; } + uint8_t GetScanNetworkTimeoutSeconds() override { return kWiFiScanNetworksTimeOutSeconds; } + uint8_t GetConnectNetworkTimeoutSeconds() override { return kWiFiConnectNetworkTimeoutSeconds; } + + CHIP_ERROR CommitConfiguration() override; + CHIP_ERROR SaveConfiguration(); + CHIP_ERROR RevertConfiguration() override; + + Status RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) override; + Status ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) override; + void ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) override; + + // WiFiDriver + Status AddOrUpdateNetwork(ByteSpan ssid, ByteSpan credentials, MutableCharSpan & outDebugText, + uint8_t & outNetworkIndex) override; + void ScanNetworks(ByteSpan ssid, ScanCallback * callback) override; + + CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen); + CHIP_ERROR ReConnectWiFiNetwork(void); + void OnConnectWiFiNetwork(bool isConnected); + void OnScanWiFiNetworkDone(); + void OnNetworkStatusChange(); + + CHIP_ERROR SetLastDisconnectReason(const ChipDeviceEvent * event); + int32_t GetLastDisconnectReason(); + + static BLWiFiDriver & GetInstance() + { + static BLWiFiDriver instance; + return instance; + } + +private: + bool NetworkMatch(const WiFiNetwork & network, ByteSpan networkId); + + WiFiNetwork mSavedNetwork; + WiFiNetwork mStagingNetwork; + ScanCallback * mpScanCallback; + ConnectCallback * mpConnectCallback; + NetworkStatusChangeCallback * mpStatusChangeCallback = nullptr; + int32_t mLastDisconnectedReason; +}; + +} // namespace NetworkCommissioning +} // namespace DeviceLayer +} // namespace chip + +#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI diff --git a/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp new file mode 100644 index 00000000000000..4ed9920cfd843d --- /dev/null +++ b/src/platform/bouffalolab/BL616/PlatformManagerImpl.cpp @@ -0,0 +1,108 @@ +/* + * + * Copyright (c) 2021 Project CHIP Authors + * Copyright (c) 2019 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#if CHIP_SYSTEM_CONFIG_USE_LWIP +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI +#include +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#include +#include +#endif + +#include +#include +extern "C" { +#include +#include +} + +namespace chip { +namespace DeviceLayer { + +static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen) +{ + bflb_trng_readlen(reinterpret_cast(output), static_cast(len)); + *olen = len; + return 0; +} + +CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + TaskHandle_t backup_eventLoopTask; + int iret_rfInit = -1; + + pt_table_set_flash_operation(bflb_flash_erase, bflb_flash_write, bflb_flash_read); + + VerifyOrDieWithMsg(0 == (iret_rfInit = rfparam_init(0, NULL, 0)), DeviceLayer, "rfparam_init failed with %d", iret_rfInit); + +#if CHIP_SYSTEM_CONFIG_USE_LWIP + tcpip_init(NULL, NULL); +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_WIFI + wifi_start_firmware_task(); +#endif + +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD + otRadio_opt_t opt; +#if CHIP_DEVICE_CONFIG_THREAD_FTD + opt.bf.isFtd = true; +#else + opt.bf.isFtd = false; +#endif + opt.bf.isCoexEnable = true; + + ot_alarmInit(); + ot_radioInit(opt); +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + + ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); + + err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); + SuccessOrExit(err); + + // Call _InitChipStack() on the generic implementation base class + // to finish the initialization process. + /** weiyin, backup mEventLoopTask which is reset in _InitChipStack */ + backup_eventLoopTask = Internal::GenericPlatformManagerImpl_FreeRTOS::mEventLoopTask; + err = Internal::GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(); + SuccessOrExit(err); + Internal::GenericPlatformManagerImpl_FreeRTOS::mEventLoopTask = backup_eventLoopTask; + +exit: + return err; +} + +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp b/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp new file mode 100644 index 00000000000000..251ccf5113a294 --- /dev/null +++ b/src/platform/bouffalolab/BL616/ThreadStackManagerImpl.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include +#include + +#include + +#include + +#include + +#include +#include + +namespace chip { +namespace DeviceLayer { + +using namespace ::chip::DeviceLayer::Internal; + +ThreadStackManagerImpl ThreadStackManagerImpl::sInstance; + +CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack(void) +{ + return InitThreadStack(NULL); +} + +CHIP_ERROR ThreadStackManagerImpl::InitThreadStack(otInstance * otInst) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + + // Initialize the generic implementation base classes. + err = GenericThreadStackManagerImpl_FreeRTOS::DoInit(); + SuccessOrExit(err); + err = GenericThreadStackManagerImpl_OpenThread::DoInit(otInst); + SuccessOrExit(err); + +exit: + return err; +} + +bool ThreadStackManagerImpl::IsInitialized() +{ + return sInstance.mThreadStackLock != NULL; +} + +} // namespace DeviceLayer +} // namespace chip + +using namespace ::chip::DeviceLayer; + +ot_system_event_t ot_system_event_var = OT_SYSTEM_EVENT_NONE; + +void otSysProcessDrivers(otInstance * aInstance) +{ + ot_system_event_t sevent = otrGetNotifyEvent(); + + ot_alarmTask(sevent); + ot_radioTask(sevent); +} + +extern "C" void otTaskletsSignalPending(otInstance * p_instance) +{ + otSysEventSignalPending(); +} + +extern "C" void otSysEventSignalPending(void) +{ + if (xPortIsInsideInterrupt()) + { + BaseType_t yieldRequired = ThreadStackMgrImpl().SignalThreadActivityPendingFromISR(); + portYIELD_FROM_ISR(yieldRequired); + } + else + { + ThreadStackMgrImpl().SignalThreadActivityPending(); + } +} + +extern "C" otInstance * otrGetInstance() +{ + return ThreadStackMgrImpl().OTInstance(); +} + +extern "C" void otrLock(void) +{ + ThreadStackMgrImpl().LockThreadStack(); +} + +extern "C" void otrUnlock(void) +{ + ThreadStackMgrImpl().UnlockThreadStack(); +} + +extern "C" uint32_t otrEnterCrit(void) +{ + if (xPortIsInsideInterrupt()) + { + return taskENTER_CRITICAL_FROM_ISR(); + } + else + { + taskENTER_CRITICAL(); + return 0; + } +} + +extern "C" void otrExitCrit(uint32_t tag) +{ + if (xPortIsInsideInterrupt()) + { + taskEXIT_CRITICAL_FROM_ISR(tag); + } + else + { + taskEXIT_CRITICAL(); + } +} + +extern "C" ot_system_event_t otrGetNotifyEvent(void) +{ + ot_system_event_t sevent = OT_SYSTEM_EVENT_NONE; + + taskENTER_CRITICAL(); + sevent = ot_system_event_var; + ot_system_event_var = OT_SYSTEM_EVENT_NONE; + taskEXIT_CRITICAL(); + + return sevent; +} + +extern "C" void otrNotifyEvent(ot_system_event_t sevent) +{ + if (xPortIsInsideInterrupt()) + { + ot_system_event_var = (ot_system_event_t) (ot_system_event_var | sevent); + } + else + { + uint32_t tag = otrEnterCrit(); + ot_system_event_var = (ot_system_event_t) (ot_system_event_var | sevent); + otrExitCrit(tag); + } + + otSysEventSignalPending(); +} diff --git a/src/platform/bouffalolab/BL616/args.gni b/src/platform/bouffalolab/BL616/args.gni new file mode 100644 index 00000000000000..728448a63908c7 --- /dev/null +++ b/src/platform/bouffalolab/BL616/args.gni @@ -0,0 +1,40 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") +import("${chip_root}/examples/platform/bouffalolab/bl616/args.gni") + +riscv_platform_config = "${bouffalolab_iot_sdk_build_root}/common/rsicv.gni" + +mbedtls_target = "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" + +chip_device_platform = "bl616" + +chip_enable_ota_requestor = true + +lwip_platform = "bl616" + +chip_inet_config_enable_tcp_endpoint = false + +chip_build_tests = false + +openthread_external_mbedtls = mbedtls_target + +openthread_core_config_platform_check_file = + "bl616-openthread-core-bl-config-check.h" +openthread_project_include_dirs = + [ "${chip_root}/src/platform/bouffalolab/BL616" ] +openthread_external_platform = + "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" diff --git a/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h b/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h new file mode 100644 index 00000000000000..32eeb078fbe236 --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-chip-mbedtls-config.h @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2021, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#ifndef MBEDTLS_CONFIG_H +#define MBEDTLS_CONFIG_H +#include +#include +#include + +/** + * Enable FreeRTOS threading support + */ +#define MBEDTLS_FREERTOS +// #define MBEDTLS_THREADING_C + +/** + * Enable H Crypto and Entropy modules + */ +#define MBEDTLS_AES_C +#define MBEDTLS_ECP_C +#define MBEDTLS_ECDH_C +#define MBEDTLS_ENTROPY_C +#define MBEDTLS_SHA256_C +#define MBEDTLS_CIPHER_MODE_CTR +#define MBEDTLS_TRNG_C + +#if defined(MBEDTLS_ECP_ALT) && !defined(MBEDTLS_ECP_RESTARTABLE) +typedef void mbedtls_ecp_restart_ctx; +#endif + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +#define MBEDTLS_PLATFORM_MEMORY + +#define MBEDTLS_CIPHER_PADDING_PKCS7 +#define MBEDTLS_CIPHER_PADDING_ZEROS +#define MBEDTLS_REMOVE_ARC4_CIPHERSUITES +#define MBEDTLS_REMOVE_3DES_CIPHERSUITES + +#define MBEDTLS_AES_ROM_TABLES +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C +#define MBEDTLS_BASE64_C +#define MBEDTLS_BIGNUM_C +#define MBEDTLS_CCM_C +#define MBEDTLS_CIPHER_C +#define MBEDTLS_CIPHER_MODE_CBC +#define MBEDTLS_CIPHER_MODE_CFB +#define MBEDTLS_CMAC_C +#define MBEDTLS_CTR_DRBG_C +#define MBEDTLS_DEBUG_C +#define MBEDTLS_ECDH_LEGACY_CONTEXT +#define MBEDTLS_ECDSA_C +#define MBEDTLS_ECDSA_DETERMINISTIC +#define MBEDTLS_ECJPAKE_C +#define MBEDTLS_ECP_DP_SECP256R1_ENABLED +#define MBEDTLS_ECP_NIST_OPTIM +#define MBEDTLS_ENTROPY_FORCE_SHA256 + +#define MBEDTLS_ERROR_C +#define MBEDTLS_GCM_C +#define MBEDTLS_ERROR_STRERROR_DUMMY +#define MBEDTLS_HAVE_ASM +#define MBEDTLS_HKDF_C +#define MBEDTLS_HMAC_DRBG_C +#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED +#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED +#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED + +#define MBEDTLS_MD_C +#define MBEDTLS_MD5_C +#define MBEDTLS_OID_C +#define MBEDTLS_PEM_PARSE_C +#define MBEDTLS_PEM_WRITE_C +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#define MBEDTLS_PK_WRITE_C +#define MBEDTLS_PKCS5_C +#define MBEDTLS_PKCS1_V15 +#define MBEDTLS_PKCS1_V21 + +#define MBEDTLS_PLATFORM_C +#define MBEDTLS_GENPRIME +#define MBEDTLS_RSA_C +#define MBEDTLS_DHM_C + +#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define MBEDTLS_PSA_CRYPTO_C +#define MBEDTLS_PSA_CRYPTO_CONFIG +#define MBEDTLS_PSA_CRYPTO_DRIVERS +#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS +#define MBEDTLS_PSA_CRYPTO_STORAGE_C + +#define MBEDTLS_SHA1_C +#define MBEDTLS_SHA256_SMALLER +#define MBEDTLS_SHA512_C + +#define MBEDTLS_SSL_CLI_C +#define MBEDTLS_SSL_COOKIE_C +#define MBEDTLS_SSL_DTLS_ANTI_REPLAY +#define MBEDTLS_SSL_DTLS_HELLO_VERIFY +#define MBEDTLS_SSL_EXPORT_KEYS +#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE +#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH +#define MBEDTLS_SSL_PROTO_TLS1_2 +#define MBEDTLS_SSL_ALPN +#define MBEDTLS_SSL_SESSION_TICKETS +#define MBEDTLS_SSL_PROTO_DTLS +#define MBEDTLS_SSL_SRV_C +#define MBEDTLS_SSL_TLS_C +#define MBEDTLS_SSL_SERVER_NAME_INDICATION +#define MBEDTLS_X509_CREATE_C +#define MBEDTLS_X509_CSR_WRITE_C +#define MBEDTLS_X509_CRL_PARSE_C +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_X509_CSR_PARSE_C +#define MBEDTLS_X509_USE_C +#define MBEDTLS_X509_CHECK_KEY_USAGE +#define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE + +#define MBEDTLS_NO_PLATFORM_ENTROPY +#define MBEDTLS_ENTROPY_HARDWARE_ALT + +#define MBEDTLS_PLATFORM_STD_MEM_HDR "mbedtls_port_bouffalo_sdk.h" +#define MBEDTLS_SSL_MAX_CONTENT_LEN 900 /**< Maxium fragment length in bytes */ + +#define MBEDTLS_SHA1_ALT +#define MBEDTLS_SHA256_ALT +#define MBEDTLS_SHA512_ALT +#define MBEDTLS_AES_ALT +#define MBEDTLS_ECP_ALT + +#if defined(CONFIG_MBEDTLS_ECC_USE_HW) && defined(MBEDTLS_ECP_RESTARTABLE) +#error "ECP Restartable is not implemented with ECP HW acceleration!" +#endif + +#include "mbedtls/check_config.h" + +#endif /* MBEDTLS_CONFIG_H */ diff --git a/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h new file mode 100644 index 00000000000000..8c15b61eb608bc --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config-check.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2019, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OPENTHREAD_CORE_CONFIG_CHECK_H_ +#define OPENTHREAD_CORE_CONFIG_CHECK_H_ + +#if OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT +#error "Platform doesn't support configuration option: OPENTHREAD_CONFIG_RADIO_915MHZ_OQPSK_SUPPORT" +#endif + +#endif /* OPENTHREAD_CORE_CONFIG_CHECK_H_ */ diff --git a/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h new file mode 100644 index 00000000000000..8c4c5f3807a7d0 --- /dev/null +++ b/src/platform/bouffalolab/BL616/bl616-openthread-core-bl-config.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2016, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OPENTHREAD_CORE_PROJ_CONFIG_H +#define OPENTHREAD_CORE_PROJ_CONFIG_H + +#define OPENTHREAD_CONFIG_PLATFORM_INFO "BL616" + +// #define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_DEBG + +#if !defined(OPENTHREAD_FTD) && !defined(OPENTHREAD_MTD) +#if CHIP_DEVICE_CONFIG_THREAD_FTD +#define OPENTHREAD_FTD 1 +#define OPENTHREAD_MTD 0 +#else +#define OPENTHREAD_FTD 0 +#define OPENTHREAD_MTD 1 +#endif +#endif + +#define OPENTHREAD_CONFIG_PING_SENDER_ENABLE 1 + +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_SUBJECT_ENABLE 1 +#define OPENTHREAD_CONFIG_MLE_LINK_METRICS_INITIATOR_ENABLE 1 + +#define OPENTHREAD_CONFIG_TMF_PROXY_MLR_ENABLE 1 +#define OPENTHREAD_CONFIG_DUA_ENABLE 1 +#define OPENTHREAD_CONFIG_MLR_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_FRAGMENTATION_ENABLE 1 + +#define OPENTHREAD_CONFIG_TMF_NETDIAG_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_TMF_NETDATA_SERVICE_ENABLE 1 +#define OPENTHREAD_CONFIG_TMF_ANYCAST_LOCATOR_ENABLE 1 +#define OPENTHREAD_CONFIG_DATASET_UPDATER_ENABLE 1 + +// #define OPENTHREAD_CONFIG_COAP_API_ENABLE 1 +// #define OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE 1 +// #define OPENTHREAD_CONFIG_COAP_BLOCKWISE_TRANSFER_ENABLE 1 + +#define OPENTHREAD_CONFIG_IP6_SLAAC_ENABLE 1 +#define OPENTHREAD_CONFIG_DHCP6_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_SNTP_CLIENT_ENABLE 1 + +#define OPENTHREAD_CONFIG_NEIGHBOR_DISCOVERY_AGENT_ENABLE 1 + +#define OPENTHREAD_CONFIG_ECDSA_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_ENABLE 1 +#define OPENTHREAD_CONFIG_SRP_CLIENT_AUTO_START_API_ENABLE 1 + +// #define OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE 1 + +// #define OPENTHREAD_CONFIG_MAC_BEACON_PAYLOAD_PARSING_ENABLE 1 +// #define OPENTHREAD_CONFIG_MAC_OUTGOING_BEACON_PAYLOAD_ENABLE 1 + +#if OPENTHREAD_FTD +#define OPENTHREAD_CONFIG_COMMISSIONER_ENABLE 1 +#define OPENTHREAD_CONFIG_JOINER_ENABLE 1 +#endif + +#if OPENTHREAD_MTD +#define OPENTHREAD_CONFIG_JOINER_ENABLE 1 +#endif + +#define OPENTHREAD_CONFIG_TCP_ENABLE 0 +#define OPENTHREAD_CONFIG_TLS_ENABLE 0 +#define OPENTHREAD_CONFIG_SRP_SERVER_ENABLE 0 +#define OPENTHREAD_CONFIG_BORDER_ROUTER_ENABLE 0 +#define OPENTHREAD_CONFIG_BACKBONE_ROUTER_ENABLE 0 + +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ACK_TIMEOUT_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_RETRANSMIT_ENABLE 1 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_CSMA_BACKOFF_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_TX_SECURITY_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_TX_TIMING_ENABLE 0 +#define OPENTHREAD_CONFIG_MAC_SOFTWARE_ENERGY_SCAN_ENABLE 1 + +#define OPENTHREAD_CONFIG_PLATFORM_USEC_TIMER_ENABLE 1 +#define OPENTHREAD_CONFIG_HEAP_EXTERNAL_ENABLE 1 + +#define OPENTHREAD_EXAMPLES_SIMULATION 0 +#define OPENTHREAD_PLATFORM_POSIX 0 +#define OPENTHREAD_ENABLE_VENDOR_EXTENSION 0 + +#define IEEE802_15_4_RADIO_RECEIVE_SENSITIVITY -105 +#define OPENTHREAD_CONFIG_PLATFORM_XTAL_ACCURACY 40 + +#endif // OPENTHREAD_CORE_PROJ_CONFIG_H diff --git a/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c new file mode 100644 index 00000000000000..bf22cb51abccc3 --- /dev/null +++ b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.c @@ -0,0 +1,59 @@ +#include +#include + +#include +#include + +#include +#undef __INLINE +#undef __PACKED +#include + +#include + +#define WIFI_STACK_SIZE (1536) +#define TASK_PRIORITY_FW (16) + +static TaskHandle_t wifi_fw_task; +static netif_ext_callback_t netifExtCallback; + +struct netif * deviceInterface_getNetif(void) +{ + LOCK_TCPIP_CORE(); + struct netif * net_if = netif_find("wl1"); + UNLOCK_TCPIP_CORE(); + + return net_if; +} + +int wifi_start_scan(const uint8_t * ssid, uint32_t length) +{ + wifi_mgmr_scan_params_t config; + + memset(&config, 0, sizeof(wifi_mgmr_scan_params_t)); + if (length && length <= MGMR_SSID_LEN) + { + memcpy(config.ssid_array, ssid, length); + config.ssid_length = length; + } + + return wifi_mgmr_sta_scan(&config); +} + +void wifi_start_firmware_task(void) +{ + memset(&netifExtCallback, 0, sizeof(netifExtCallback)); + + GLB_PER_Clock_UnGate(GLB_AHB_CLOCK_IP_WIFI_PHY | GLB_AHB_CLOCK_IP_WIFI_MAC_PHY | GLB_AHB_CLOCK_IP_WIFI_PLATFORM); + GLB_AHB_MCU_Software_Reset(GLB_AHB_MCU_SW_WIFI); + + extern void interrupt0_handler(void); + bflb_irq_attach(WIFI_IRQn, (irq_callback) interrupt0_handler, NULL); + bflb_irq_enable(WIFI_IRQn); + + LOCK_TCPIP_CORE(); + netif_add_ext_callback(&netifExtCallback, network_netif_ext_callback); + UNLOCK_TCPIP_CORE(); + + xTaskCreate(wifi_main, (char *) "fw", WIFI_STACK_SIZE, NULL, TASK_PRIORITY_FW, &wifi_fw_task); +} diff --git a/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h new file mode 100644 index 00000000000000..9ebffffa20e422 --- /dev/null +++ b/src/platform/bouffalolab/BL616/wifi_mgmr_portable.h @@ -0,0 +1,18 @@ +#ifndef __WIFI_MGMR_POARABLE_H__ +#define __WIFI_MGMR_POARABLE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +int wifi_start_scan(const uint8_t * ssid, uint32_t length); +void network_netif_ext_callback(struct netif * netif, netif_nsc_reason_t reason, const netif_ext_callback_args_t * args); +void wifi_start_firmware_task(void); + +struct netif * deviceInterface_getNetif(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/platform/bouffalolab/BL702/BUILD.gn b/src/platform/bouffalolab/BL702/BUILD.gn index e0daee04056a51..c9112449a652fc 100644 --- a/src/platform/bouffalolab/BL702/BUILD.gn +++ b/src/platform/bouffalolab/BL702/BUILD.gn @@ -41,6 +41,7 @@ static_library("BL702") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -57,8 +58,6 @@ static_library("BL702") { ] } - deps = [ "${chip_root}/src/platform/logging:headers" ] - if (chip_enable_factory_data) { sources += [ "../common/FactoryDataProvider.cpp", @@ -72,6 +71,11 @@ static_library("BL702") { sources += [ "../common/BLConfig_littlefs.cpp" ] } + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + if (chip_enable_wifi) { sources += [ "ConfigurationManagerImpl.cpp", @@ -115,6 +119,5 @@ static_library("BL702") { deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } - deps += [ "${chip_root}/src/credentials:credentials_header" ] public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp index ae68f9c680795c..94835f921c753f 100644 --- a/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702/PlatformManagerImpl.cpp @@ -79,8 +79,6 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) ot_radioInit(opt); #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - err = chip::Crypto::add_entropy_source(app_entropy_source, NULL, 16); SuccessOrExit(err); diff --git a/src/platform/bouffalolab/BL702L/BUILD.gn b/src/platform/bouffalolab/BL702L/BUILD.gn index 2529c8d3a7e736..c32dc33255e541 100644 --- a/src/platform/bouffalolab/BL702L/BUILD.gn +++ b/src/platform/bouffalolab/BL702L/BUILD.gn @@ -39,6 +39,7 @@ static_library("BL702L") { "../common/DiagnosticDataProviderImpl.cpp", "../common/KeyValueStoreManagerImpl.cpp", "../common/PlatformManagerImpl.cpp", + "../common/SystemTimeSupport.cpp", ] if (chip_enable_ota_requestor) { @@ -55,8 +56,6 @@ static_library("BL702L") { ] } - deps = [ "${chip_root}/src/platform/logging:headers" ] - if (chip_enable_factory_data) { sources += [ "../common/FactoryDataProvider.cpp", @@ -70,6 +69,11 @@ static_library("BL702L") { sources += [ "../common/BLConfig_littlefs.cpp" ] } + deps = [ + "${chip_root}/src/credentials:credentials_header", + "${chip_root}/src/platform/logging:headers", + ] + if (chip_enable_openthread) { # needed for MTD/FTD @@ -92,6 +96,5 @@ static_library("BL702L") { } } - deps += [ "${chip_root}/src/credentials:credentials_header" ] public_deps = [ "${chip_root}/src/platform:platform_base" ] } diff --git a/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp b/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp index 68c75305f64ed8..2cd84609ef0505 100644 --- a/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp +++ b/src/platform/bouffalolab/BL702L/PlatformManagerImpl.cpp @@ -57,17 +57,22 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) TaskHandle_t backup_eventLoopTask; otRadio_opt_t opt; + opt.byte = 0; - opt.byte = 0; +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD +#if CHIP_DEVICE_CONFIG_THREAD_FTD + opt.bf.isFtd = true; +#else + opt.bf.isFtd = false; +#endif opt.bf.isCoexEnable = true; +#endif ot_utils_init(); ot_alarmInit(); ot_radioInit(opt); - ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); - #if CHIP_SYSTEM_CONFIG_USE_LWIP // Initialize LwIP. tcpip_init(NULL, NULL); diff --git a/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h b/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h index 6937bba875750b..659f782448357c 100644 --- a/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h +++ b/src/platform/bouffalolab/BL702L/bl702l-openthread-core-bl-config.h @@ -32,6 +32,7 @@ #define OPENTHREAD_CONFIG_PLATFORM_INFO "BL702L" // #define OPENTHREAD_CONFIG_LOG_LEVEL OT_LOG_LEVEL_DEBG +// #define OPENTHREAD_CONFIG_LOG_PKT_DUMP 0 #if !defined(OPENTHREAD_FTD) && !defined(OPENTHREAD_MTD) #if CHIP_DEVICE_CONFIG_THREAD_FTD diff --git a/src/platform/bouffalolab/common/BLConfig_littlefs.cpp b/src/platform/bouffalolab/common/BLConfig_littlefs.cpp index ae0788ab1c8f62..7f5e221195e8d3 100644 --- a/src/platform/bouffalolab/common/BLConfig_littlefs.cpp +++ b/src/platform/bouffalolab/common/BLConfig_littlefs.cpp @@ -36,7 +36,20 @@ namespace chip { namespace DeviceLayer { namespace Internal { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +static struct lfs_context lfs_ctx = { .partition_name = (char *) "PSM" }; +static struct lfs_config lfs_cfg = { + .read_size = 256, + .prog_size = 256, + .block_size = 4096, + .block_cycles = 500, + .cache_size = 512, + .lookahead_size = 256, +}; +static lfs_t * blconfig_lfs = NULL; +#else static lfs_t * blconfig_lfs = nullptr; +#endif static inline char * blcfg_convert_key(const char * pKey, const char * pNameSpace = NULL) { @@ -153,7 +166,11 @@ void BLConfig::Init(void) int ret; struct lfs_info stat; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + blconfig_lfs = lfs_xip_init(&lfs_ctx, &lfs_cfg); +#else blconfig_lfs = lfs_xip_init(); +#endif VerifyOrExit(blconfig_lfs != NULL, err = CHIP_ERROR_PERSISTED_STORAGE_FAILED); /* init namespace */ diff --git a/src/platform/bouffalolab/common/BLEManagerImpl.cpp b/src/platform/bouffalolab/common/BLEManagerImpl.cpp index 7731828c314ca3..c5a3932e83cc1f 100644 --- a/src/platform/bouffalolab/common/BLEManagerImpl.cpp +++ b/src/platform/bouffalolab/common/BLEManagerImpl.cpp @@ -31,7 +31,7 @@ #endif extern "C" { -#if CHIP_DEVICE_LAYER_TARGET_BL702L +#if CHIP_DEVICE_LAYER_TARGET_BL702L || CHIP_DEVICE_LAYER_TARGET_BL616 #include #else #include @@ -121,7 +121,7 @@ CHIP_ERROR BLEManagerImpl::_Init() memset(mSubscribedConns, 0, sizeof(mSubscribedConns)); ReturnErrorOnFailure(InitRandomStaticAddress()); -#if CHIP_DEVICE_LAYER_TARGET_BL702L +#if CHIP_DEVICE_LAYER_TARGET_BL702L || CHIP_DEVICE_LAYER_TARGET_BL616 btble_controller_init(configMAX_PRIORITIES - 1); #else ble_controller_init(configMAX_PRIORITIES - 1); @@ -841,6 +841,10 @@ ssize_t BLEManagerImpl::HandleC3Read(struct bt_conn * conId, const struct bt_gat } #endif +extern "C" int ble_connection_number(void) +{ + return BLEMgr().NumConnections(); +} } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp index 4318dcc4a58dac..176803d00a1ebe 100644 --- a/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConfigurationManagerImpl.cpp @@ -21,7 +21,13 @@ #include +#if CHIP_DEVICE_LAYER_TARGET_BL616 +extern "C" { +#include +} +#else extern "C" void hal_reboot(void); +#endif namespace chip { namespace DeviceLayer { @@ -202,8 +208,11 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) // Restart the system. ChipLogProgress(DeviceLayer, "System restarting"); - +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bl_sys_reset_por(); +#else hal_reboot(); +#endif } ConfigurationManager & ConfigurationMgrImpl() diff --git a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp index c6babf25e5f74c..dcff80f79beab9 100644 --- a/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.cpp @@ -39,6 +39,9 @@ #if CHIP_DEVICE_LAYER_TARGET_BL702 #include #endif +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#endif #endif #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/bouffalolab/common/ConnectivityManagerImpl.h b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h index 80b1d980d4f9d1..7a36c59cceca29 100644 --- a/src/platform/bouffalolab/common/ConnectivityManagerImpl.h +++ b/src/platform/bouffalolab/common/ConnectivityManagerImpl.h @@ -46,6 +46,7 @@ enum { kWiFiOnInitDone = DeviceEventType::kRange_PublicPlatformSpecific, kWiFiOnScanDone, + kWiFiOnConnecting, kWiFiOnConnected, kGotIpAddress, kGotIpv6Address, diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp index 45deceb2e03255..a5d70240ba5a04 100644 --- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp +++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp @@ -23,7 +23,9 @@ #include #include - +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#endif namespace chip { namespace DeviceLayer { @@ -41,22 +43,33 @@ DiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance() CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + struct meminfo info; + bflb_mem_usage(KMEM_HEAP, &info); + currentHeapFree = info.free_size; +#else #ifdef CFG_USE_PSRAM - size_t freeHeapSize = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); + currentHeapFree = xPortGetFreeHeapSize() + xPortGetFreeHeapSizePsram(); #else - size_t freeHeapSize = xPortGetFreeHeapSize(); + currentHeapFree = xPortGetFreeHeapSize(); +#endif #endif - currentHeapFree = static_cast(freeHeapSize); return CHIP_NO_ERROR; } CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + struct meminfo info; + bflb_mem_usage(KMEM_HEAP, &info); + currentHeapUsed = info.total_size - info.free_size; +#else #ifdef CFG_USE_PSRAM currentHeapUsed = (get_heap_size() + get_heap3_size() - xPortGetFreeHeapSize() - xPortGetFreeHeapSizePsram()); #else currentHeapUsed = (get_heap_size() - xPortGetFreeHeapSize()); +#endif #endif return CHIP_NO_ERROR; @@ -64,14 +77,17 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeap CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + return CHIP_ERROR_NOT_IMPLEMENTED; +#else #ifdef CFG_USE_PSRAM currentHeapHighWatermark = get_heap_size() + get_heap3_size() - xPortGetMinimumEverFreeHeapSize() - xPortGetMinimumEverFreeHeapSizePsram(); #else currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize(); #endif - return CHIP_NO_ERROR; +#endif } CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut) @@ -233,7 +249,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** #if CHIP_DEVICE_CONFIG_ENABLE_WIFI ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kWiFi; #else - ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kEthernet; + ifp->type = app::Clusters::GeneralDiagnostics::InterfaceTypeEnum::kEthernet; #endif ifp->offPremiseServicesReachableIPv4.SetNull(); ifp->offPremiseServicesReachableIPv6.SetNull(); diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp index 0d3357b38f0106..d55b2a26d10af4 100644 --- a/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.cpp @@ -19,14 +19,20 @@ #include extern "C" { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +#include +#include +#else #include #include - -extern void hal_reboot(void); +#endif } - #include "OTAImageProcessorImpl.h" +#if CHIP_DEVICE_LAYER_TARGET_BL602 || CHIP_DEVICE_LAYER_TARGET_BL702 || CHIP_DEVICE_LAYER_TARGET_BL702L +extern "C" void hal_reboot(void); +#endif + using namespace chip::System; namespace chip { @@ -136,7 +142,11 @@ void OTAImageProcessorImpl::HandleFinalize(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_check() < 0) +#else if (hosal_ota_check() < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); ChipLogProgress(SoftwareUpdate, "OTA image verification error"); @@ -158,12 +168,20 @@ void OTAImageProcessorImpl::HandleApply(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bflb_ota_apply(); +#else hosal_ota_apply(0); +#endif DeviceLayer::SystemLayer().StartTimer( System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), [](Layer *, void *) { ChipLogProgress(SoftwareUpdate, "Rebooting..."); +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bl_sys_reset_por(); +#else hal_reboot(); +#endif }, nullptr); } @@ -176,7 +194,11 @@ void OTAImageProcessorImpl::HandleAbort(intptr_t context) return; } +#if CHIP_DEVICE_LAYER_TARGET_BL616 + bflb_ota_abort(); +#else hosal_ota_abort(); +#endif imageProcessor->ReleaseBlock(); } @@ -219,7 +241,11 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) imageProcessor->mParams.totalFileBytes = header.mPayloadSize; imageProcessor->mHeaderParser.Clear(); +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_start(header.mPayloadSize) < 0) +#else if (hosal_ota_start(header.mPayloadSize) < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); return; @@ -228,8 +254,13 @@ void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) if (imageProcessor->mParams.totalFileBytes) { +#if CHIP_DEVICE_LAYER_TARGET_BL616 + if (bflb_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, + (uint8_t *) block.data(), block.size()) < 0) +#else if (hosal_ota_update(imageProcessor->mParams.totalFileBytes, imageProcessor->mParams.downloadedBytes, (uint8_t *) block.data(), block.size()) < 0) +#endif { imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); return; diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl.h b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h index 3e68f3c59d329a..2e0656affacf03 100644 --- a/src/platform/bouffalolab/common/OTAImageProcessorImpl.h +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl.h @@ -24,6 +24,31 @@ namespace chip { +#if CHIP_DEVICE_LAYER_TARGET_BL616 +typedef struct _ota_header_s +{ + uint8_t header[16]; + + uint8_t type[4]; // RAW XZ + uint32_t image_len; // body len + uint8_t pad0[8]; + + uint8_t ver_hardware[16]; + uint8_t ver_software[16]; + + uint8_t sha256[32]; +} ota_header_s_t; + +typedef struct _ota_header +{ + union + { + ota_header_s_t s; + uint8_t _pad[512]; + } u; +} ota_header_t; +#endif + class OTAImageProcessorImpl : public OTAImageProcessorInterface { public: @@ -59,6 +84,10 @@ class OTAImageProcessorImpl : public OTAImageProcessorInterface MutableByteSpan mBlock; OTADownloader * mDownloader; OTAImageHeaderParser mHeaderParser; +#if CHIP_DEVICE_LAYER_TARGET_BL616 + ota_header_s_t mOtaHdr; + uint32_t mImageTotalSize; +#endif }; } // namespace chip diff --git a/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp b/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp new file mode 100644 index 00000000000000..0e0a6ff0ccd14d --- /dev/null +++ b/src/platform/bouffalolab/common/OTAImageProcessorImpl_bflb.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2022 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "OTAImageProcessorImpl.h" +#include +#include + +extern "C" { +#include +#include +} + +using namespace chip::System; + +namespace chip { + +#define OTA_IMAGE_TYPE_XZ "XZ" +#define OTA_IMAGE_TYPE_RAW "RAW" + +static bool check_ota_header(ota_header_s_t * ota_header_s) +{ + char str[sizeof(ota_header_s->header) + 1]; + + memcpy(str, ota_header_s->header, sizeof(ota_header_s->header)); + str[sizeof(ota_header_s->header)] = '\0'; + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA header: %s", str); + + if (0 == memcmp(OTA_IMAGE_TYPE_XZ, ota_header_s->type, strlen(OTA_IMAGE_TYPE_XZ))) + { + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image type: %s", OTA_IMAGE_TYPE_XZ); + } + else if (0 == memcmp(OTA_IMAGE_TYPE_RAW, ota_header_s->type, strlen(OTA_IMAGE_TYPE_RAW))) + { + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image type: %s", OTA_IMAGE_TYPE_RAW); + } + else + { + return false; + } + + ChipLogProgress(SoftwareUpdate, "Bouffalo Lab OTA image file size: %ld", ota_header_s->image_len); + + memcpy(str, ota_header_s->ver_hardware, sizeof(ota_header_s->ver_hardware)); + str[sizeof(ota_header_s->ver_hardware)] = '\0'; + ChipLogProgress(SoftwareUpdate, "OTA image hardware version: %s", str); + + memcpy(str, ota_header_s->ver_software, sizeof(ota_header_s->ver_software)); + str[sizeof(ota_header_s->ver_software)] = '\0'; + ChipLogProgress(SoftwareUpdate, "OTA image software version: %s", str); + + return true; +} + +bool OTAImageProcessorImpl::IsFirstImageRun() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return false; + } + + return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying; +} + +CHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage() +{ + OTARequestorInterface * requestor = chip::GetRequestorInstance(); + if (requestor == nullptr) + { + return CHIP_ERROR_INTERNAL; + } + + uint32_t currentVersion; + uint32_t targetVersion = requestor->GetTargetVersion(); + ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion)); + if (currentVersion != targetVersion) + { + ChipLogError(SoftwareUpdate, "Current software version = %" PRIu32 ", expected software version = %" PRIu32, currentVersion, + targetVersion); + return CHIP_ERROR_INCORRECT_STATE; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::PrepareDownload() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Finalize() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Apply() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::Abort() +{ + DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block) +{ + if ((nullptr == block.data()) || block.empty()) + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Store block data for HandleProcessBlock to access + CHIP_ERROR err = SetBlock(block); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot set block data: %" CHIP_ERROR_FORMAT, err.Format()); + } + + DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast(this)); + return CHIP_NO_ERROR; +} + +void OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + + imageProcessor->mParams.downloadedBytes = 0; + imageProcessor->mParams.totalFileBytes = 0; + imageProcessor->mHeaderParser.Init(); + + memset(&(imageProcessor->mOtaHdr), 0, sizeof(ota_header_s_t)); + imageProcessor->mImageTotalSize = 0; + + imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR); +} + +void OTAImageProcessorImpl::HandleFinalize(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + return; + } + + ByteSpan block = imageProcessor->mBlock; + + if (bflb_ota_update(imageProcessor->mImageTotalSize, imageProcessor->mParams.downloadedBytes - sizeof(ota_header_t), + imageProcessor->mOtaHdr.sha256, sizeof(imageProcessor->mOtaHdr.sha256)) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + + if (bflb_ota_check() < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + ChipLogProgress(SoftwareUpdate, "OTA image verification error"); + } + else + { + ChipLogProgress(SoftwareUpdate, "OTA image downloaded"); + } + + imageProcessor->ReleaseBlock(); +} + +void OTAImageProcessorImpl::HandleApply(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + return; + } + + bflb_ota_apply(); + + DeviceLayer::SystemLayer().StartTimer( + System::Clock::Seconds32(OTA_AUTO_REBOOT_DELAY), + [](Layer *, void *) { + ChipLogProgress(SoftwareUpdate, "Rebooting..."); + bl_sys_reset_por(); + }, + nullptr); +} + +void OTAImageProcessorImpl::HandleAbort(intptr_t context) +{ + auto * imageProcessor = reinterpret_cast(context); + if (imageProcessor == nullptr) + { + return; + } + + bflb_ota_abort(); + + imageProcessor->ReleaseBlock(); +} + +void OTAImageProcessorImpl::HandleProcessBlock(intptr_t context) +{ + OTAImageHeader header; + CHIP_ERROR error; + uint32_t iOffset, iSize; + + auto * imageProcessor = reinterpret_cast(context); + + if (imageProcessor == nullptr) + { + ChipLogError(SoftwareUpdate, "ImageProcessor context is null"); + return; + } + else if (imageProcessor->mDownloader == nullptr) + { + ChipLogError(SoftwareUpdate, "mDownloader is null"); + return; + } + + ByteSpan block = imageProcessor->mBlock; + if (imageProcessor->mHeaderParser.IsInitialized()) + { + error = imageProcessor->mHeaderParser.AccumulateAndDecode(block, header); + if (CHIP_ERROR_BUFFER_TOO_SMALL == error) + { + return; + } + else if (CHIP_NO_ERROR != error) + { + ChipLogError(SoftwareUpdate, "Matter image header parser error %s", chip::ErrorStr(error)); + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER); + imageProcessor->mHeaderParser.Clear(); + return; + } + + ChipLogProgress(SoftwareUpdate, "Image Header software version: %ld payload size: %lu", header.mSoftwareVersion, + (long unsigned int) header.mPayloadSize); + imageProcessor->mParams.totalFileBytes = header.mPayloadSize; + imageProcessor->mHeaderParser.Clear(); + } + + if (imageProcessor->mParams.totalFileBytes) + { + if (0 == imageProcessor->mImageTotalSize) + { + + iSize = sizeof(ota_header_s_t) - imageProcessor->mParams.downloadedBytes; + if (block.size() < iSize) + { + iSize = block.size(); + } + + memcpy(reinterpret_cast(&imageProcessor->mOtaHdr) + imageProcessor->mParams.downloadedBytes, block.data(), + iSize); + + if (imageProcessor->mParams.downloadedBytes + iSize >= sizeof(ota_header_s_t)) + { + if (!check_ota_header(&imageProcessor->mOtaHdr)) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_DECODE_FAILED); + return; + } + + if (bflb_ota_start(imageProcessor->mOtaHdr.image_len + sizeof(imageProcessor->mOtaHdr.sha256)) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_OPEN_FAILED); + return; + } + + imageProcessor->mImageTotalSize = imageProcessor->mOtaHdr.image_len + sizeof(imageProcessor->mOtaHdr.sha256); + } + } + + if (imageProcessor->mImageTotalSize && imageProcessor->mParams.downloadedBytes + block.size() > sizeof(ota_header_t)) + { + + if (imageProcessor->mParams.downloadedBytes >= sizeof(ota_header_t)) + { + iOffset = imageProcessor->mParams.downloadedBytes - sizeof(ota_header_t); + iSize = 0; + } + else + { + iOffset = 0; + iSize = sizeof(ota_header_t) - imageProcessor->mParams.downloadedBytes; + } + + if (bflb_ota_update(imageProcessor->mImageTotalSize, iOffset, const_cast(block.data() + iSize), + block.size() - iSize) < 0) + { + imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED); + return; + } + } + + imageProcessor->mParams.downloadedBytes += block.size(); + } + + imageProcessor->mDownloader->FetchNextData(); +} + +// Store block data for HandleProcessBlock to access +CHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block) +{ + if ((block.data() == nullptr) || block.empty()) + { + return CHIP_NO_ERROR; + } + + // Allocate memory for block data if we don't have enough already + if (mBlock.size() < block.size()) + { + ReleaseBlock(); + + mBlock = MutableByteSpan(static_cast(chip::Platform::MemoryAlloc(block.size())), block.size()); + if (mBlock.data() == nullptr) + { + return CHIP_ERROR_NO_MEMORY; + } + } + + // Store the actual block data + CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock); + if (err != CHIP_NO_ERROR) + { + ChipLogError(SoftwareUpdate, "Cannot copy block data: %" CHIP_ERROR_FORMAT, err.Format()); + return err; + } + + return CHIP_NO_ERROR; +} + +CHIP_ERROR OTAImageProcessorImpl::ReleaseBlock() +{ + if (mBlock.data() != nullptr) + { + chip::Platform::MemoryFree(mBlock.data()); + } + + mBlock = MutableByteSpan(); + return CHIP_NO_ERROR; +} + +} // namespace chip diff --git a/src/platform/bouffalolab/common/SystemPlatformConfig.h b/src/platform/bouffalolab/common/SystemPlatformConfig.h index c42b2671f84b48..89a0a5a8f9a966 100644 --- a/src/platform/bouffalolab/common/SystemPlatformConfig.h +++ b/src/platform/bouffalolab/common/SystemPlatformConfig.h @@ -34,5 +34,13 @@ struct ChipDeviceEvent; #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 8 #endif +#if CHIP_DEVICE_LAYER_TARGET_BL616 +// #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(mbedtls_sha256_context) in hw_acc/sha256_alt.h +#define CHIP_CONFIG_SHA256_CONTEXT_SIZE (32 + 64 + 64 + 19 * 32) +#define CHIP_CONFIG_SHA256_CONTEXT_ALIGN 32 +#define CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE (388) +#else + // #define CHIP_CONFIG_SHA256_CONTEXT_SIZE sizeof(bl_sha_ctx_t) #define CHIP_CONFIG_SHA256_CONTEXT_SIZE ((7 + 1 + 5 + 18 + 16 + 16 + 7) * sizeof(unsigned int)) +#endif diff --git a/src/platform/bouffalolab/common/SystemTimeSupport.cpp b/src/platform/bouffalolab/common/SystemTimeSupport.cpp new file mode 100644 index 00000000000000..89a9756ca23fde --- /dev/null +++ b/src/platform/bouffalolab/common/SystemTimeSupport.cpp @@ -0,0 +1,78 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2018 Nest Labs, Inc. + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* this file behaves like a config.h, comes first */ +#include + +#include +#include + +#include + +#if CHIP_SYSTEM_CONFIG_PLATFORM_PROVIDES_TIME + +namespace chip { +namespace System { +namespace Clock { + +namespace Internal { +ClockImpl gClockImpl; +} // namespace Internal + +static Microseconds64 gBootRealTime = Seconds64::zero(); + +Microseconds64 ClockImpl::GetMonotonicMicroseconds64(void) +{ + return Clock::Microseconds64(bl_timer_now_us64()); +} + +Milliseconds64 ClockImpl::GetMonotonicMilliseconds64(void) +{ + return Clock::Milliseconds64(bl_timer_now_us64() / 1000); +} + +CHIP_ERROR ClockImpl::GetClock_RealTime(Microseconds64 & aCurTime) +{ + aCurTime = gBootRealTime + GetMonotonicMicroseconds64(); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::GetClock_RealTimeMS(Milliseconds64 & aCurTime) +{ + Microseconds64 curTimeUs; + + GetClock_RealTime(curTimeUs); + aCurTime = std::chrono::duration_cast(curTimeUs); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR ClockImpl::SetClock_RealTime(Microseconds64 aNewCurTime) +{ + gBootRealTime = aNewCurTime - GetMonotonicMicroseconds64(); + + return CHIP_NO_ERROR; +} + +} // namespace Clock +} // namespace System +} // namespace chip + +#endif diff --git a/src/platform/bouffalolab/common/SystemTimeSupport.h b/src/platform/bouffalolab/common/SystemTimeSupport.h new file mode 100644 index 00000000000000..7ef95ab66c67cd --- /dev/null +++ b/src/platform/bouffalolab/common/SystemTimeSupport.h @@ -0,0 +1,24 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +namespace chip { +namespace System { +namespace Clock {} // namespace Clock +} // namespace System +} // namespace chip diff --git a/src/platform/device.gni b/src/platform/device.gni index 87e2eb12e8d0d2..a28d9823a91438 100644 --- a/src/platform/device.gni +++ b/src/platform/device.gni @@ -175,6 +175,8 @@ if (chip_device_platform == "cc13x4_26x4") { _chip_device_layer = "Ameba" } else if (chip_device_platform == "bl602") { _chip_device_layer = "bouffalolab/common" +} else if (chip_device_platform == "bl616") { + _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702") { _chip_device_layer = "bouffalolab/common" } else if (chip_device_platform == "bl702l") { @@ -265,9 +267,9 @@ assert( chip_device_platform == "ameba" || chip_device_platform == "cyw30739" || chip_device_platform == "webos" || chip_device_platform == "mw320" || chip_device_platform == "zephyr" || chip_device_platform == "beken" || - chip_device_platform == "bl602" || chip_device_platform == "bl702" || - chip_device_platform == "bl702l" || chip_device_platform == "mt793x" || - chip_device_platform == "SiWx917" || + chip_device_platform == "bl602" || chip_device_platform == "bl616" || + chip_device_platform == "bl702" || chip_device_platform == "bl702l" || + chip_device_platform == "mt793x" || chip_device_platform == "SiWx917" || chip_device_platform == "openiotsdk" || chip_device_platform == "asr" || chip_device_platform == "stm32" || chip_device_platform == "nuttx", "Please select a valid value for chip_device_platform") diff --git a/src/platform/logging/BUILD.gn b/src/platform/logging/BUILD.gn index e415448a7f12d1..f928f0d863a8b1 100644 --- a/src/platform/logging/BUILD.gn +++ b/src/platform/logging/BUILD.gn @@ -25,6 +25,7 @@ group("default") { } else if (chip_device_platform == "mbed") { deps += [ "${chip_root}/src/platform/mbed:logging" ] } else if (chip_device_platform == "bl602" || + chip_device_platform == "bl616" || chip_device_platform == "bl702" || chip_device_platform == "bl702l") { deps += [ "${chip_root}/src/platform/bouffalolab/common:logging" ] diff --git a/src/system/BUILD.gn b/src/system/BUILD.gn index 3de5ea84be11f5..3fff2a61e648da 100644 --- a/src/system/BUILD.gn +++ b/src/system/BUILD.gn @@ -72,6 +72,8 @@ if (chip_device_platform == "cc13x4_26x4") { import("//build_overrides/bouffalolab_iot_sdk.gni") } else if (chip_device_platform == "bl702l") { import("//build_overrides/bouffalolab_iot_sdk.gni") +} else if (chip_device_platform == "bl616") { + import("//build_overrides/bouffalolab_iot_sdk.gni") } buildconfig_header("system_buildconfig") { @@ -197,6 +199,10 @@ source_set("system_config_header") { if (chip_device_platform == "bl702l") { public_deps += [ "${bouffalolab_iot_sdk_build_root}/bl702l:bl_iot_sdk" ] } + if (chip_device_platform == "bl616") { + public_deps += + [ "${bouffalolab_iot_sdk_build_root}/bl616:bouffalo_sdk" ] + } # Add platform here as needed. } diff --git a/third_party/bouffalolab/bl616/BUILD.gn b/third_party/bouffalolab/bl616/BUILD.gn new file mode 100644 index 00000000000000..15335a44f9354a --- /dev/null +++ b/third_party/bouffalolab/bl616/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (c) 2020 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("${bouffalolab_iot_sdk_build_root}/bl616/bouffalo_sdk.gni") + +declare_args() { + # Build target to use for Bouffalo Lab SDK. Use this to set global SDK defines. + bouffalo_sdk_target = "" +} + +assert(bouffalo_sdk_target != "", "bl_iot_sdk_target must be specified") + +group("bouffalo_sdk") { + public_deps = [ bouffalo_sdk_target ] +} diff --git a/third_party/bouffalolab/bl616/bouffalo_sdk.gni b/third_party/bouffalolab/bl616/bouffalo_sdk.gni new file mode 100644 index 00000000000000..174b04b8160ae2 --- /dev/null +++ b/third_party/bouffalolab/bl616/bouffalo_sdk.gni @@ -0,0 +1,1272 @@ +# Copyright (c) 2021 Project CHIP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//args.gni") +import("//build_overrides/bouffalolab_iot_sdk.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/mbedtls.gni") +import("${chip_root}/src/lib/lib.gni") + +declare_args() { + # Location of the bl616 SDK. + bouffalo_sdk_root = "${chip_root}/third_party/bouffalolab/bouffalo_sdk" + + enable_debug_coredump = false + coredump_binary_id = 0 + bouffalo_sdk_coredump_version = 1 +} + +assert(bouffalo_sdk_root != "", "bouffalo_sdk_root must be specified") + +# Defines an bl616 SDK build target. +# +# Parameters: +# bouffalo_sdk_root - The location of the bl616 SDK. +# sources - The sources files to build. +template("bouffalo_sdk") { + if (defined(invoker.bouffalo_sdk_root)) { + bouffalo_sdk_root = invoker.bouffalo_sdk_root + } + + assert(bouffalo_sdk_root != "", "bouffalo_sdk_root must be specified") + + sdk_target_name = target_name + + config("${sdk_target_name}_config") { + defines = [ + "BL616=BL616", + "ARCH_RISCV", + ] + + include_dirs = [] + if (defined(invoker.include_dirs)) { + include_dirs += invoker.include_dirs + } + + if (defined(invoker.defines)) { + defines += invoker.defines + } + + cflags_c = [ + "-fno-jump-tables", + "-fstrict-volatile-bitfields", + "-fshort-enums", + "-Wno-unused-but-set-variable", + ] + + cflags = [ + "-Wno-conversion", + "-fstack-usage", + ] + + if (defined(invoker.defines)) { + defines += invoker.defines + } + } + + config("${sdk_target_name}_config_startup") { + include_dirs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup" ] + } + + source_set("${sdk_target_name}_startup") { + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + "CONFIG_IRQ_NUM=80", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "CONFIG_COREDUMP" ] + } + + include_dirs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup" ] + + sources = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/interrupt.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/riscv_fpu.S", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/start.S", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/start_load.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/system_bl616.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/startup/vector.S", + ] + + configs += [ + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_startup", + ] + } + + config("${sdk_target_name}_config_std_drv") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include/hardware", + ] + + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + ] + + cflags = [ "-Wsign-compare" ] + } + + source_set("${sdk_target_name}_std_drv") { + defines = [ + "ARCH_RISCV", + "BFLB_USE_HAL_DRIVER", + "BFLB_USE_ROM_DRIVER", + ] + + include_dirs = [ + #bl616 startup + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/include/hardware", + ] + + sources = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/std/port/bl616_clock.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/port/bl616_gpio.c", + ] + + sources += [ + #use rom api default + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_clock.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_common.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_ef_cfg.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_efuse.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_flash.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_mfg_media.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_pm.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_psram.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_romapi_e907.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_romapi_patch.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_sdh.c", + "${bouffalo_sdk_root}/drivers/soc/bl616/std/src/bl616_tzc_sec.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-enum-conversion", + "-Wno-type-limits", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config", + ] + } + + config("${sdk_target_name}_config_lhal") { + include_dirs = [ + #bl616 lhal + "${bouffalo_sdk_root}/drivers/lhal/include", + "${bouffalo_sdk_root}/drivers/lhal/include/arch", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/Core/Include", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/csi_dsp/include", + "${bouffalo_sdk_root}/drivers/lhal/src/flash", + "${bouffalo_sdk_root}/drivers/lhal/config/bl616", + ] + } + + source_set("${sdk_target_name}_lhal") { + defines = [ + "CPU_M0", + "CONFIG_IRQ_NUM=80", + ] + + include_dirs = [ + #bl616 lhal + "${bouffalo_sdk_root}/drivers/lhal/include", + ] + + sources = [ + "${bouffalo_sdk_root}/drivers/lhal/config/bl616/device_table.c", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/rv_hart.c", + "${bouffalo_sdk_root}/drivers/lhal/include/arch/risc-v/t-head/rv_pmp.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_acomp.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_adc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_auadc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_audac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_cam.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_cks.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_common.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dbi.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_dma.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_ef_ctrl.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_emac.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_flash.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_gpio.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_i2c.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_i2s.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_ir.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_irq.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_l1c.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_mjpeg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_mtimer.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_pwm_v2.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_rtc.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sdio2.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_aes.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_sha.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_sec_trng.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_spi.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_timer.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_uart.c", + "${bouffalo_sdk_root}/drivers/lhal/src/bflb_wdg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sf_cfg.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sf_ctrl.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_sflash.c", + "${bouffalo_sdk_root}/drivers/lhal/src/flash/bflb_xip_sflash.c", + ] + + libs = [ "${bouffalo_sdk_root}/drivers/lhal/src/pka/libpka.a" ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + "-Wno-implicit-fallthrough", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-function", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lhal", + ] + } + + config("${sdk_target_name}_config_sys") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/sys", + "${bouffalo_sdk_root}/drivers/sys/bl616", + ] + } + + source_set("${sdk_target_name}_sys") { + defines = [ "BL_WIFI_LP_FW" ] + sources = [ + "${bouffalo_sdk_root}/drivers/sys/bl616/bl616_lp.c", + "${bouffalo_sdk_root}/drivers/sys/bl616/bl616_sys.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-shadow", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_sys", + ] + } + + config("${sdk_target_name}_config_board") { + include_dirs = [ "${bouffalo_sdk_root}/bsp/board" ] + } + + source_set("${sdk_target_name}_board") { + defines = [ + "CONFIG_MBEDTLS", + "CONFIG_BFLOG", + "BL616", + ] + + include_dirs = [ "${bouffalo_sdk_root}/bsp/board/bl616dk" ] + + sources = [ + "${bouffalo_sdk_root}/bsp/board/bl616dk/board.c", + "${bouffalo_sdk_root}/bsp/board/bl616dk/board_rf.c", + "${bouffalo_sdk_root}/bsp/board/bl616dk/fw_header.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-enum-conversion", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_rf", + ] + + public_configs = [ ":${sdk_target_name}_config_board" ] + } + + config("${sdk_target_name}_config_shell") { + include_dirs = [ "${bouffalo_sdk_root}/components/shell" ] + } + + source_set("${sdk_target_name}_shell") { + include_dirs = [ "${bouffalo_sdk_root}/bsp/board/bl616dk" ] + + sources = [ + "${bouffalo_sdk_root}/components/shell/shell.c", + "${bouffalo_sdk_root}/components/shell/shell_freertos.c", + ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-enum-conversion", + "-Wno-format-security", + "-Wno-format-truncation", + "-Wno-format-nonliteral", + "-Wno-sign-compare", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_board", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ] + public_configs = [ ":${sdk_target_name}_config_shell" ] + } + + config("${sdk_target_name}_config_rf") { + include_dirs = [ + "${bouffalo_sdk_root}/drivers/soc/bl616/phyrf/include", + "${bouffalo_sdk_root}/drivers/rfparam/Inc", + ] + + defines = [ "WL_BL616=1" ] + } + + source_set("${sdk_target_name}_rf") { + defines = [ "RFPARAM_BL616" ] + + include_dirs = [ "${bouffalo_sdk_root}/drivers/rfparam/Inc" ] + + sources = [ + "${bouffalo_sdk_root}/drivers/rfparam/Src/rfparam_adapter.c", + "${bouffalo_sdk_root}/drivers/rfparam/Src/rfparam_rftlv.c", + ] + + libs = [ "${bouffalo_sdk_root}/drivers/soc/bl616/phyrf/lib-gcc_10.2.0-toolchain_V2.6.1/libbl616_phyrf.a" ] + + cflags_c = [ + "-Wno-shadow", + "-Wno-sign-compare", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_rf", + ] + } + + source_set("${sdk_target_name}_libc") { + include_dirs = [ "${bouffalo_sdk_root}/components/libc" ] + + sources = [ + "${bouffalo_sdk_root}/components/libc/newlib/port_init_fini.c", + "${bouffalo_sdk_root}/components/libc/newlib/port_memory.c", + "${bouffalo_sdk_root}/components/libc/newlib/syscalls_nosys.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_abs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atof.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atoi.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atol.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_atoll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_bsearch.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_checkbase.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_itoa.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_llabs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_lldiv.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_qsort.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/stdlib/lib_strtod.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffs.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffsl.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_ffsll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_fls.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_flsl.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_flsll.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_index.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memccpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memcmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memmove.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memrchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_memset.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_stpcpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_stpncpy.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcasecmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcasestr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcat.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strchr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcmp.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strcspn.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strdup.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strnlen.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strpbrk.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strsep.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strspn.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strstr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtok.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_strtokr.c", + "${bouffalo_sdk_root}/components/libc/nuttx/libc/string/lib_vikmemcpy.c", + "${bouffalo_sdk_root}/components/libc/printf.c", + "${bouffalo_sdk_root}/components/libc/snprintf.c", + "${bouffalo_sdk_root}/components/libc/sprintf.c", + "${bouffalo_sdk_root}/components/libc/stdatomic.c", + "${bouffalo_sdk_root}/components/libc/vsnprintf.c", + "${bouffalo_sdk_root}/components/libc/vsprintf.c", + ] + + cflags = [ + "-fno-builtin", + "-Wno-sign-compare", + "-Wno-implicit-fallthrough", + "-Wno-builtin-declaration-mismatch", + ] + configs += [ + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_lhal", + ] + public_configs = [ ":${sdk_target_name}_config" ] + } + + config("${sdk_target_name}_config_freertos") { + defines = [ + "CONFIG_FREERTOS", + "configSTACK_ALLOCATION_FROM_SEPARATE_HEAP=1", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/os/freertos/include", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/chip_specific_extensions/RV32I_CLINT_no_extensions", + + #"${bouffalo_sdk_root}/components/os/freertos/posix/include", + "${chip_root}/examples/platform/bouffalolab/bl616", + ] + } + + source_set("${sdk_target_name}_freertos") { + defines = [ + "portasmHANDLE_INTERRUPT=interrupt_entry", + "default_interrupt_handler=freertos_risc_v_trap_handler", + + #"CONFIG_POSIX", + ] + + include_dirs = [ + #memory heap + "${bouffalo_sdk_root}/components/os/freertos/include", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/chip_specific_extensions/RV32I_CLINT_no_extensions", + ] + + sources = [ + "${bouffalo_sdk_root}/components/os/freertos/croutine.c", + "${bouffalo_sdk_root}/components/os/freertos/event_groups.c", + "${bouffalo_sdk_root}/components/os/freertos/freertos_port.c", + "${bouffalo_sdk_root}/components/os/freertos/list.c", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/port.c", + "${bouffalo_sdk_root}/components/os/freertos/portable/GCC/RISC-V/common/portASM.S", + "${bouffalo_sdk_root}/components/os/freertos/portable/MemMang/heap_3.c", + "${bouffalo_sdk_root}/components/os/freertos/queue.c", + "${bouffalo_sdk_root}/components/os/freertos/tasks.c", + "${bouffalo_sdk_root}/components/os/freertos/timers.c", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_freertos", + ] + } + + config("${sdk_target_name}_config_mm") { + include_dirs = [ + "${bouffalo_sdk_root}/components/mm", + "${bouffalo_sdk_root}/components/mm/tlsf", + ] + } + + source_set("${sdk_target_name}_mm") { + defines = [ + "configSTACK_ALLOCATION_FROM_SEPARATE_HEAP=1", + "CONFIG_TLSF", + ] + + include_dirs = [ + #memory heap + "${bouffalo_sdk_root}/components/mm", + "${bouffalo_sdk_root}/components/mm/tlsf", + ] + + sources = [ + "${bouffalo_sdk_root}/components/mm/mem.c", + "${bouffalo_sdk_root}/components/mm/tlsf/bflb_tlsf.c", + "${bouffalo_sdk_root}/components/mm/tlsf/tlsf.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_mm", + ] + } + + config("${sdk_target_name}_config_easyflash4") { + include_dirs = [ "${bouffalo_sdk_root}/components/easyflash4/inc" ] + } + + source_set("${sdk_target_name}_easyflash4") { + defines = [ + "CONFIG_EASYFLASH4", + "BL616", + "EF_ENV_CACHE_TABLE_SIZE=100", + ] + + include_dirs = [ "${bouffalo_sdk_root}/components/easyflash4/inc" ] + + sources = [ + "${bouffalo_sdk_root}/components/easyflash4/src/easyflash.c", + "${bouffalo_sdk_root}/components/easyflash4/src/easyflash_cli.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env_legacy.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_env_legacy_wl.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_port.c", + "${bouffalo_sdk_root}/components/easyflash4/src/ef_utils.c", + ] + + cflags_c = [ "-Wno-sign-compare" ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ ":${sdk_target_name}_config_easyflash4" ] + } + + config("${sdk_target_name}_config_littlefs") { + include_dirs = [ + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs", + "${bouffalo_sdk_root}/components/fs/littlefs/port", + ] + + defines = [ "LFS_THREADSAFE" ] + } + + source_set("${sdk_target_name}_littlefs") { + defines = [ + "CONFIG_LITTLEFS", + "CONFIG_FREERTOS", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs", + "${bouffalo_sdk_root}/components/fs/littlefs/port", + ] + + sources = [ + "${bouffalo_sdk_root}/components/fs/littlefs/easyflash_port/lfs_easyflash.c", + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs/lfs.c", + "${bouffalo_sdk_root}/components/fs/littlefs/littlefs/lfs_util.c", + "${bouffalo_sdk_root}/components/fs/littlefs/port/lfs_xip_flash.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-shadow", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_littlefs", + ] + } + + config("${sdk_target_name}_config_utils") { + include_dirs = [ + "${bouffalo_sdk_root}/components/utils/log", + "${bouffalo_sdk_root}/components/utils/log/bflog", + "${bouffalo_sdk_root}/components/utils/bflb_mtd/include", + "${bouffalo_sdk_root}/components/utils/bflb_ota", + "${bouffalo_sdk_root}/components/utils/coredump", + "${bouffalo_sdk_root}/components/utils/partition", + "${bouffalo_sdk_root}/components/utils/getopt", + "${bouffalo_sdk_root}/components/utils/ring_buffer", + "${bouffalo_sdk_root}/components/utils/math/include", + "${bouffalo_sdk_root}/components/utils/list", + ] + + defines = [ + "CONFIG_LOG_LEVEL=0", + "CONFIG_BFLOG", + "CONFIG_BFLOG_DEBUG", + ] + } + + source_set("${sdk_target_name}_utils") { + defines = [ + "CONFIG_LOG_LEVEL=0", + "CONFIG_BFLOG", + "CONFIG_BFLOG_DEBUG", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + defines += [ "CONFIG_COREDUMP" ] + } + + sources = [ + "${bouffalo_sdk_root}/components/utils/bflb_mtd/bflb_boot2.c", + "${bouffalo_sdk_root}/components/utils/bflb_mtd/bflb_mtd.c", + "${bouffalo_sdk_root}/components/utils/bflb_ota/bflb_ota.c", + "${bouffalo_sdk_root}/components/utils/bflb_ota/utils_sha256.c", + "${bouffalo_sdk_root}/components/utils/getopt/utils_getopt.c", + "${bouffalo_sdk_root}/components/utils/log/bflog/bflog.c", + "${bouffalo_sdk_root}/components/utils/log/log.c", + "${bouffalo_sdk_root}/components/utils/log/log_freertos.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_base64.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_crc.c", + "${bouffalo_sdk_root}/components/utils/math/src/utils_hex.c", + "${bouffalo_sdk_root}/components/utils/partition/partition.c", + "${bouffalo_sdk_root}/components/utils/ring_buffer/ring_buffer.c", + ] + + if (defined(invoker.enable_debug_coredump) && + invoker.enable_debug_coredump) { + if (bouffalo_sdk_coredump_version == 1) { + sources += [ + "${bouffalo_sdk_root}/components/utils/coredump/bin_fmt_v1.c", + "${bouffalo_sdk_root}/components/utils/coredump/coredump.c", + "${bouffalo_sdk_root}/components/utils/coredump/encoder_v1.c", + ] + } else if (bouffalo_sdk_coredump_version == 2) { + sources += [ + "${bouffalo_sdk_root}/components/utils/coredump/bin_fmt_v2.c", + "${bouffalo_sdk_root}/components/utils/coredump/coredump.c", + "${bouffalo_sdk_root}/components/utils/coredump/encoder_v2.c", + ] + } + } + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-type-limits", + "-Wno-stringop-truncation", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-implicit-function-declaration", + ] + + configs += [ + ":${sdk_target_name}_config_startup", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ] + } + + config("${sdk_target_name}_config_mbedtls") { + include_dirs = [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/include", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port", + ] + + defines = [ "MBEDTLS_CONFIG_FILE=\"bl616-chip-mbedtls-config.h\"" ] + } + + source_set("${sdk_target_name}_mbedtls") { + defines = [ "CONFIG_FREERTOS" ] + + include_dirs = + [ "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library" ] + + sources = [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/aes_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/bignum_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/bignum_ext.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/ecp_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/ecp_curves_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha1_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha256_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/hw_acc/sha512_alt.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/bignum.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/entropy_poll_alt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/net_sockets.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/port/sec_mutex.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/poly1305.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/ripemd160.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/rsa.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls//library/rsa_internal.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aes.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aesni.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/arc4.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/aria.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/asn1parse.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/asn1write.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/base64.c", + + # "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/bignum.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/blowfish.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/camellia.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ccm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/certs.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/chacha20.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/chachapoly.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cipher.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cipher_wrap.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/cmac.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/constant_time.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ctr_drbg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/debug.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/des.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/dhm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecdh.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecdsa.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecjpake.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecp.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ecp_curves.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/entropy.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/entropy_poll.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/error.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/gcm.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/havege.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/hkdf.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/hmac_drbg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md2.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md4.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/md5.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/memory_buffer_alloc.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/mps_reader.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/mps_trace.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/nist_kw.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/oid.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/padlock.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pem.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pk.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pk_wrap.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs11.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs12.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkcs5.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkparse.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/pkwrite.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/platform.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/platform_util.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha1.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha256.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/sha512.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cache.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_ciphersuites.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cli.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_cookie.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_msg.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_srv.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_ticket.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_tls.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/ssl_tls13_keys.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/threading.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/timing.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/version.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/version_features.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_create.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_crl.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_crt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509_csr.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509write_crt.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/x509write_csr.c", + "${bouffalo_sdk_root}/components/crypto/mbedtls/mbedtls/library/xtea.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-security", + "-Wno-format-nonliteral", + ] + + configs += [ + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_lwip", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_mbedtls", + ] + } + + config("${sdk_target_name}_config_lwip") { + include_dirs = [ + "${bouffalolab_iot_sdk_build_root}/bl616", + "${bouffalo_sdk_root}/components/net/lwip/lwip/system", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/include", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/compat/posix", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/include/compat/posix", + "${bouffalo_sdk_root}/components/net/lwip/lwip/lwip-port", + ] + + include_dirs += + [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd" ] + + defines = [ + "CONFIG_LWIP", + "CONFIG_MAC_TXQ_DEPTH=8", + "CONFIG_MAC_RXQ_DEPTH=8", + ] + } + + source_set("${sdk_target_name}_lwip") { + sources = [ + "${bouffalo_sdk_root}/components/net/lwip/lwip/lwip-port/FreeRTOS/sys_arch.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/api_lib.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/api_msg.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/err.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netbuf.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netdb.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/netifapi.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/sockets.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/api/tcpip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/http/fs.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/mdns/mdns.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/def.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/dns.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/inet_chksum.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/init.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/autoip.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/dhcp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/etharp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/icmp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/igmp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4_addr.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv4/ip4_frag.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/dhcp6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ethip6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/icmp6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/inet6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_addr.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_frag.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/mld6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/nd6.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/memp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/netif.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/pbuf.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/raw.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/stats.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/sys.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp_in.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/tcp_out.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/timeouts.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/udp.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/netif/ethernet.c", + ] + + sources += [ + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd/dhcp_server_raw.c", + "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/lwiperf/lwiperf.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-unused-variable", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_wifi", + ] + + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_lwip", + ] + } + + config("${sdk_target_name}_config_wifi") { + defines = [ + "CFG_VIF_MAX=2", + "CFG_STA_MAX=4", + "CFG_UMAC", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/wifi6/include", + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/include", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/include", + ] + } + + source_set("${sdk_target_name}_wifi") { + defines = [ "CFG_IPV6" ] + libs = [ "${bouffalo_sdk_root}/components/wireless/wifi6/lib/libwifi6.a" ] + + include_dirs = + [ "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter" ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/src/platform_bouffalo_sdk.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/bl6_os_adapter/src/rtos_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/cli_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/mat.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/net_al.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/net_al_ext.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/pbuf_custom_ref.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/tx_buffer_copy.c", + "${bouffalo_sdk_root}/components/wireless/wifi6/wifi6_lwip_adapter/wifi_pkt_hooks.c", + ] + + cflags_c = [ + "-Wno-error", + "-Wno-sign-compare", + "-Wno-int-conversion", + "-Wno-shadow", + "-Wno-incompatible-pointer-types", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-discarded-qualifiers", + "-Wno-format-security", + ] + + configs += [ + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_shell", + ":${sdk_target_name}_config_freertos", + ":${sdk_target_name}_config_lwip", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_wifi", + ] + } + + config("${sdk_target_name}_config_ble") { + defines = [ + "BFLB_BLE", + "CONFIG_BT_CONN=1", + + "CONFIG_SET_TX_PWR", + "CFG_CON=1", + "CFG_BLE", + "CFG_SLEEP", + "CFG_BT_RESET", + "CONFIG_BT_PERIPHERAL=1", + "CFG_BLE_TX_BUFF_DATA=2", + "CONFIG_BT_GATT_DYNAMIC_DB", + "CONFIG_BT_GATT_SERVICE_CHANGED", + "CONFIG_BT_SETTINGS_CCC_LAZY_LOADING", + "CONFIG_BT_KEYS_OVERWRITE_OLDEST", + "CONFIG_BT_GAP_PERIPHERAL_PREF_PARAMS", + "CONFIG_BT_BONDABLE", + "CONFIG_BT_ASSERT", + "CFG_BLE_STACK_DBG_PRINT", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/btblecontroller/btble_inc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include/bluetooth", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/port/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/zephyr", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/misc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/include/drivers/bluetooth", + ] + } + + source_set("${sdk_target_name}_ble") { + defines = [ + "CONFIG_BT_L2CAP_DYNAMIC_CHANNEL", + "CONFIG_BT_GATT_CLIENT", + "CONFIG_BT_CONN=1", + "CONFIG_BT_GATT_DIS_PNP", + "CONFIG_BT_GATT_DIS_SERIAL_NUMBER", + "CONFIG_BT_GATT_DIS_FW_REV", + "CONFIG_BT_GATT_DIS_HW_REV", + "CONFIG_BT_GATT_DIS_SW_REV", + "CONFIG_BT_ECC", + "CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING", + "CONFIG_BT_HCI_VS_EVT_USER", + "CONFIG_BT_SETTINGS_USE_PRINTK", + "CONFIG_BLE_MULTI_ADV", + ] + + libs = [ "${bouffalo_sdk_root}/components/wireless/bluetooth/btblecontroller/lib/libbtblecontroller_bl616_ble1m0s1bredr0.a" ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/bl_hci_wrapper", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/include/misc", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/tinycrypt/include/tinycrypt", + ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/bl_hci_wrapper/bl_hci_wrapper.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/atomic_c.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/buf.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/dec.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/log.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/poll.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/common/work_q.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/hci_onchip/hci_driver.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/att.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/bl_host_assist.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/conn.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/crypto.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/gatt.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/hci_core.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/l2cap.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/multi_adv.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/settings.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/host/uuid.c", + "${bouffalo_sdk_root}/components/wireless/bluetooth/blestack/src/port/bl_port.c", + ] + + cflags_c = [ + "-Wno-sign-compare", + "-Wno-implicit-function-declaration", + "-Wno-format", + "-Wno-format-nonliteral", + "-Wno-format-security", + "-Wno-discarded-qualifiers", + "-Wno-misleading-indentation", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_freertos", + ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_ble", + ] + } + + config("${sdk_target_name}_config_openthread_port") { + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/include", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_utils/include", + ] + } + + source_set("${sdk_target_name}_openthread_port") { + import("//build_overrides/openthread.gni") + + defines = [ + "CONFIG_BL_SDK", + "CHIP_HDR=", + "CHIP_GLB_HDR=", + "MAC_ADDRESS_MAX_NUM=3", + ] + + include_dirs = [ + "${bouffalo_sdk_root}/components/wireless/lmac154/lmac154/include", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port", + ] + + sources = [ + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_alarm_bl616.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_radio.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_radio_bflb.c", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_sys_bflb.c", + ] + + if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && + invoker.bouffalo_sdk_component_easyflash_enabled) { + sources += [ "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_settings_easyflash.c" ] + } else { + sources += [ "${bouffalo_sdk_root}/components/wireless/thread/openthread_port/ot_settings_littlefs.c" ] + } + + libs = [ + "${bouffalo_sdk_root}/components/wireless/lmac154/lmac154/lib/liblmac154.a", + "${bouffalo_sdk_root}/components/wireless/thread/openthread_utils/lib/libopenthread_utils.a", + ] + + cflags_c = [ "-Wno-sign-compare" ] + + configs += [ ":${sdk_target_name}_config_freertos" ] + public_configs = [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_utils", + ":${sdk_target_name}_config_mm", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_shell", + ":${sdk_target_name}_config_littlefs", + ":${sdk_target_name}_config_openthread_port", + ] + + public_deps = [ + "${chip_root}/third_party/openthread/platforms:libopenthread-platform-utils", + "${openthread_root}/src/core:libopenthread_core_headers", + ] + } + + config("${sdk_target_name}_config_factory_data") { + include_dirs = + [ "${bouffalo_sdk_root}/components/wireless/matter/mfd/include" ] + } + + source_set("${sdk_target_name}_factory_data") { + defines = [ "BL_MFD_PLAT_H=\"bl_mfd_bl616.h\"" ] + sources = [ + "${bouffalo_sdk_root}/components/wireless/matter/mfd/bl_mfd.c", + "${bouffalo_sdk_root}/components/wireless/matter/mfd/bl_mfd_decrypt_bl616.c", + ] + + configs += [ + ":${sdk_target_name}_config", + ":${sdk_target_name}_config_std_drv", + ":${sdk_target_name}_config_lhal", + ":${sdk_target_name}_config_utils", + ] + public_configs = [ ":${sdk_target_name}_config_factory_data" ] + } + + group(sdk_target_name) { + public_deps = [ + ":${sdk_target_name}_board", + ":${sdk_target_name}_freertos", + ":${sdk_target_name}_lhal", + ":${sdk_target_name}_libc", + ":${sdk_target_name}_mbedtls", + ":${sdk_target_name}_mm", + ":${sdk_target_name}_rf", + ":${sdk_target_name}_shell", + ":${sdk_target_name}_startup", + ":${sdk_target_name}_std_drv", + ":${sdk_target_name}_sys", + ":${sdk_target_name}_utils", + ] + + if (defined(invoker.bouffalo_sdk_component_easyflash_enabled) && + invoker.bouffalo_sdk_component_easyflash_enabled) { + public_deps += [ ":${sdk_target_name}_easyflash4" ] + } else { + public_deps += [ ":${sdk_target_name}_littlefs" ] + } + + if (defined(invoker.chip_enable_wifi) && invoker.chip_enable_wifi) { + public_deps += [ ":${sdk_target_name}_wifi" ] + public_deps += [ ":${sdk_target_name}_lwip" ] + } else if (defined(invoker.chip_enable_openthread) && + invoker.chip_enable_openthread) { + public_deps += [ ":${sdk_target_name}_openthread_port" ] + } + + if (defined(invoker.chip_config_network_layer_ble) && + invoker.chip_config_network_layer_ble) { + public_deps += [ ":${sdk_target_name}_ble" ] + } + + if (defined(invoker.chip_enable_factory_data) && + invoker.chip_enable_factory_data) { + public_deps += [ ":${sdk_target_name}_factory_data" ] + } + } +} diff --git a/third_party/bouffalolab/common/bouffalolab_executable.gni b/third_party/bouffalolab/common/bouffalolab_executable.gni index 105a8dc2fe48e4..491cb49cdf50ed 100644 --- a/third_party/bouffalolab/common/bouffalolab_executable.gni +++ b/third_party/bouffalolab/common/bouffalolab_executable.gni @@ -21,12 +21,15 @@ import("${build_root}/toolchain/flashable_executable.gni") template("bouffalolab_executable") { output_base_name = get_path_info(invoker.output_name, "name") - objcopy_image_name = output_base_name + ".bin" objcopy_image_format = "binary" objcopy = "riscv64-unknown-elf-objcopy" if ("linux" == host_os) { - objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-objcopy" + if (invoker.bl_plat_name == "bl616") { + objcopy = "${bouffalolab_sdk_root}/toolchain/t-head-riscv/gcc_t-head_v2.6.1/bin/riscv64-unknown-elf-objcopy" + } else { + objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Linux/bin/riscv64-unknown-elf-objcopy" + } } else if ("mac" == host_os || "darwin" == host_os) { objcopy = "${bouffalolab_sdk_root}/toolchain/riscv/Darwin/bin/riscv64-unknown-elf-objcopy" } @@ -46,17 +49,30 @@ template("bouffalolab_executable") { } flashing_config_target = target_name + ".config" + if (invoker.bl_plat_name == "bl616") { + objcopy_image_name = output_base_name + ".raw" + flashing_config_inputs = [ + "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml", + "${chip_root}/third_party/bouffalolab/bouffalo_sdk/bsp/board/bl616dk/config/bl_factory_params_IoTKitA_auto.dts", + "${chip_root}/third_party/bouffalolab/bouffalo_sdk/bsp/board/bl616dk/config/boot2_bl616_isp_release_v8.1.6.bin", + ] - objcopy_image_name = output_base_name + ".bin" - if (invoker.bl_plat_name == "bl602") { - flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml" ] + copy(flashing_config_target) { + sources = flashing_config_inputs + outputs = [ "${root_out_dir}/config/{{source_file_part}}" ] + } } else { - flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_2M.toml" ] - } + objcopy_image_name = output_base_name + ".bin" + if (invoker.bl_plat_name == "bl602") { + flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_4M.toml" ] + } else { + flashing_config_inputs = [ "${chip_root}/examples/platform/bouffalolab/${invoker.bl_plat_name}/flash_config/partition_cfg_2M.toml" ] + } - copy(flashing_config_target) { - sources = flashing_config_inputs - outputs = [ "${root_out_dir}/{{source_file_part}}" ] + copy(flashing_config_target) { + sources = flashing_config_inputs + outputs = [ "${root_out_dir}/{{source_file_part}}" ] + } } flashing_script_generator = @@ -66,27 +82,34 @@ template("bouffalolab_executable") { flashing_options += [ "--chipname" ] flashing_options += [ "${invoker.bl_plat_name}" ] - flashing_options += [ "--xtal" ] - if (invoker.bl_plat_name == "bl602") { - flashing_options += [ "40M" ] - } else if (invoker.bl_plat_name == "bl702") { - flashing_options += [ "32M" ] - } else if (invoker.bl_plat_name == "bl702l") { - flashing_options += [ "32M" ] - } - - flashing_options += [ "--pt" ] - if (invoker.bl_plat_name == "bl602") { - flashing_options += - [ rebase_path("partition_cfg_4M.toml", root_out_dir, root_out_dir) ] - } else if (defined(invoker.enable_openthread_border_router) && - invoker.enable_openthread_border_router) { - flashing_options += [ rebase_path("partition_cfg_2M_noOTA.toml", - root_out_dir, - root_out_dir) ] + if (invoker.bl_plat_name == "bl616") { + flashing_options += [ + "--config", + "${root_out_dir}/flash_prog_cfg.ini", + ] } else { - flashing_options += - [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] + flashing_options += [ "--xtal" ] + if (invoker.bl_plat_name == "bl602") { + flashing_options += [ "40M" ] + } else if (invoker.bl_plat_name == "bl702") { + flashing_options += [ "32M" ] + } else if (invoker.bl_plat_name == "bl702l") { + flashing_options += [ "32M" ] + } + + flashing_options += [ "--pt" ] + if (invoker.bl_plat_name == "bl602") { + flashing_options += + [ rebase_path("partition_cfg_4M.toml", root_out_dir, root_out_dir) ] + } else if (defined(invoker.enable_openthread_border_router) && + invoker.enable_openthread_border_router) { + flashing_options += [ rebase_path("partition_cfg_2M_noOTA.toml", + root_out_dir, + root_out_dir) ] + } else { + flashing_options += + [ rebase_path("partition_cfg_2M.toml", root_out_dir, root_out_dir) ] + } } # set 2000000 baudrate for image download by default diff --git a/third_party/bouffalolab/common/rsicv.gni b/third_party/bouffalolab/common/rsicv.gni index fea2acd4d10100..25b5c78bc99f1e 100644 --- a/third_party/bouffalolab/common/rsicv.gni +++ b/third_party/bouffalolab/common/rsicv.gni @@ -17,5 +17,10 @@ import("//build_overrides/chip.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/platform/device.gni") -riscv_arch = "rv32imfc" +if (chip_device_platform == "bl616") { + riscv_arch = "rv32imafcpzpsfoperand_xtheade" +} else { + riscv_arch = "rv32imfc" +} + riscv_abi = "ilp32f"