From bc328657aa6936550031a5478ba0d26604a74c13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kuba=20Szczodrzy=C5=84ski?= Date: Sat, 4 Mar 2023 11:09:27 +0100 Subject: [PATCH] [beken-72xx] Update base core to new structure --- TODO.md | 1 + builder/family/beken-72xx.py | 13 ++- builder/family/realtek-ambz.py | 1 - builder/frameworks/arduino.py | 51 +++++----- builder/frameworks/base.py | 92 ++++++++++--------- builder/utils/config.py | 8 +- builder/utils/cores.py | 29 +++--- builder/utils/env.py | 7 +- cores/beken-72xx/arduino/libraries/LT/LT.cpp | 26 ------ cores/beken-72xx/arduino/src/ArduinoFamily.h | 11 --- cores/beken-72xx/arduino/src/lt_defs.h | 5 +- cores/beken-72xx/base/fixups/.clang-format | 2 + cores/beken-72xx/base/fixups/arch_main.c | 4 +- cores/beken-72xx/base/fixups/param_config.h | 4 +- cores/beken-72xx/base/fixups/uart_pub.h | 6 +- cores/beken-72xx/base/lt_defs.h | 3 + cores/beken-72xx/base/lt_family.h | 12 +++ cores/beken-72xx/base/lt_family_api.c | 29 ++++++ .../base/port/fal_flash_bk72xx_port.c | 5 +- cores/beken-72xx/base/port/printf.c | 5 +- cores/beken-72xx/base/port/printf_port.h | 8 ++ cores/beken-72xx/base/sdk_mem.h | 20 ---- cores/beken-72xx/base/sdk_private.h | 12 +-- cores/common/arduino/libraries/api/LT/LT.cpp | 7 ++ cores/common/arduino/libraries/api/LT/LT.h | 17 +--- cores/common/arduino/src/Arduino.h | 57 ++++++++++++ cores/common/arduino/src/SerialExtern.h | 25 ----- cores/common/arduino/src/main.c | 39 ++++++++ ...{LibreTuyaCompat.cpp => wiring_compat.cpp} | 8 +- .../{LibreTuyaCompat.h => wiring_compat.h} | 4 + cores/common/arduino/src/wiring_custom.c | 24 ++++- cores/common/arduino/src/wiring_custom.h | 25 +---- cores/common/base/config/fal_cfg.h | 10 +- cores/common/base/config/fdb_cfg.h | 3 +- cores/common/base/config/printf_config.h | 10 +- cores/common/base/{lt_api.h => libretuya.h} | 60 +++--------- cores/common/base/lt_chip.h | 8 +- .../common/base/{lt_api.c => lt_common_api.c} | 14 +-- cores/common/base/lt_common_api.h | 35 +++++++ cores/common/base/lt_family_api.h | 18 ++++ cores/common/base/lt_logger.c | 34 ++++++- cores/common/base/lt_logger.h | 11 ++- cores/common/base/lt_main.c | 64 ++----------- cores/common/base/lt_posix_api.h | 2 + cores/common/base/lt_types.h | 15 +++ cores/common/base/posix/strdup.c | 3 +- cores/common/base/strptime.h | 7 -- cores/realtek-amb/arduino/libraries/LT/LT.cpp | 4 - cores/realtek-amb/arduino/src/lt_defs.h | 1 + cores/realtek-amb/base/lt_family_api.c | 7 ++ .../base/port/fal_flash_ambz_port.c | 4 +- cores/realtek-amb/base/port/printf.c | 5 +- cores/realtek-amb/base/port/printf_port.h | 8 ++ cores/realtek-amb/base/sdk_mem.h | 2 - cores/realtek-amb/base/sdk_private.h | 4 +- cores/realtek-amb/lt_defs.h | 7 ++ cores/realtek-ambz/base/fixups/.clang-format | 2 + .../base/fixups/app_start_patch.c | 4 +- 58 files changed, 510 insertions(+), 392 deletions(-) create mode 100644 cores/beken-72xx/base/fixups/.clang-format create mode 100644 cores/beken-72xx/base/lt_family.h create mode 100644 cores/beken-72xx/base/lt_family_api.c delete mode 100644 cores/beken-72xx/base/sdk_mem.h create mode 100644 cores/common/arduino/src/Arduino.h delete mode 100644 cores/common/arduino/src/SerialExtern.h create mode 100644 cores/common/arduino/src/main.c rename cores/common/arduino/src/{LibreTuyaCompat.cpp => wiring_compat.cpp} (80%) rename cores/common/arduino/src/{LibreTuyaCompat.h => wiring_compat.h} (95%) rename cores/common/base/{lt_api.h => libretuya.h} (57%) rename cores/common/base/{lt_api.c => lt_common_api.c} (83%) create mode 100644 cores/common/base/lt_common_api.h create mode 100644 cores/common/base/lt_family_api.h create mode 100644 cores/common/base/lt_types.h delete mode 100644 cores/common/base/strptime.h create mode 100644 cores/realtek-amb/base/lt_family_api.c create mode 100644 cores/realtek-amb/lt_defs.h create mode 100644 cores/realtek-ambz/base/fixups/.clang-format diff --git a/TODO.md b/TODO.md index 7017d3a..966794b 100644 --- a/TODO.md +++ b/TODO.md @@ -11,6 +11,7 @@ Developers wanting to use SDK functions need to include them. Explicit is better than implicit. - consider moving to C++17 (GNU)? or any newer than C++11 +- wrap all memory management functions (malloc, calloc, free, memset, etc.) and their vendor SDK counterparts to use FreeRTOS instead ### New families diff --git a/builder/family/beken-72xx.py b/builder/family/beken-72xx.py index b99ae7b..458faa9 100644 --- a/builder/family/beken-72xx.py +++ b/builder/family/beken-72xx.py @@ -2,7 +2,6 @@ from os.path import join -from ltchiptool.soc.bk72xx.binary import to_offset from platformio.platform.board import PlatformBoardConfig from SCons.Script import DefaultEnvironment, Environment @@ -50,7 +49,6 @@ env.Append( "-fno-strict-aliasing", "-fsigned-char", "-Wno-comment", - "-Werror=implicit-function-declaration", "-Wno-write-strings", "-Wno-char-subscripts", "-Wno-missing-braces", @@ -78,8 +76,6 @@ env.Append( ("WOLFSSL_BEKEN", env.Cfg("CFG_WPA3")), "MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED", ("INCLUDE_xTaskGetHandle", "1"), - # mbedtls_net_set_nonblock is commented out in tls_net.c - ("mbedtls_net_set_nonblock", "net_set_nonblock"), ], ASFLAGS=[ "-mcpu=arm968e-s", @@ -95,7 +91,6 @@ env.Append( "-marm", "-mthumb-interwork", "-g", - "-nostartfiles", "--specs=nano.specs", "-Wl,--gc-sections", "-Wl,-wrap,_free_r", @@ -204,9 +199,8 @@ env.AddLibrary( "+", "+", "+", - "+", + "+", "+", - "ARDUINO" in env and "-", ], includes=[ "+", @@ -543,6 +537,11 @@ env.Replace( SIZEPRINTCMD="$SIZETOOL -B -d $SOURCES", ) + +def to_offset(addr: int) -> int: + return int(addr + (addr // 32) * 2) + + # Calculate RBL header offset app_offs = int(env["FLASH_APP_OFFSET"], 16) app_size = int(board.get("build.bkrbl_size_app"), 16) diff --git a/builder/family/realtek-ambz.py b/builder/family/realtek-ambz.py index 51afaab..bed7f69 100644 --- a/builder/family/realtek-ambz.py +++ b/builder/family/realtek-ambz.py @@ -52,7 +52,6 @@ env.Append( "-mfpu=fpv4-sp-d16", "-g", "--specs=nano.specs", - "-nostartfiles", "-Os", "-Wl,--gc-sections", "-Wl,--cref", diff --git a/builder/frameworks/arduino.py b/builder/frameworks/arduino.py index f124d9c..fa7874d 100644 --- a/builder/frameworks/arduino.py +++ b/builder/frameworks/arduino.py @@ -13,6 +13,28 @@ env["ARDUINO"] = True # Add base cores' sources first env.SConscript("base.py") +# Flags & linker options +env.Append( + CPPDEFINES=[ + ("LIBRETUYA_ARDUINO", 1), + ("ARDUINO", 10812), + ("ARDUINO_SDK", 1), + ("ARDUINO_ARCH_${FAMILY_CODE}", 1), + ], + LINKFLAGS=[ + "--specs=nosys.specs", + "-Wl,--as-needed", + "-Wl,--build-id=none", + "-Wl,--cref", + "-Wl,--no-enum-size-warning", + "-Wl,--no-undefined", + "-Wl,--warn-common", + # wrappers from posix/time.c + "-Wl,-wrap,gettimeofday", + "-Wl,-wrap,settimeofday", + ], +) + family: Family = env["FAMILY_OBJ"] # Add common sources among all families @@ -52,35 +74,8 @@ env.AddLibrary( srcs=[ "+", ], - includes=[ - "!<.>", - ], + # not adding includes since they're added in base.py ) -# Flags & linker options -env.Append( - CPPDEFINES=[ - ("LIBRETUYA_ARDUINO", 1), - ("ARDUINO", 10812), - ("ARDUINO_SDK", 1), - ("ARDUINO_ARCH_${FAMILY_CODE}", 1), - ], - LINKFLAGS=[ - "--specs=nosys.specs", - "-Wl,--as-needed", - "-Wl,--build-id=none", - "-Wl,--cref", - "-Wl,--no-enum-size-warning", - "-Wl,--no-undefined", - "-Wl,--warn-common", - # wrappers from posix/time.c - "-Wl,-wrap,gettimeofday", - "-Wl,-wrap,settimeofday", - ], -) -# Arduino core uses __libc_init_array -if "-nostartfiles" in env["LINKFLAGS"]: - env["LINKFLAGS"].remove("-nostartfiles") - # Build all libraries env.BuildLibraries() diff --git a/builder/frameworks/base.py b/builder/frameworks/base.py index 42c70d5..e97fe23 100644 --- a/builder/frameworks/base.py +++ b/builder/frameworks/base.py @@ -14,55 +14,15 @@ board: PlatformBoardConfig = env.BoardConfig() platform: PlatformBase = env.PioPlatform() # Environment variables, include paths, etc. -env.ConfigureEnvironment(platform, board) -family: Family = env["FAMILY_OBJ"] - +family: Family = env.ConfigureEnvironment(platform, board) # Flash layout defines env.AddFlashLayout(board) -# Configure each family first (add CPP defines, prepend fixups' paths) -for f in family.inheritance: - path = env.AddFamily(f) - env.AddCoreConfig(name=f.code, path=join(path, "base")) - if "ARDUINO" in env: - env.AddCoreConfig(name=f"{f.code}_arduino", path=join(path, "arduino", "src")) - -# Include SDK builder scripts -# The script will call BuildLibraries(safe=True) to secure the include paths -found = False -for f in family.inheritance: - try: - env.SConscript(f"../family/{f.name}.py", must_exist=True) - found = True - except UserError: - pass - -# Fail if no SDK builder was found -if not found: - click.secho( - f"Platform '{family.name}' is currently not supported - " - "no SDK builder script could be found.", - fg="red", - ) - exit(1) - -# Add common sources among all families -env.AddCoreSources( - name="common", - path=join("$COMMON_DIR", "base"), -) -# Add sources for this family and each parent -for f in family.inheritance: - path = join("$CORES_DIR", f.name, "base") - env.AddCoreSources(name=f.code, path=path) - -# Sources - external libraries -env.AddExternalLibrary("ltchiptool") # uf2ota source code -env.AddExternalLibrary("flashdb") -env.AddExternalLibrary("printf") - # Flags & linker options env.Append( + CFLAGS=[ + "-Werror=implicit-function-declaration", + ], CPPDEFINES=[ ("LIBRETUYA", 1), ("LT_VERSION", env.ReadLTVersion(platform.get_dir(), platform.version)), @@ -71,6 +31,9 @@ env.Append( ("MCU", "${MCU}"), ("FAMILY", "F_${FAMILY}"), ], + CPPPATH=[ + "$BOARD_DIR", + ], LINKFLAGS=[ '"-Wl,-Map=' + join("$BUILD_DIR", "${PROGNAME}.map") + '"', ], @@ -80,5 +43,46 @@ env.Append( ], ) +# Build a core list to add sources, flags, etc. +cores = { + "common": "$COMMON_DIR", +} +# Configure each family first (add CPP defines) +for f in family.inheritance: + cores[f.code] = env.AddFamily(f) + +# Add fixups & config for each core +for name, path in cores.items(): + env.AddCoreConfig(path=join(path, "base")) + if "ARDUINO" in env: + env.AddCoreConfig(path=join(path, "arduino", "src")) + +# Include SDK builder scripts +# The script will call BuildLibraries(safe=True) to secure the include paths +found = False +for f in family.inheritance: + try: + env.SConscript(f"../family/{f.name}.py", must_exist=True) + found = True + except UserError: + pass +# Fail if no SDK builder was found +if not found: + click.secho( + f"Platform '{family.name}' is currently not supported - " + "no SDK builder script could be found.", + fg="red", + ) + exit(1) + +# Add sources & include paths for each core +for name, path in cores.items(): + env.AddCoreSources(name=name, path=join(path, "base")) + +# Sources - external libraries +env.AddExternalLibrary("ltchiptool") # uf2ota source code +env.AddExternalLibrary("flashdb") +env.AddExternalLibrary("printf") + # Build everything from the base core env.BuildLibraries() diff --git a/builder/utils/config.py b/builder/utils/config.py index b6f41b1..8a49589 100644 --- a/builder/utils/config.py +++ b/builder/utils/config.py @@ -11,6 +11,7 @@ def env_load_defines(env: Environment, path: str): path = env.subst(path) if not isfile(path): raise FileNotFoundError(f"Defines file not found ({path})") + config = {} f = open(path, "r", encoding="utf-8") for line in f: line: str @@ -19,11 +20,16 @@ def env_load_defines(env: Environment, path: str): line = line[7:].strip() line = line.split(None, 2) if len(line) == 1: - env.Append(CPPDEFINES=[(line[0], "1")]) + env.Append(CPPDEFINES=[(line[0], 1)]) + config[line[0]] = 1 elif len(line) == 2: env.Append(CPPDEFINES=[(line[0], line[1])]) + config[line[0]] = line[1] else: raise ValueError(f"Unknown directive: {line}") + env.Append( + CONFIG=config, + ) f.close() diff --git a/builder/utils/cores.py b/builder/utils/cores.py index 1497a38..3ecaab3 100644 --- a/builder/utils/cores.py +++ b/builder/utils/cores.py @@ -22,27 +22,23 @@ def env_add_family(env: Environment, family: Family) -> str: return path -def env_add_core_config(env: Environment, name: str, path: str) -> bool: +def env_add_core_config(env: Environment, path: str) -> bool: if not isdir(env.subst(path)): return False env.Prepend( - CPPPATH=[join(path, "config")], - LIBPATH=[join(path, "fixups")], + CPPPATH=[ + join(path, "compat"), + join(path, "config"), + join(path, "fixups"), + ], + LIBPATH=[ + join(path, "fixups"), + ], ) try: env.LoadDefines(join(path, "lt_defs.h")) except FileNotFoundError: pass - env.AddLibrary( - name=f"core_{name}_fixups", - base_dir=path, - srcs=[ - "+", - ], - includes=[ - "!", - ], - ) return True @@ -56,6 +52,8 @@ def env_add_core_sources(env: Environment, name: str, path: str) -> bool: "+<*.c*>", "+", "+", + "+", + "+", "+", "+", ], @@ -63,6 +61,9 @@ def env_add_core_sources(env: Environment, name: str, path: str) -> bool: # prepend the paths before SDK directories "!<.>", "!", + "!", + "!", + "!", ], ) return True @@ -78,7 +79,7 @@ def env_add_arduino_libraries(env: Environment, name: str, path: str) -> bool: "+<**/*.c*>", ], includes=[ - "!<*>", + "!<*/*>" if name.startswith("common") else "!<*>", ], ) return True diff --git a/builder/utils/env.py b/builder/utils/env.py index b43edba..bf81177 100644 --- a/builder/utils/env.py +++ b/builder/utils/env.py @@ -50,7 +50,11 @@ def env_read_version(env: Environment, platform_dir: str, version: str): return f"{version}+{build_str}" if build_str else version -def env_configure(env: Environment, platform: PlatformBase, board: PlatformBoardConfig): +def env_configure( + env: Environment, + platform: PlatformBase, + board: PlatformBoardConfig, +) -> Family: # Read external libraries list with open(join(platform.get_dir(), "external-libs.json")) as f: external_libs = json.load(f) @@ -84,6 +88,7 @@ def env_configure(env: Environment, platform: PlatformBase, board: PlatformBoard ) # Store family parameters as environment variables env.Replace(**dict(family)) + return family env.AddMethod(env_configure, "ConfigureEnvironment") diff --git a/cores/beken-72xx/arduino/libraries/LT/LT.cpp b/cores/beken-72xx/arduino/libraries/LT/LT.cpp index 0c36da2..a9ff92a 100644 --- a/cores/beken-72xx/arduino/libraries/LT/LT.cpp +++ b/cores/beken-72xx/arduino/libraries/LT/LT.cpp @@ -36,32 +36,6 @@ void LibreTuya::restartDownloadMode() { bk_reboot(); } -ResetReason LibreTuya::getResetReason() { - switch (bk_misc_get_start_type()) { - case RESET_SOURCE_POWERON: - return RESET_REASON_POWER; - - case RESET_SOURCE_REBOOT: - return RESET_REASON_SOFTWARE; - - case RESET_SOURCE_WATCHDOG: - return RESET_REASON_WATCHDOG; - - case RESET_SOURCE_CRASH_XAT0: - case RESET_SOURCE_CRASH_UNDEFINED: - case RESET_SOURCE_CRASH_PREFETCH_ABORT: - case RESET_SOURCE_CRASH_DATA_ABORT: - case RESET_SOURCE_CRASH_UNUSED: - case RESET_SOURCE_CRASH_PER_XAT0: - return RESET_REASON_CRASH; - - case RESET_SOURCE_DEEPPS_GPIO: - case RESET_SOURCE_DEEPPS_RTC: - return RESET_REASON_SLEEP; - } - return RESET_REASON_UNKNOWN; -} - /* CPU-related */ ChipType LibreTuya::getChipType() { diff --git a/cores/beken-72xx/arduino/src/ArduinoFamily.h b/cores/beken-72xx/arduino/src/ArduinoFamily.h index c2df300..118d1b4 100644 --- a/cores/beken-72xx/arduino/src/ArduinoFamily.h +++ b/cores/beken-72xx/arduino/src/ArduinoFamily.h @@ -13,17 +13,6 @@ // Include family-specific code #include "WVariant.h" -// Include board variant -#include "variant.h" - -// Choose the main UART output port -#ifndef LT_UART_DEFAULT_PORT -#if defined(PIN_SERIAL2_TX) -#define LT_UART_DEFAULT_PORT 2 -#else -#define LT_UART_DEFAULT_PORT 1 -#endif -#endif // Define available serial ports #ifdef __cplusplus diff --git a/cores/beken-72xx/arduino/src/lt_defs.h b/cores/beken-72xx/arduino/src/lt_defs.h index 98353e2..28cb3fa 100644 --- a/cores/beken-72xx/arduino/src/lt_defs.h +++ b/cores/beken-72xx/arduino/src/lt_defs.h @@ -2,5 +2,6 @@ #error "Don't include this file directly" -#define LT_ARD_HAS_WIFI 1 -#define LT_ARD_HAS_MD5 1 +#define LT_ARD_HAS_WIFI 1 +#define LT_ARD_HAS_MD5 1 +#define LT_ARD_HAS_SERIAL 1 diff --git a/cores/beken-72xx/base/fixups/.clang-format b/cores/beken-72xx/base/fixups/.clang-format new file mode 100644 index 0000000..47a38a9 --- /dev/null +++ b/cores/beken-72xx/base/fixups/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: Never diff --git a/cores/beken-72xx/base/fixups/arch_main.c b/cores/beken-72xx/base/fixups/arch_main.c index 1ca42b1..0e22688 100644 --- a/cores/beken-72xx/base/fixups/arch_main.c +++ b/cores/beken-72xx/base/fixups/arch_main.c @@ -24,7 +24,7 @@ void entry_set_world_flag(void) { } #endif // CFG_SUPPORT_BOOTLOADER -extern void main(void); +extern void lt_main(void); // declare as weak to override with Arduino framework __attribute__((weak)) void __wrap_bk_printf_disable(); @@ -57,5 +57,5 @@ void entry_main(void) { // enable bk_printf output again __wrap_bk_printf_enable(); // run the app - main(); + lt_main(); } diff --git a/cores/beken-72xx/base/fixups/param_config.h b/cores/beken-72xx/base/fixups/param_config.h index 759eda6..68cef1b 100644 --- a/cores/beken-72xx/base/fixups/param_config.h +++ b/cores/beken-72xx/base/fixups/param_config.h @@ -1,8 +1,8 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-14. */ -#pragma once - #include_next "param_config.h" +#pragma once + #undef WIFI_MAC_POS #define WIFI_MAC_POS -1 // do not use stored MAC address by default diff --git a/cores/beken-72xx/base/fixups/uart_pub.h b/cores/beken-72xx/base/fixups/uart_pub.h index ca8521e..9626f78 100644 --- a/cores/beken-72xx/base/fixups/uart_pub.h +++ b/cores/beken-72xx/base/fixups/uart_pub.h @@ -1,10 +1,9 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-20. */ -#pragma once - #include_next "uart_pub.h" -#ifdef LIBRETUYA_ARDUINO +#pragma once + // make uart.c call __wrap_bk_printf() instead of bk_printf() // standard wrapping does not work in this case, as bk_printf() // is implemented in the same translation unit @@ -15,4 +14,3 @@ extern void __wrap_bk_printf(const char *fmt, ...); // not defining bk_printf() again, as this would just change the impl name #define os_printf __wrap_bk_printf #define as_printf (__wrap_bk_printf("%s:%d\r\n", __FUNCTION__, __LINE__)) -#endif diff --git a/cores/beken-72xx/base/lt_defs.h b/cores/beken-72xx/base/lt_defs.h index 0125e4b..552faaf 100644 --- a/cores/beken-72xx/base/lt_defs.h +++ b/cores/beken-72xx/base/lt_defs.h @@ -2,7 +2,10 @@ #error "Don't include this file directly" +#define LT_HAS_PRINTF 1 #define LT_HAS_LWIP 1 #define LT_HAS_LWIP2 1 #define LT_HAS_FREERTOS 1 #define LT_HAS_MBEDTLS 1 + +#define LT_HEAP_FUNC xPortGetFreeHeapSize diff --git a/cores/beken-72xx/base/lt_family.h b/cores/beken-72xx/base/lt_family.h new file mode 100644 index 0000000..0919cc6 --- /dev/null +++ b/cores/beken-72xx/base/lt_family.h @@ -0,0 +1,12 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#pragma once + +// Choose the main UART output port +#ifndef LT_UART_DEFAULT_PORT +#if defined(PIN_SERIAL2_TX) +#define LT_UART_DEFAULT_PORT 2 +#else +#define LT_UART_DEFAULT_PORT 1 +#endif +#endif diff --git a/cores/beken-72xx/base/lt_family_api.c b/cores/beken-72xx/base/lt_family_api.c new file mode 100644 index 0000000..45deff9 --- /dev/null +++ b/cores/beken-72xx/base/lt_family_api.c @@ -0,0 +1,29 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#include "lt_family_api.h" + +#include + +ResetReason lt_get_reset_reason() { + switch (bk_misc_get_start_type()) { + case RESET_SOURCE_POWERON: + return RESET_REASON_POWER; + case RESET_SOURCE_REBOOT: + return RESET_REASON_SOFTWARE; + case RESET_SOURCE_WATCHDOG: + return RESET_REASON_WATCHDOG; + case RESET_SOURCE_CRASH_XAT0: + case RESET_SOURCE_CRASH_UNDEFINED: + case RESET_SOURCE_CRASH_PREFETCH_ABORT: + case RESET_SOURCE_CRASH_DATA_ABORT: + case RESET_SOURCE_CRASH_UNUSED: + case RESET_SOURCE_CRASH_PER_XAT0: + return RESET_REASON_CRASH; + case RESET_SOURCE_DEEPPS_GPIO: + case RESET_SOURCE_DEEPPS_RTC: + case RESET_SOURCE_DEEPPS_USB: + return RESET_REASON_SLEEP; + default: + return RESET_REASON_UNKNOWN; + } +} diff --git a/cores/beken-72xx/base/port/fal_flash_bk72xx_port.c b/cores/beken-72xx/base/port/fal_flash_bk72xx_port.c index abca7a0..78e92b7 100644 --- a/cores/beken-72xx/base/port/fal_flash_bk72xx_port.c +++ b/cores/beken-72xx/base/port/fal_flash_bk72xx_port.c @@ -1,10 +1,9 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-19. */ -#include -#include +#include +#include #include -#include #define FLASH_ERASE_MIN_SIZE (4 * 1024) diff --git a/cores/beken-72xx/base/port/printf.c b/cores/beken-72xx/base/port/printf.c index 93fd8ca..61685e9 100644 --- a/cores/beken-72xx/base/port/printf.c +++ b/cores/beken-72xx/base/port/printf.c @@ -1,11 +1,8 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-19. */ -#include +#include #include -#include -#include -#include extern void bk_send_byte(uint8_t uport, uint8_t data); extern int uart_print_port; diff --git a/cores/beken-72xx/base/port/printf_port.h b/cores/beken-72xx/base/port/printf_port.h index a3242a7..c627e53 100644 --- a/cores/beken-72xx/base/port/printf_port.h +++ b/cores/beken-72xx/base/port/printf_port.h @@ -4,4 +4,12 @@ #include +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + WRAP_DISABLE_DEF(bk_printf); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/beken-72xx/base/sdk_mem.h b/cores/beken-72xx/base/sdk_mem.h deleted file mode 100644 index e61ab14..0000000 --- a/cores/beken-72xx/base/sdk_mem.h +++ /dev/null @@ -1,20 +0,0 @@ -/* Copyright (c) Kuba Szczodrzyński 2022-06-18. */ - -#pragma once - -#include - -// Beken SDK is actually pretty good, in terms of declaring -// stdlib functions properly! So no need for any #define hell. -#include - -// All the MemMang functions are in stdlib, just wrapped -// during linking. -#include -// for memcpy etc. -#include - -// ...except zalloc, which is apparently not in the stdlib -#define zalloc os_zalloc - -#define LT_HEAP_FUNC xPortGetFreeHeapSize diff --git a/cores/beken-72xx/base/sdk_private.h b/cores/beken-72xx/base/sdk_private.h index 535c87e..193a980 100644 --- a/cores/beken-72xx/base/sdk_private.h +++ b/cores/beken-72xx/base/sdk_private.h @@ -2,23 +2,17 @@ #pragma once -// for printf() etc (they are wrapped anyway) -#include - // most stuff is here #include -// for os_printf -#include -// for GPIO names +// other includes +#include #include +#include // conflict with stl_algobase.h #undef min #undef max -// include printf() wrapper disable methods -#include - // make non-SDK code call the proper printf() #undef bk_printf #undef os_printf diff --git a/cores/common/arduino/libraries/api/LT/LT.cpp b/cores/common/arduino/libraries/api/LT/LT.cpp index 4cf53dd..a17a8fc 100644 --- a/cores/common/arduino/libraries/api/LT/LT.cpp +++ b/cores/common/arduino/libraries/api/LT/LT.cpp @@ -50,6 +50,13 @@ const char *LibreTuya::getDeviceName() { return deviceName; } +/** + * @brief Get the reason of last chip reset. + */ +ResetReason LibreTuya::getResetReason() { + return lt_get_reset_reason(); +} + /** * @brief Get a textual representation of a reset reason. * diff --git a/cores/common/arduino/libraries/api/LT/LT.h b/cores/common/arduino/libraries/api/LT/LT.h index be2a42a..cb0ab3b 100644 --- a/cores/common/arduino/libraries/api/LT/LT.h +++ b/cores/common/arduino/libraries/api/LT/LT.h @@ -7,18 +7,6 @@ #include "LibreTuyaAPI.h" #include -typedef enum { - RESET_REASON_UNKNOWN = 0, - RESET_REASON_POWER = 1, - RESET_REASON_BROWNOUT = 2, - RESET_REASON_HARDWARE = 3, - RESET_REASON_SOFTWARE = 4, - RESET_REASON_WATCHDOG = 5, - RESET_REASON_CRASH = 6, - RESET_REASON_SLEEP = 7, - RESET_REASON_MAX = 8, -} ResetReason; - /** * @brief Flash chip ID structure. */ @@ -43,6 +31,7 @@ class LibreTuya { ChipFamily getChipFamily(); const char *getChipFamilyName(); const char *getDeviceName(); + ResetReason getResetReason(); const char *getResetReasonName(ResetReason reason = RESET_REASON_MAX); uint32_t getCpuFreqMHz(); uint32_t getFlashChipSize(); @@ -67,10 +56,6 @@ class LibreTuya { * @brief Reboot the CPU and stay in download mode (if possible). */ void restartDownloadMode(); - /** - * @brief Get the reason of last chip reset. - */ - ResetReason getResetReason(); /** * @brief Reconfigure GPIO pins used for debugging * (SWD/JTAG), so that they can be used as normal I/O. diff --git a/cores/common/arduino/src/Arduino.h b/cores/common/arduino/src/Arduino.h new file mode 100644 index 0000000..f6a1a1c --- /dev/null +++ b/cores/common/arduino/src/Arduino.h @@ -0,0 +1,57 @@ +/* Copyright (c) Kuba Szczodrzyński 2022-06-14. */ + +#pragma once + +// LibreTuya C API (with C standard libraries) +#include + +// C++ standard libraries +#ifdef __cplusplus +#include +#include +using ::round; +using std::abs; +using std::isinf; +using std::isnan; +using std::max; +using std::min; +#endif + +// Arduino Core and LT class +#include +#ifdef __cplusplus +#include +#endif + +// Include family-specific code +#include +// Include board variant +#include "variant.h" + +/** + * @brief Run mainTask & start OS kernel (family-defined). + * Return false if an error occured; else do not return and + * and keep the OS kernel running. + */ +extern int startMainTask(void); + +// Define available serial ports +#if defined(__cplusplus) && LT_ARD_HAS_SERIAL +#include + +#ifdef PIN_SERIAL0_TX +extern SerialClass Serial0; +#endif + +#ifdef PIN_SERIAL1_TX +extern SerialClass Serial1; +#endif + +#ifdef PIN_SERIAL2_TX +extern SerialClass Serial2; +#endif + +#define SerialN(x) Serial##x +#define SerialM(x) SerialN(x) +#define Serial SerialM(LT_UART_DEFAULT_SERIAL) +#endif diff --git a/cores/common/arduino/src/SerialExtern.h b/cores/common/arduino/src/SerialExtern.h deleted file mode 100644 index e404333..0000000 --- a/cores/common/arduino/src/SerialExtern.h +++ /dev/null @@ -1,25 +0,0 @@ -/* Copyright (c) Kuba Szczodrzyński 2022-07-04. */ - -#pragma once - -#include - -#ifdef HAS_SERIAL_CLASS // failsafe for circular inclusion - -#ifdef PIN_SERIAL0_TX -extern SerialClass Serial0; -#endif - -#ifdef PIN_SERIAL1_TX -extern SerialClass Serial1; -#endif - -#ifdef PIN_SERIAL2_TX -extern SerialClass Serial2; -#endif - -#define SerialN(x) Serial##x -#define SerialM(x) SerialN(x) -#define Serial SerialM(LT_UART_DEFAULT_SERIAL) - -#endif diff --git a/cores/common/arduino/src/main.c b/cores/common/arduino/src/main.c new file mode 100644 index 0000000..ae8d831 --- /dev/null +++ b/cores/common/arduino/src/main.c @@ -0,0 +1,39 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#include + +// Arduino framework initialization. +// May be redefined by family files. +void initArduino() __attribute__((weak)); + +// Weak empty variant initialization function. +// May be redefined by variant files. +void initVariant() __attribute__((weak)); + +int main() { + // initialize Arduino framework + initArduino(); + // optionally initialize per-variant code + initVariant(); + // start the main task and OS kernel + if (!startMainTask()) { + LT_F("Couldn't start the main task"); + return 1; + } + return 0; +} + +/** + * @brief Main setup() and loop() task. + * Not to be called directly. + */ +void mainTask(const void *arg) { + setup(); + + for (;;) { + loop(); + if (serialEventRun) + serialEventRun(); + yield(); + } +} diff --git a/cores/common/arduino/src/LibreTuyaCompat.cpp b/cores/common/arduino/src/wiring_compat.cpp similarity index 80% rename from cores/common/arduino/src/LibreTuyaCompat.cpp rename to cores/common/arduino/src/wiring_compat.cpp index 203f390..67469cc 100644 --- a/cores/common/arduino/src/LibreTuyaCompat.cpp +++ b/cores/common/arduino/src/wiring_compat.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-04. */ -#include "LibreTuyaCompat.h" +#include "wiring_compat.h" #if LT_HAS_FREERTOS BaseType_t xTaskCreateUniversal( @@ -31,3 +31,9 @@ BaseType_t xTaskCreateUniversal( // #endif } #endif + +String ipToString(const IPAddress &ip) { + char szRet[16]; + sprintf(szRet, "%hhu.%hhu.%hhu.%hhu", ip[0], ip[1], ip[2], ip[3]); + return String(szRet); +} diff --git a/cores/common/arduino/src/LibreTuyaCompat.h b/cores/common/arduino/src/wiring_compat.h similarity index 95% rename from cores/common/arduino/src/LibreTuyaCompat.h rename to cores/common/arduino/src/wiring_compat.h index 9c5f469..b49470c 100644 --- a/cores/common/arduino/src/LibreTuyaCompat.h +++ b/cores/common/arduino/src/wiring_compat.h @@ -40,3 +40,7 @@ BaseType_t xTaskCreateUniversal( // Default values from sdkconfig.h #define CONFIG_LWIP_MAX_ACTIVE_TCP 16 + +#ifdef __cplusplus +String ipToString(const IPAddress &ip); +#endif diff --git a/cores/common/arduino/src/wiring_custom.c b/cores/common/arduino/src/wiring_custom.c index 0fe5738..0ca036e 100644 --- a/cores/common/arduino/src/wiring_custom.c +++ b/cores/common/arduino/src/wiring_custom.c @@ -1,11 +1,33 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-20. */ -#include "LibreTuyaCustom.h" +#include "wiring_custom.h" int _analogReadResolution = 10; // 0-1023 int _analogWriteResolution = 8; // 0-255 int _analogWritePeriod = 20000; // 50 Hz +static unsigned long periodicTasks[] = {0, 0}; + +/** + * @brief Run periodic tasks, like printing free heap or checking millis() overflow. + * + * This is called during delaying operations, like yield() or delay(). + */ +void runPeriodicTasks() { +#if LT_LOG_HEAP + if (millis() - periodicTasks[0] > 1000) { + LT_HEAP_I(); + periodicTasks[0] = millis(); + } +#endif +#if LT_USE_TIME + if (millis() - periodicTasks[1] > 10000) { + gettimeofday(NULL, NULL); + periodicTasks[1] = millis(); + } +#endif +} + /** * @brief Check if pin is invalid (too low or too high). */ diff --git a/cores/common/arduino/src/wiring_custom.h b/cores/common/arduino/src/wiring_custom.h index 3c67122..3acca1b 100644 --- a/cores/common/arduino/src/wiring_custom.h +++ b/cores/common/arduino/src/wiring_custom.h @@ -2,32 +2,12 @@ #pragma once -#include "LibreTuyaAPI.h" +#include #ifdef __cplusplus extern "C" { #endif -/** - * @brief Run mainTask & start OS kernel (family-defined). - * Return false if an error occured; else do not return and - * and keep the OS kernel running. - */ -extern bool startMainTask(); - -/** - * @brief Main setup() and loop() task. - * Not to be called directly. - */ -extern void mainTask(const void *arg); - -/** - * @brief Run periodic tasks, like printing free heap or checking millis() overflow. - * - * This is called during delaying operations, like yield() or delay(). - */ -extern void runPeriodicTasks(); - #define PIN_NONE (1 << 0) #define PIN_GPIO (1 << 1) #define PIN_IRQ (1 << 2) @@ -64,6 +44,9 @@ extern PinInfo pinTable[]; // Custom Wiring methods +void mainTask(const void *arg); // implemented in main.cpp +void runPeriodicTasks(); // implemented in wiring_custom.c + bool pinInvalid(pin_size_t pinNumber); PinInfo *pinInfo(pin_size_t pinNumber); bool pinSupported(PinInfo *pin, uint32_t mask); diff --git a/cores/common/base/config/fal_cfg.h b/cores/common/base/config/fal_cfg.h index d5bc0f0..fbd073d 100644 --- a/cores/common/base/config/fal_cfg.h +++ b/cores/common/base/config/fal_cfg.h @@ -2,6 +2,10 @@ #pragma once +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + inline void printf_nop(const char *fmt, ...) {} #define FAL_PRINTF printf_nop @@ -10,6 +14,10 @@ inline void printf_nop(const char *fmt, ...) {} // Flash device configuration extern const struct fal_flash_dev flash0; +#ifdef __cplusplus +} // extern "C" +#endif + #define FAL_FLASH_DEV_NAME "flash0" #define FAL_FLASH_DEV_TABLE \ @@ -33,6 +41,6 @@ extern const struct fal_flash_dev flash0; #include /** - * @brief Root partition table, representing the entire flash. + * @brief "Root" partition entry, representing the entire flash. */ extern fal_partition_t fal_root_part; diff --git a/cores/common/base/config/fdb_cfg.h b/cores/common/base/config/fdb_cfg.h index a967900..1009280 100644 --- a/cores/common/base/config/fdb_cfg.h +++ b/cores/common/base/config/fdb_cfg.h @@ -36,9 +36,8 @@ /* MCU Endian Configuration, default is Little Endian Order. */ // #define FDB_BIG_ENDIAN -#include - #if LT_DEBUG_FDB +#include #include #define FDB_PRINT(...) __wrap_printf(__VA_ARGS__) #define FDB_DEBUG_ENABLE diff --git a/cores/common/base/config/printf_config.h b/cores/common/base/config/printf_config.h index e89a456..2b0d921 100644 --- a/cores/common/base/config/printf_config.h +++ b/cores/common/base/config/printf_config.h @@ -2,7 +2,11 @@ #pragma once -#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus #define PRINTF_HAS_DISABLE 1 @@ -127,3 +131,7 @@ void putchar_p(char c, unsigned long port); int __wrap_##name(char *s, size_t count, const char *format, va_list arg) { \ return vsnprintf(s, count, format, arg); \ } + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/common/base/lt_api.h b/cores/common/base/libretuya.h similarity index 57% rename from cores/common/base/lt_api.h rename to cores/common/base/libretuya.h index d649368..369b03d 100644 --- a/cores/common/base/lt_api.h +++ b/cores/common/base/libretuya.h @@ -12,18 +12,6 @@ #include #include -// C++ standard libraries -#ifdef __cplusplus -#include -#include -using ::round; -using std::abs; -using std::isinf; -using std::isnan; -using std::max; -using std::min; -#endif - // LibreTuya version macros #ifndef LT_VERSION #define LT_VERSION 1.0.0 @@ -36,25 +24,6 @@ using std::min; #define LT_VERSION_STR STRINGIFY_MACRO(LT_VERSION) #define LT_BOARD_STR STRINGIFY_MACRO(LT_BOARD) -// Includes -#include "LibreTuyaClass.h" // global LT class -#include "LibreTuyaCompat.h" // compatibility methods -#include "LibreTuyaConfig.h" // configuration macros -#include "LibreTuyaCustom.h" // family-defined methods (Wiring custom) -#include - -// C includes -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - -#include "lt_logger.h" -#include "lt_posix_api.h" - -#ifdef __cplusplus -} // extern "C" -#endif - // Functional macros #define LT_BANNER() \ LT_LOG( \ @@ -64,17 +33,18 @@ extern "C" { "LibreTuya v" LT_VERSION_STR " on " LT_BOARD_STR ", compiled at " __DATE__ " " __TIME__ \ ) -#ifdef __cplusplus -String ipToString(const IPAddress &ip); - -extern "C" { -void lt_rand_bytes(uint8_t *buf, size_t len); -void hexdump(const uint8_t *buf, size_t len, uint32_t offset = 0, uint8_t width = 16); -} - -#else - -void lt_rand_bytes(uint8_t *buf, size_t len); -void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width); - -#endif +// Types & macros +#include "lt_chip.h" // ChipType enum +#include "lt_config.h" // configuration macros +#include "lt_types.h" // other types & enums +// Family-specific macros +#include +// Board variant (pin definitions) +#include +// APIs +#include "lt_common_api.h" // common APIs +#include "lt_family_api.h" // family-specific APIs +#include "lt_logger.h" // UART logger utility +#include "lt_posix_api.h" // POSIX compat functions +// printf silencing methods +#include diff --git a/cores/common/base/lt_chip.h b/cores/common/base/lt_chip.h index 7537a87..98a0cf9 100644 --- a/cores/common/base/lt_chip.h +++ b/cores/common/base/lt_chip.h @@ -5,7 +5,7 @@ #define CHIP_TYPE(family, chip_id) (((family >> 24) << 8) | chip_id) #define CHIP_TYPE_ENUM(family, chip_id) (ChipType) CHIP_TYPE(family, chip_id) -enum ChipFamily { +typedef enum { // used in UF2 Family ID F_RTL8710A = 0x9FFFD543, // Realtek Ameba1 F_RTL8710B = 0x22E0D6FC, // Realtek AmebaZ (realtek-ambz) @@ -15,9 +15,9 @@ enum ChipFamily { F_BK7231N = 0x7B3EF230, // Beken 7231N F_BK7251 = 0x6A82CC42, // Beken 7251/7252 F_BL60X = 0xDE1270B7, // Boufallo 602 -}; +} ChipFamily; -enum ChipType { +typedef enum { // Realtek AmebaZ // IDs copied from rtl8710b_efuse.h RTL8710BL = CHIP_TYPE(F_RTL8710B, 0xE0), // ??? @@ -32,4 +32,4 @@ enum ChipType { BK7231N = CHIP_TYPE(F_BK7231N, 0x1C), // *SCTRL_CHIP_ID = 0x7231c BL2028N = CHIP_TYPE(F_BK7231N, 0x1C), // *SCTRL_CHIP_ID = 0x7231c BK7252 = CHIP_TYPE(F_BK7251, 0x00), // TODO -}; +} ChipType; diff --git a/cores/common/base/lt_api.c b/cores/common/base/lt_common_api.c similarity index 83% rename from cores/common/base/lt_api.c rename to cores/common/base/lt_common_api.c index 3304f27..54a83e6 100644 --- a/cores/common/base/lt_api.c +++ b/cores/common/base/lt_common_api.c @@ -1,12 +1,6 @@ /* Copyright (c) Kuba Szczodrzyński 2022-04-29. */ -#include "LibreTuyaAPI.h" - -String ipToString(const IPAddress &ip) { - char szRet[16]; - sprintf(szRet, "%hhu.%hhu.%hhu.%hhu", ip[0], ip[1], ip[2], ip[3]); - return String(szRet); -} +#include "lt_common_api.h" /** * @brief Generate random bytes using rand(). @@ -14,7 +8,6 @@ String ipToString(const IPAddress &ip) { * @param buf destination pointer * @param len how many bytes to generate */ -extern "C" { void lt_rand_bytes(uint8_t *buf, size_t len) { int *data = (int *)buf; size_t i; @@ -28,8 +21,6 @@ void lt_rand_bytes(uint8_t *buf, size_t len) { } } -#undef putchar - /** * @brief Print data pointed to by buf in hexdump-like format (hex+ASCII). * @@ -44,7 +35,7 @@ void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width) { // print hex offset printf("%06x ", offset + pos); // calculate current line width - uint8_t lineWidth = min(width, len - pos); + uint8_t lineWidth = MIN(width, len - pos); // print hexadecimal representation for (uint8_t i = 0; i < lineWidth; i++) { if (i % 8 == 0) { @@ -62,4 +53,3 @@ void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width) { pos += lineWidth; } } -} diff --git a/cores/common/base/lt_common_api.h b/cores/common/base/lt_common_api.h new file mode 100644 index 0000000..9a40cac --- /dev/null +++ b/cores/common/base/lt_common_api.h @@ -0,0 +1,35 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// https://stackoverflow.com/a/3437484 +#define MAX(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a > _b ? _a : _b; \ + }) +#define MIN(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a < _b ? _a : _b; \ + }) + +void lt_rand_bytes(uint8_t *buf, size_t len); + +#ifdef __cplusplus +void hexdump(const uint8_t *buf, size_t len, uint32_t offset = 0, uint8_t width = 16); +#else +void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/common/base/lt_family_api.h b/cores/common/base/lt_family_api.h new file mode 100644 index 0000000..a2fd48b --- /dev/null +++ b/cores/common/base/lt_family_api.h @@ -0,0 +1,18 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * @brief Get the reason of last chip reset. + */ +ResetReason lt_get_reset_reason(); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/common/base/lt_logger.c b/cores/common/base/lt_logger.c index f3feac5..795a125 100644 --- a/cores/common/base/lt_logger.c +++ b/cores/common/base/lt_logger.c @@ -2,10 +2,17 @@ #include "lt_logger.h" -#include -#include +#include +#include -#if LT_LOGGER_TASK && LT_HAS_FREERTOS +#if LT_HAS_PRINTF +#include +#include +#else +#include +#endif + +#if (LT_LOGGER_TIMESTAMP || LT_LOGGER_TASK) && LT_HAS_FREERTOS #include #include #endif @@ -42,7 +49,9 @@ static const uint8_t colors[] = { }; #endif +#if LIBRETUYA_ARDUINO unsigned long millis(void); +#endif #if LT_LOGGER_CALLER void lt_log(const uint8_t level, const char *caller, const unsigned short line, const char *format, ...) { @@ -54,7 +63,13 @@ void lt_log(const uint8_t level, const char *format, ...) { return; #if LT_LOGGER_TIMESTAMP +#if LIBRETUYA_ARDUINO float seconds = millis() / 1000.0f; +#elif LT_HAS_FREERTOS + float seconds = xTaskGetTickCount() * portTICK_PERIOD_MS / 1000.0f; +#else + float seconds = 0; +#endif #if LT_PRINTF_BROKEN char zero[4] = "\x00\x30\x30"; if (seconds == 0.0f) @@ -77,9 +92,13 @@ void lt_log(const uint8_t level, const char *format, ...) { char c_value = '0' + (colors[level] & 0x7); #endif +#if LT_HAS_PRINTF fctprintf( (void (*)(char, void *))putchar_p, (void *)uart_port, +#else + printf( +#endif // format: #if LT_LOGGER_COLOR "\e[%c;3%cm" @@ -128,12 +147,21 @@ void lt_log(const uint8_t level, const char *format, ...) { #endif ); +#if LT_HAS_PRINTF va_list va_args; va_start(va_args, format); vfctprintf((void (*)(char, void *))putchar_p, (void *)uart_port, format, va_args); va_end(va_args); putchar_p('\r', uart_port); putchar_p('\n', uart_port); +#else + va_list va_args; + va_start(va_args, format); + vprintf(format, va_args); + va_end(va_args); + putchar('\r'); + putchar('\n'); +#endif } void lt_log_set_port(uint8_t port) { diff --git a/cores/common/base/lt_logger.h b/cores/common/base/lt_logger.h index 816f6f2..14abf69 100644 --- a/cores/common/base/lt_logger.h +++ b/cores/common/base/lt_logger.h @@ -2,8 +2,11 @@ #pragma once -#include "LibreTuyaConfig.h" -#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus #if LT_LOGGER_CALLER #define LT_LOG(level, caller, line, ...) lt_log(level, caller, line, __VA_ARGS__) @@ -168,3 +171,7 @@ void lt_log_disable(); #else #define LT_ERRNO() #endif + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/common/base/lt_main.c b/cores/common/base/lt_main.c index bbad290..7f1d566 100644 --- a/cores/common/base/lt_main.c +++ b/cores/common/base/lt_main.c @@ -1,74 +1,28 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-19. */ -#include -#include +#include -using namespace arduino; - -extern "C" { #include + fal_partition_t fal_root_part = NULL; -} - -// Arduino framework initialization. -// May be redefined by family files. -void initArduino() __attribute__((weak)); - -// Weak empty variant initialization function. -// May be redefined by variant files. -void initVariant() __attribute__((weak)); // Initialize C library -extern "C" void __libc_init_array(void); +void __libc_init_array(void); +// Main app entrypoint +int main(void); -void mainTask(const void *arg) { - setup(); - - for (;;) { - loop(); - if (serialEventRun) - serialEventRun(); - yield(); - } -} - -static unsigned long periodicTasks[] = {0, 0}; - -void runPeriodicTasks() { -#if LT_LOG_HEAP - if (millis() - periodicTasks[0] > 1000) { - LT_HEAP_I(); - periodicTasks[0] = millis(); - } -#endif -#if LT_USE_TIME - if (millis() - periodicTasks[1] > 10000) { - gettimeofday(NULL, NULL); - periodicTasks[1] = millis(); - } -#endif -} - -int main(void) { +int lt_main(void) { // print a startup banner LT_BANNER(); // initialize C library __libc_init_array(); // inform about the reset reason - LT_I("Reset reason: %u", LT.getResetReason()); - // initialize Arduino framework - initArduino(); - // optionally initialize per-variant code - initVariant(); + LT_I("Reset reason: %u", lt_get_reset_reason()); // initialize FAL fal_init(); // provide root partition fal_root_part = (fal_partition_t)fal_partition_find("root"); - // start the main task and OS kernel - if (!startMainTask()) { - LT_F("Couldn't start the main task"); - } - while (1) {} - return 0; + // run the application + return main(); } diff --git a/cores/common/base/lt_posix_api.h b/cores/common/base/lt_posix_api.h index c27d2f4..e703029 100644 --- a/cores/common/base/lt_posix_api.h +++ b/cores/common/base/lt_posix_api.h @@ -1,7 +1,9 @@ /* Copyright (c) Kuba Szczodrzyński 2022-05-16. */ #include +#include extern char *strdup(const char *); extern int strcasecmp(const char *s1, const char *s2); extern int strncasecmp(const char *s1, const char *s2, size_t n); +extern char *strptime(const char *buf, const char *fmt, struct tm *tm); diff --git a/cores/common/base/lt_types.h b/cores/common/base/lt_types.h new file mode 100644 index 0000000..97abb7d --- /dev/null +++ b/cores/common/base/lt_types.h @@ -0,0 +1,15 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#pragma once + +typedef enum { + RESET_REASON_UNKNOWN = 0, + RESET_REASON_POWER = 1, + RESET_REASON_BROWNOUT = 2, + RESET_REASON_HARDWARE = 3, + RESET_REASON_SOFTWARE = 4, + RESET_REASON_WATCHDOG = 5, + RESET_REASON_CRASH = 6, + RESET_REASON_SLEEP = 7, + RESET_REASON_MAX = 8, +} ResetReason; diff --git a/cores/common/base/posix/strdup.c b/cores/common/base/posix/strdup.c index 160d396..db16569 100644 --- a/cores/common/base/posix/strdup.c +++ b/cores/common/base/posix/strdup.c @@ -1,7 +1,8 @@ /* Copyright (c) Kuba Szczodrzyński 2022-05-16. */ #include -#include +#include +#include __attribute__((weak)) char *strdup(const char *s) { size_t len = strlen(s) + 1; diff --git a/cores/common/base/strptime.h b/cores/common/base/strptime.h deleted file mode 100644 index 62b9b56..0000000 --- a/cores/common/base/strptime.h +++ /dev/null @@ -1,7 +0,0 @@ -/* Copyright (c) Kuba Szczodrzyński 2022-04-29. */ - -#pragma once - -#include - -extern char *strptime(const char *buf, const char *fmt, struct tm *tm); diff --git a/cores/realtek-amb/arduino/libraries/LT/LT.cpp b/cores/realtek-amb/arduino/libraries/LT/LT.cpp index c3703d2..2580a35 100644 --- a/cores/realtek-amb/arduino/libraries/LT/LT.cpp +++ b/cores/realtek-amb/arduino/libraries/LT/LT.cpp @@ -25,10 +25,6 @@ void LibreTuya::restartDownloadMode() { while (1) {} } -ResetReason LibreTuya::getResetReason() { - return RESET_REASON_UNKNOWN; -} - void LibreTuya::gpioRecover() { // PA14 and PA15 are apparently unusable with SWD enabled sys_jtag_off(); diff --git a/cores/realtek-amb/arduino/src/lt_defs.h b/cores/realtek-amb/arduino/src/lt_defs.h index 846f707..969894e 100644 --- a/cores/realtek-amb/arduino/src/lt_defs.h +++ b/cores/realtek-amb/arduino/src/lt_defs.h @@ -5,6 +5,7 @@ #define LT_ARD_HAS_WIFI 1 #define LT_ARD_HAS_MD5 1 #define LT_ARD_HAS_SOFTSERIAL 1 +#define LT_ARD_HAS_SERIAL 1 #define ARDUINO_AMEBA #define ARDUINO_ARCH_AMBZ diff --git a/cores/realtek-amb/base/lt_family_api.c b/cores/realtek-amb/base/lt_family_api.c new file mode 100644 index 0000000..ddc4e17 --- /dev/null +++ b/cores/realtek-amb/base/lt_family_api.c @@ -0,0 +1,7 @@ +/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */ + +#include "lt_family_api.h" + +ResetReason getResetReason() { + return RESET_REASON_UNKNOWN; +} diff --git a/cores/realtek-amb/base/port/fal_flash_ambz_port.c b/cores/realtek-amb/base/port/fal_flash_ambz_port.c index 79b25c3..951d2ba 100644 --- a/cores/realtek-amb/base/port/fal_flash_ambz_port.c +++ b/cores/realtek-amb/base/port/fal_flash_ambz_port.c @@ -1,7 +1,9 @@ /* Copyright (c) Kuba Szczodrzyński 2022-05-24. */ +#include +#include + #include -#include #define FLASH_ERASE_MIN_SIZE (4 * 1024) diff --git a/cores/realtek-amb/base/port/printf.c b/cores/realtek-amb/base/port/printf.c index 9724504..7217451 100644 --- a/cores/realtek-amb/base/port/printf.c +++ b/cores/realtek-amb/base/port/printf.c @@ -1,11 +1,8 @@ /* Copyright (c) Kuba Szczodrzyński 2022-06-19. */ -#include +#include #include -#include -#include -#include #define LOG_UART_REG_BASE 0x40003000 #define UART0_REG_BASE 0x40040000 diff --git a/cores/realtek-amb/base/port/printf_port.h b/cores/realtek-amb/base/port/printf_port.h index f54885d..74d770e 100644 --- a/cores/realtek-amb/base/port/printf_port.h +++ b/cores/realtek-amb/base/port/printf_port.h @@ -4,7 +4,15 @@ #include +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + WRAP_DISABLE_DEF(rtl_printf); WRAP_DISABLE_DEF(DiagPrintf); WRAP_DISABLE_DEF(prvDiagPrintf); WRAP_DISABLE_DEF(LOG_PRINTF); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/realtek-amb/base/sdk_mem.h b/cores/realtek-amb/base/sdk_mem.h index a242d4a..2f0e9e2 100644 --- a/cores/realtek-amb/base/sdk_mem.h +++ b/cores/realtek-amb/base/sdk_mem.h @@ -17,5 +17,3 @@ extern void vPortFree(void *pv); #define calloc pvPortCalloc #define realloc pvPortReAlloc #define free vPortFree - -#define LT_HEAP_FUNC xPortGetFreeHeapSize diff --git a/cores/realtek-amb/base/sdk_private.h b/cores/realtek-amb/base/sdk_private.h index c77cb73..0653549 100644 --- a/cores/realtek-amb/base/sdk_private.h +++ b/cores/realtek-amb/base/sdk_private.h @@ -18,6 +18,7 @@ #undef strtoul #include +#include #include #include #include @@ -55,6 +56,3 @@ extern void DumpForOneBytes(void *addr, int cnt); // cnt max 0x70! extern void SystemCoreClockUpdate(void); extern int _sscanf_patch(const char *buf, const char *fmt, ...); - -// include printf() wrapper disable methods -#include diff --git a/cores/realtek-amb/lt_defs.h b/cores/realtek-amb/lt_defs.h new file mode 100644 index 0000000..1e33567 --- /dev/null +++ b/cores/realtek-amb/lt_defs.h @@ -0,0 +1,7 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_HAS_PRINTF 1 + +#define LT_HEAP_FUNC xPortGetFreeHeapSize diff --git a/cores/realtek-ambz/base/fixups/.clang-format b/cores/realtek-ambz/base/fixups/.clang-format new file mode 100644 index 0000000..47a38a9 --- /dev/null +++ b/cores/realtek-ambz/base/fixups/.clang-format @@ -0,0 +1,2 @@ +DisableFormat: true +SortIncludes: Never diff --git a/cores/realtek-ambz/base/fixups/app_start_patch.c b/cores/realtek-ambz/base/fixups/app_start_patch.c index 7d12206..0778a50 100644 --- a/cores/realtek-ambz/base/fixups/app_start_patch.c +++ b/cores/realtek-ambz/base/fixups/app_start_patch.c @@ -75,7 +75,7 @@ void APP_InitTrace(void) } -extern void main(void); +extern void lt_main(void); // The Main App entry point void APP_Start(void) @@ -112,7 +112,7 @@ void APP_Start(void) "mov sp, r0\n" ); - main(); + lt_main(); #endif // end of #if CONFIG_APP_DEMO #endif // end of else of "#ifdef CONFIG_MBED_ENABLED" }