[beken-72xx] Update base core to new structure

This commit is contained in:
Kuba Szczodrzyński
2023-03-04 11:09:27 +01:00
parent c579219427
commit bc328657aa
58 changed files with 510 additions and 392 deletions

View File

@@ -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

View File

@@ -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(
"+<security/*.c>",
"+<spidma/*.c>",
"+<sys_ctrl/*.c>",
"+<uart/*.c>",
"+<uart/uart.c>",
"+<wdt/*.c>",
"ARDUINO" in env and "-<uart/printf.c>",
],
includes=[
"+<common>",
@@ -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)

View File

@@ -52,7 +52,6 @@ env.Append(
"-mfpu=fpv4-sp-d16",
"-g",
"--specs=nano.specs",
"-nostartfiles",
"-Os",
"-Wl,--gc-sections",
"-Wl,--cref",

View File

@@ -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=[
"+<variant.cpp>",
],
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()

View File

@@ -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()

View File

@@ -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()

View File

@@ -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=[
"+<fixups/*.c*>",
],
includes=[
"!<fixups>",
],
)
return True
@@ -56,6 +52,8 @@ def env_add_core_sources(env: Environment, name: str, path: str) -> bool:
"+<*.c*>",
"+<common/*.c*>",
"+<compat/*.c*>",
"+<fixups/*.c*>",
"+<port/*.c*>",
"+<posix/*.c>",
"+<wraps/*.c>",
],
@@ -63,6 +61,9 @@ def env_add_core_sources(env: Environment, name: str, path: str) -> bool:
# prepend the paths before SDK directories
"!<.>",
"!<compat>",
"!<config>",
"!<fixups>",
"!<port>",
],
)
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

View File

@@ -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")

View File

@@ -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() {

View File

@@ -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

View File

@@ -4,3 +4,4 @@
#define LT_ARD_HAS_WIFI 1
#define LT_ARD_HAS_MD5 1
#define LT_ARD_HAS_SERIAL 1

View File

@@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: Never

View File

@@ -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();
}

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,29 @@
/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */
#include "lt_family_api.h"
#include <start_type_pub.h>
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;
}
}

View File

@@ -1,10 +1,9 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-19. */
#include <lt_logger.h>
#include <sdk_extern.h>
#include <libretuya.h>
#include <sdk_private.h>
#include <fal.h>
#include <flash_pub.h>
#define FLASH_ERASE_MIN_SIZE (4 * 1024)

View File

@@ -1,11 +1,8 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-19. */
#include <printf_config.h>
#include <libretuya.h>
#include <printf/printf.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
extern void bk_send_byte(uint8_t uport, uint8_t data);
extern int uart_print_port;

View File

@@ -4,4 +4,12 @@
#include <printf_config.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
WRAP_DISABLE_DEF(bk_printf);
#ifdef __cplusplus
} // extern "C"
#endif

View File

@@ -1,20 +0,0 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-18. */
#pragma once
#include <stddef.h>
// Beken SDK is actually pretty good, in terms of declaring
// stdlib functions properly! So no need for any #define hell.
#include <mem_pub.h>
// All the MemMang functions are in stdlib, just wrapped
// during linking.
#include <stdlib.h>
// for memcpy etc.
#include <string.h>
// ...except zalloc, which is apparently not in the stdlib
#define zalloc os_zalloc
#define LT_HEAP_FUNC xPortGetFreeHeapSize

View File

@@ -2,23 +2,17 @@
#pragma once
// for printf() etc (they are wrapped anyway)
#include <stdio.h>
// most stuff is here
#include <include.h>
// for os_printf
#include <uart_pub.h>
// for GPIO names
// other includes
#include <flash_pub.h>
#include <gpio_pub.h>
#include <uart_pub.h>
// conflict with stl_algobase.h
#undef min
#undef max
// include printf() wrapper disable methods
#include <printf_port.h>
// make non-SDK code call the proper printf()
#undef bk_printf
#undef os_printf

View File

@@ -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.
*

View File

@@ -7,18 +7,6 @@
#include "LibreTuyaAPI.h"
#include <core/ChipType.h>
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.

View File

@@ -0,0 +1,57 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-14. */
#pragma once
// LibreTuya C API (with C standard libraries)
#include <libretuya.h>
// C++ standard libraries
#ifdef __cplusplus
#include <algorithm>
#include <cmath>
using ::round;
using std::abs;
using std::isinf;
using std::isnan;
using std::max;
using std::min;
#endif
// Arduino Core and LT class
#include <api/ArduinoAPI.h>
#ifdef __cplusplus
#include <LT.h>
#endif
// Include family-specific code
#include <ArduinoFamily.h>
// 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 <SerialClass.h>
#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

View File

@@ -1,25 +0,0 @@
/* Copyright (c) Kuba Szczodrzyński 2022-07-04. */
#pragma once
#include <Arduino.h>
#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

View File

@@ -0,0 +1,39 @@
/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */
#include <Arduino.h>
// 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();
}
}

View File

@@ -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);
}

View File

@@ -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

View File

@@ -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).
*/

View File

@@ -2,32 +2,12 @@
#pragma once
#include "LibreTuyaAPI.h"
#include <Arduino.h>
#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);

View File

@@ -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 <fal_def.h>
/**
* @brief Root partition table, representing the entire flash.
* @brief "Root" partition entry, representing the entire flash.
*/
extern fal_partition_t fal_root_part;

View File

@@ -36,9 +36,8 @@
/* MCU Endian Configuration, default is Little Endian Order. */
// #define FDB_BIG_ENDIAN
#include <printf_config.h>
#if LT_DEBUG_FDB
#include <libretuya.h>
#include <printf/printf.h>
#define FDB_PRINT(...) __wrap_printf(__VA_ARGS__)
#define FDB_DEBUG_ENABLE

View File

@@ -2,7 +2,11 @@
#pragma once
#include <LibreTuyaConfig.h>
#include <lt_config.h>
#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

View File

@@ -12,18 +12,6 @@
#include <stdlib.h>
#include <string.h>
// C++ standard libraries
#ifdef __cplusplus
#include <algorithm>
#include <cmath>
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 <Arduino.h>
// 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 <lt_family.h>
// Board variant (pin definitions)
#include <variant.h>
// 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 <printf_port.h>

View File

@@ -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;

View File

@@ -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;
}
}
}

View File

@@ -0,0 +1,35 @@
/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */
#pragma once
#include <libretuya.h>
#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

View File

@@ -0,0 +1,18 @@
/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */
#pragma once
#include <libretuya.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* @brief Get the reason of last chip reset.
*/
ResetReason lt_get_reset_reason();
#ifdef __cplusplus
} // extern "C"
#endif

View File

@@ -2,10 +2,17 @@
#include "lt_logger.h"
#include <Arduino.h>
#include <printf/printf.h>
#include <stdarg.h>
#include <stdint.h>
#if LT_LOGGER_TASK && LT_HAS_FREERTOS
#if LT_HAS_PRINTF
#include <printf/printf.h>
#include <printf_port.h>
#else
#include <stdio.h>
#endif
#if (LT_LOGGER_TIMESTAMP || LT_LOGGER_TASK) && LT_HAS_FREERTOS
#include <FreeRTOS.h>
#include <task.h>
#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) {

View File

@@ -2,8 +2,11 @@
#pragma once
#include "LibreTuyaConfig.h"
#include <stdint.h>
#include <libretuya.h>
#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

View File

@@ -1,74 +1,28 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-19. */
#include <Arduino.h>
#include <api/HardwareSerial.h>
#include <libretuya.h>
using namespace arduino;
extern "C" {
#include <fal.h>
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();
}

View File

@@ -1,7 +1,9 @@
/* Copyright (c) Kuba Szczodrzyński 2022-05-16. */
#include <sys/time.h>
#include <time.h>
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);

View File

@@ -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;

View File

@@ -1,7 +1,8 @@
/* Copyright (c) Kuba Szczodrzyński 2022-05-16. */
#include <stddef.h>
#include <sdk_mem.h>
#include <stdlib.h>
#include <string.h>
__attribute__((weak)) char *strdup(const char *s) {
size_t len = strlen(s) + 1;

View File

@@ -1,7 +0,0 @@
/* Copyright (c) Kuba Szczodrzyński 2022-04-29. */
#pragma once
#include <time.h>
extern char *strptime(const char *buf, const char *fmt, struct tm *tm);

View File

@@ -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();

View File

@@ -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

View File

@@ -0,0 +1,7 @@
/* Copyright (c) Kuba Szczodrzyński 2023-02-27. */
#include "lt_family_api.h"
ResetReason getResetReason() {
return RESET_REASON_UNKNOWN;
}

View File

@@ -1,7 +1,9 @@
/* Copyright (c) Kuba Szczodrzyński 2022-05-24. */
#include <libretuya.h>
#include <sdk_private.h>
#include <fal.h>
#include <flash_api.h>
#define FLASH_ERASE_MIN_SIZE (4 * 1024)

View File

@@ -1,11 +1,8 @@
/* Copyright (c) Kuba Szczodrzyński 2022-06-19. */
#include <printf_config.h>
#include <libretuya.h>
#include <printf/printf.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#define LOG_UART_REG_BASE 0x40003000
#define UART0_REG_BASE 0x40040000

View File

@@ -4,7 +4,15 @@
#include <printf_config.h>
#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

View File

@@ -17,5 +17,3 @@ extern void vPortFree(void *pv);
#define calloc pvPortCalloc
#define realloc pvPortReAlloc
#define free vPortFree
#define LT_HEAP_FUNC xPortGetFreeHeapSize

View File

@@ -18,6 +18,7 @@
#undef strtoul
#include <ameba_soc.h>
#include <flash_api.h>
#include <gpio_api.h>
#include <main.h>
#include <rand.h>
@@ -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 <printf_port.h>

View File

@@ -0,0 +1,7 @@
#pragma once
#error "Don't include this file directly"
#define LT_HAS_PRINTF 1
#define LT_HEAP_FUNC xPortGetFreeHeapSize

View File

@@ -0,0 +1,2 @@
DisableFormat: true
SortIncludes: Never

View File

@@ -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"
}