diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 50bf218..8794182 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -18,25 +18,28 @@ jobs: with: python-version: '3.10' - - name: Install ltchiptool - run: pip install ltchiptool + - name: Install docs dependencies + run: pip install -U ltchiptool boardgen - - name: Generate static JSON files + - name: Generate docs and static JSON files run: | mkdir -p site/ - python docs/build_json.py + boardgen ltci + python docs/scripts/update_docs.py + python docs/scripts/prepare_doxygen.py + python docs/scripts/build_json.py cp *.json site/ - name: Set custom domain run: | mkdir -p site/ - echo docs.libretuya.ml > site/CNAME + echo docs.libretiny.eu > site/CNAME - name: Deploy docs - uses: libretuya/mkdocs-deploy-gh-pages@master + uses: libretiny-eu/mkdocs-deploy-gh-pages@master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CONFIG_FILE: mkdocs.yml EXTRA_PACKAGES: build-base doxygen REQUIREMENTS: docs/requirements.txt - CUSTOM_DOMAIN: docs.libretuya.ml + CUSTOM_DOMAIN: docs.libretiny.eu diff --git a/.gitignore b/.gitignore index e0759e9..d4c122c 100644 --- a/.gitignore +++ b/.gitignore @@ -258,3 +258,9 @@ xml/ ltapi/ hashChanges.yaml .piopm + +# board files +docs/status/supported_*.md +docs/status/unsupported_boards_*.md +boards/**/*.svg +boards/**/*.md diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 4265a1e..0000000 --- a/.gitmodules +++ /dev/null @@ -1,2 +0,0 @@ -[submodule "tools/boardgen"] - url = https://github.com/kuba2k2/boardgen diff --git a/README.md b/README.md index 0130107..6a8420b 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,45 @@ -# LibreTuya +# LibreTiny
-[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/kuba2k2/libretuya/Deploy%20docs%20on%20GitHub%20Pages?label=docs&logo=markdown)](https://kuba2k2.github.io/libretuya/) -![GitHub last commit](https://img.shields.io/github/last-commit/kuba2k2/libretuya?logo=github) +[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/kuba2k2/libretiny/Deploy%20docs%20on%20GitHub%20Pages?label=docs&logo=markdown)](https://kuba2k2.github.io/libretiny/) +![GitHub last commit](https://img.shields.io/github/last-commit/kuba2k2/libretiny?logo=github) [![Code style: clang-format](https://img.shields.io/badge/code%20style-clang--format-purple.svg)](.clang-format) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![Discord](https://img.shields.io/discord/967863521511608370?color=%235865F2&label=Discord&logo=discord&logoColor=white)](https://discord.gg/SyGCB9Xwtf) -[![PlatformIO Registry](https://badges.registry.platformio.org/packages/kuba2k2/platform/libretuya.svg)](https://registry.platformio.org/platforms/kuba2k2/libretuya) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/kuba2k2/platform/libretiny.svg)](https://registry.platformio.org/platforms/kuba2k2/libretiny) ![RTL8710BN](https://img.shields.io/badge/-rtl8710bn-blue) ![BK7231](https://img.shields.io/badge/-bk7231-blue)
+## LibreTuya is now LibreTiny! 🎉 + +We have [renamed the project](https://github.com/kuba2k2/libretiny/issues/92) to LibreTiny, also marking the very first v1.0.0 release, along with a huge structure refactor. While some care has been taken to ensure that things don't break, you may still need to update some references in your code to use the new name. + +--- + PlatformIO development platform for IoT modules manufactured by Tuya Inc. The main goal of this project is to provide a usable build environment for IoT developers. While also providing vendor SDKs as PlatformIO cores, the project focuses on developing working Arduino-compatible cores for supported families. The cores are inspired by Espressif's official core for ESP32, -which should make it easier to port/run existing ESP apps on Tuya IoT (and 3-rd party) modules. +which should make it easier to port/run existing ESP apps on less-common, unsupported IoT modules. -**There's an [ESPHome port](https://docs.libretuya.ml/docs/projects/esphome/) based on LibreTuya, which supports BK7231 and RTL8710B chips.** +**There's an [ESPHome port](https://docs.libretiny.eu/docs/projects/esphome/) based on LibreTiny, which supports BK7231 and RTL8710B chips.** **Note:** this project is work-in-progress. ## Usage 1. [Install PlatformIO](https://platformio.org/platformio-ide) -2. `platformio platform install https://github.com/kuba2k2/libretuya` +2. `platformio platform install -f https://github.com/kuba2k2/libretiny` 3. Create a project, build it and upload! -4. See the [docs](https://docs.libretuya.ml/) for any questions/problems. +4. See the [docs](https://docs.libretiny.eu/) for any questions/problems. + ## License diff --git a/SUMMARY.md b/SUMMARY.md index 7badd4c..fbe2623 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -1,58 +1,56 @@ * [Home](README.md) +* [](SUMMARY.md) * [😊 Getting started](docs/getting-started/README.md) - * [ESPHome](docs/projects/esphome.md) -* [đŸ“Č Flashing/dumping](docs/flashing/) -* [đŸ’» Supported boards & chips](docs/status/supported.md) -* 📖 Reference - * Chip families - * [Beken BK72xx](docs/platform/beken-72xx/README.md) - * [Realtek Ameba - info](docs/platform/realtek-amb/README.md) - * [Realtek AmebaZ](docs/platform/realtek-ambz/README.md) - * [Debugging](docs/platform/realtek-ambz/debugging.md) - * [Exception decoder](docs/platform/realtek-ambz/exception-decoder.md) - * C library - * [Built-in functions](docs/platform/realtek-ambz/stdlib.md) - * [Memory management](docs/platform/realtek-ambz/memory-management.md) - * [🔧 LT configuration](docs/reference/config.md) - * [✔ Implementation status](docs/status/arduino.md) - * [🔌 Boards documentation](boards/) - * [🔋 Examples](examples/) - * [📖 LibreTuya API](docs/reference/lt-api.md) - * [LT class reference](ltapi/class_libre_tuya.md) - * [Common methods](ltapi/_libre_tuya_a_p_i_8h.md) - * [Wiring custom methods](ltapi/_libre_tuya_custom_8h.md) - * [Logger](ltapi/lt__logger_8h.md) - * [Chip & family IDs](ltapi/_chip_type_8h_source.md) - * [POSIX utilities](ltapi/lt__posix__api_8h.md) - * 📖 Common API - * [FS](ltapi/classfs_1_1_f_s.md) - * [Preferences](ltapi/class_i_preferences.md) + * [âžĄïž Info on accessing GPIOs](docs/getting-started/gpio.md) +* [💡 ESPHome setup guide](docs/projects/esphome.md) +* [đŸ“Č Flashing/dumping guide](docs/flashing/) +* [🔌 How to connect the chip in download mode?](docs/flashing/chip-connection/) +* [đŸ’» Supported chips](docs/status/supported.md) + * [All boards](boards/) +* [](SUMMARY.md) +* đŸȘ Chip family docs & info + * [Beken BK72xx](docs/platform/beken-72xx/README.md) + * [Realtek Ameba - info](docs/platform/realtek-amb/README.md) + * [Realtek AmebaZ](docs/platform/realtek-ambz/README.md) + * [Debugging](docs/platform/realtek-ambz/debugging.md) + * [Exception decoder](docs/platform/realtek-ambz/exception-decoder.md) +* [🔧 LT Configuration](docs/dev/config.md) +* 🧑 Programmer's manual + * [⚠ Migration guide](docs/dev/migration_v1.0.0.md) + * [🔋 PlatformIO Examples](examples/) + * [📖 LibreTiny API](docs/dev/lt-api.md) + * [C API](ltapi/dir_c7e317b16142bccc961a83c0babf0065.md) + * [C++ API](ltapi/dir_930634efd5dc4a957bbb6e685a3ccda1.md) + * 📚 Arduino Libraries * [SoftwareSerial](ltapi/class_software_serial.md) - * [WiFi API](ltapi/class_wi_fi_class.md) - * [TCP Client](ltapi/class_i_wi_fi_client.md) - * [SSL Client](ltapi/class_i_wi_fi_client_secure.md) - * [TCP Server](ltapi/class_i_wi_fi_server.md) - * [📖 LibreTuya libraries](docs/libs-built-in.md) - * [base64](ltapi/classbase64.md) + * [WiFi](ltapi/class_wi_fi_class.md) + * [](SUMMARY.md) * [Flash](ltapi/class_flash_class.md) - * [HTTPClient](ltapi/class_h_t_t_p_client.md) + * [IPv6Address](ltapi/classarduino_1_1_i_pv6_address.md) + * [MD5](ltapi/libraries_2common_2_m_d5_2_m_d5_8h.md) * [mDNS](ltapi/classm_d_n_s.md) - * NetUtils - * [ssl/MbedTLSClient](ltapi/class_mbed_t_l_s_client.md) - * [IPv6Address](ltapi/classarduino_1_1_i_pv6_address.md) - * [LwIPRxBuffer](ltapi/class_lw_i_p_rx_buffer.md) * [Update](ltapi/class_update_class.md) + * [WiFiClient](ltapi/class_i_wi_fi_client.md) + * [WiFiClientSecure](ltapi/class_i_wi_fi_client_secure.md) + * [WiFiServer](ltapi/class_i_wi_fi_server.md) + * [WiFiUDP](ltapi/class_i_wi_fi_u_d_p.md) + * [](SUMMARY.md) + * [HTTPClient](ltapi/class_h_t_t_p_client.md) + * [StreamString](ltapi/class_stream_string.md) * [WebServer](ltapi/class_web_server.md) * [WiFiMulti](ltapi/class_wi_fi_multi.md) - * [Third party libraries](docs/libs-3rd-party.md) + * [](SUMMARY.md) + * [External compatible libraries](docs/dev/libs-3rd-party.md) * Full documentation * [Classes](ltapi/classes.md) * [Functions](ltapi/functions.md) * [Macros](ltapi/macros.md) * [File list](ltapi/files.md) - * [📁 Project structure](docs/reference/project-structure.md) - * [✈ OTA format](docs/ota/README.md) - * [uf2ota.py tool](docs/ota/uf2ota.md) - * [uf2ota.h library](docs/ota/library.md) - * [📓 TODO](TODO.md) +* đŸ‘· Contributor's manual (WIP) + * [📁 Project structure](docs/dev/project-structure.md) + * [✈ OTA format](docs/dev/ota/README.md) + * [uf2ota.py tool](docs/dev/ota/uf2ota.md) + * [uf2ota.h library](docs/dev/ota/library.md) + * [📓 TODO](docs/TODO.md) +* [](SUMMARY.md) * [🔗 Resources](docs/resources/) diff --git a/arduino/beken-72xx/cores/arduino/Arduino.h b/arduino/beken-72xx/cores/arduino/Arduino.h deleted file mode 100644 index c2df300..0000000 --- a/arduino/beken-72xx/cores/arduino/Arduino.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-14. */ - -#pragma once - -#ifdef __cplusplus -#include "WCharacterFixup.h" -#endif - -#define delay delayMilliseconds // change delay()'s signature - it's defined as static inline in WVariant.h -#include -#include -#undef delay - -// 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 -#include "SerialClass.h" -#include -#endif diff --git a/arduino/beken-72xx/cores/arduino/LibreTuyaAPI.cpp b/arduino/beken-72xx/cores/arduino/LibreTuyaAPI.cpp deleted file mode 100644 index 0c36da2..0000000 --- a/arduino/beken-72xx/cores/arduino/LibreTuyaAPI.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-19. */ - -#include -#include - -// can't include as it collides with on Windows -_- -#define REG_FLASH_BASE 0x00803000 -#define REG_FLASH_OPERATE_SW (REG_FLASH_BASE + 0 * 4) -#define REG_FLASH_RDID (REG_FLASH_BASE + 4 * 4) -#define FLASH_BUSY_SW (0x01UL << 31) -#define FLASH_WP_VALUE (0x01UL << 30) -#define FLASH_OP_SW (0x01UL << 29) -#define FLASH_OP_TYPE_POS 24 -#define FLASH_OP_RDID 20 - -extern "C" { - -#include -#include -#include -#include -#include -#include -#include - -extern uint8_t system_mac[]; -extern uint32_t wdt_ctrl(uint32_t cmd, void *param); - -} // extern "C" - -void LibreTuya::restart() { - bk_reboot(); -} - -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() { - uint8_t chipId = *(uint8_t *)(SCTRL_CHIP_ID); - return CHIP_TYPE_ENUM(FAMILY, chipId); -} - -const char *LibreTuya::getChipModel() { - return STRINGIFY_MACRO(MCU); -} - -uint32_t LibreTuya::getChipId() { - uint8_t mac[6]; - cfg_load_mac(mac); // force loading MAC from TLV (ignore user-set WiFi MAC) - return (mac[3]) | (mac[4] << 8) | (mac[5] << 16); -} - -uint8_t LibreTuya::getChipCores() { - return 1; -} - -const char *LibreTuya::getChipCoreType() { - return "ARM968E-S"; -} - -uint32_t LibreTuya::getCpuFreq() { - return configCPU_CLOCK_HZ; -} - -uint32_t LibreTuya::getCycleCount() { - // TODO - return 0; -} - -/* Flash memory utilities */ - -FlashId LibreTuya::getFlashChipId() { - uint32_t data = (FLASH_OP_RDID << FLASH_OP_TYPE_POS) | FLASH_OP_SW | FLASH_WP_VALUE; - REG_WRITE(REG_FLASH_OPERATE_SW, data); - while (REG_READ(REG_FLASH_OPERATE_SW) & FLASH_BUSY_SW) {} - FlashId id = { - .manufacturerId = REG_RD8(REG_FLASH_RDID, 2), - .chipId = REG_RD8(REG_FLASH_RDID, 1), - .chipSizeId = REG_RD8(REG_FLASH_RDID, 0), - }; - return id; -} - -/* Memory management */ - -uint32_t LibreTuya::getRamSize() { - return 256 * 1024; -} - -uint32_t LibreTuya::getHeapSize() { -#if configDYNAMIC_HEAP_SIZE - extern unsigned char _empty_ram; -#if CFG_SOC_NAME == SOC_BK7231N - return (0x00400000 + 192 * 1024) - (uint32_t)(&_empty_ram); -#else - return (0x00400000 + 256 * 1024) - (uint32_t)(&_empty_ram); -#endif -#else - return configTOTAL_HEAP_SIZE; -#endif -} - -uint32_t LibreTuya::getFreeHeap() { - return xPortGetFreeHeapSize(); -} - -uint32_t LibreTuya::getMinFreeHeap() { - return xPortGetMinimumEverFreeHeapSize(); -} - -uint32_t LibreTuya::getMaxAllocHeap() { - return 0; -} - -/* OTA-related */ - -static int8_t otaImage2Valid = -1; - -uint8_t LibreTuya::otaGetRunning() { - // Beken has bootloader-based OTA, running app is always index 1 - return 1; -} - -uint8_t LibreTuya::otaGetStoredIndex() { - return otaHasImage2() ? 2 : 1; -} - -bool LibreTuya::otaSupportsDual() { - return true; -} - -bool LibreTuya::otaHasImage1() { - return true; -} - -bool LibreTuya::otaHasImage2() { - if (otaImage2Valid != -1) - return otaImage2Valid; - // check download RBL - // TODO: maybe check header CRC or even binary hashes - uint32_t magic; - Flash.readBlock(FLASH_DOWNLOAD_OFFSET, (uint8_t *)&magic, 4); - otaImage2Valid = magic == 0x004C4252; // "RBL\0", little-endian - return otaImage2Valid; -} - -bool LibreTuya::otaSwitch(bool force) { - // no need to check otaGetStoredIndex() as it does the same as otaHasImage2() - - // force checking validity again - otaImage2Valid = -1; - - if (otaHasImage2() && force) { - // "rollback" - abort bootloader upgrade operation by wiping first sector - return Flash.eraseSector(FLASH_DOWNLOAD_OFFSET); - } - - return otaHasImage2(); // false if second image is not valid -} - -/* Watchdog */ - -bool LibreTuya::wdtEnable(uint32_t timeout) { - wdt_ctrl(WCMD_SET_PERIOD, &timeout); - wdt_ctrl(WCMD_POWER_UP, NULL); -} - -void LibreTuya::wdtDisable() { - wdt_ctrl(WCMD_POWER_DOWN, NULL); -} - -void LibreTuya::wdtFeed() { - wdt_ctrl(WCMD_RELOAD_PERIOD, NULL); -} - -/* Global instance */ - -LibreTuya LT; -LibreTuya ESP = LT; diff --git a/arduino/beken-72xx/cores/arduino/WVariant.h b/arduino/beken-72xx/cores/arduino/WVariant.h deleted file mode 100644 index cbe3777..0000000 --- a/arduino/beken-72xx/cores/arduino/WVariant.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-18. */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "sdk_extern.h" -#include "sdk_mem.h" - -// define an inline delay() which overrides BDK's delay() -static inline __attribute__((always_inline)) void delay(unsigned long ms) { - delayMilliseconds(ms); -} - -// from fixups/arch_main.c -extern unsigned char __bk_rf_is_init; - -#ifdef __cplusplus -} // extern "C" -#endif diff --git a/arduino/beken-72xx/cores/arduino/sdk_extern.h b/arduino/beken-72xx/cores/arduino/sdk_extern.h deleted file mode 100644 index 535c87e..0000000 --- a/arduino/beken-72xx/cores/arduino/sdk_extern.h +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-18. */ - -#pragma once - -// for printf() etc (they are wrapped anyway) -#include - -// most stuff is here -#include -// for os_printf -#include -// for GPIO names -#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 -#undef warning_prf -#undef fatal_prf -#define bk_printf printf -#define os_printf printf -#define warning_prf printf -#define fatal_prf printf diff --git a/arduino/beken-72xx/cores/arduino/sdk_mem.h b/arduino/beken-72xx/cores/arduino/sdk_mem.h deleted file mode 100644 index e61ab14..0000000 --- a/arduino/beken-72xx/cores/arduino/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/arduino/beken-72xx/libraries/MD5/MD5Impl.h b/arduino/beken-72xx/libraries/MD5/MD5Impl.h deleted file mode 100644 index 11d2134..0000000 --- a/arduino/beken-72xx/libraries/MD5/MD5Impl.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-11. */ - -#pragma once - -#define LT_MD5_USE_HOSTAPD 1 diff --git a/arduino/beken-72xx/libraries/WiFi/WiFi.h b/arduino/beken-72xx/libraries/WiFi/WiFi.h deleted file mode 100644 index 8d5fcad..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFi.h +++ /dev/null @@ -1,10 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-26. */ - -#pragma once - -#include -#include - -#include "WiFiClient.h" -#include "WiFiClientSecure.h" -#include "WiFiServer.h" diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiClient.h b/arduino/beken-72xx/libraries/WiFi/WiFiClient.h deleted file mode 100644 index eb27361..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFiClient.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ - -#pragma once - -#include -#include - -typedef LwIPClient WiFiClient; diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiClientSecure.h b/arduino/beken-72xx/libraries/WiFi/WiFiClientSecure.h deleted file mode 100644 index 3addedf..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFiClientSecure.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-04. */ - -#pragma once - -#include -#include - -typedef MbedTLSClient WiFiClientSecure; diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiData.h b/arduino/beken-72xx/libraries/WiFi/WiFiData.h deleted file mode 100644 index b572acb..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFiData.h +++ /dev/null @@ -1,25 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-26. */ - -#pragma once - -#include - -extern "C" { - -#include -#include -#include - -} // extern "C" - -typedef struct { - void *configSta; - void *configAp; - unsigned long scannedAt; - SemaphoreHandle_t scanSem; - void *statusIp; - void *statusLink; - rw_evt_type lastStaEvent; - rw_evt_type lastApEvent; - bool apEnabled; -} WiFiData; diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiServer.h b/arduino/beken-72xx/libraries/WiFi/WiFiServer.h deleted file mode 100644 index db8df0b..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFiServer.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ - -#pragma once - -#include -#include - -typedef LwIPServer WiFiServer; diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiUdp.h b/arduino/beken-72xx/libraries/WiFi/WiFiUdp.h deleted file mode 100644 index 8b60be1..0000000 --- a/arduino/beken-72xx/libraries/WiFi/WiFiUdp.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-09-10. */ - -#pragma once - -#include -#include - -typedef LwIPUDP WiFiUDP; diff --git a/arduino/libretuya/core/ChipType.h b/arduino/libretuya/core/ChipType.h deleted file mode 100644 index 7faca88..0000000 --- a/arduino/libretuya/core/ChipType.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-28. */ - -#pragma once - -#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 { - // used in UF2 Family ID - F_RTL8710A = 0x9FFFD543, // Realtek Ameba1 - F_RTL8710B = 0x22E0D6FC, // Realtek AmebaZ (realtek-ambz) - F_RTL8720C = 0xE08F7564, // Realtek AmebaZ2 - F_RTL8720D = 0x3379CFE2, // Realtek AmebaD - F_BK7231U = 0x675A40B0, // Beken 7231U/7231T - F_BK7231N = 0x7B3EF230, // Beken 7231N - F_BK7251 = 0x6A82CC42, // Beken 7251/7252 - F_BL602 = 0xDE1270B7, // Boufallo 602 - F_XR809 = 0x51E903A8, // Xradiotech 809 - F_NATIVE = 0xDEADBEEF, // Host-native -}; - -enum ChipType { - // Realtek AmebaZ - // IDs copied from rtl8710b_efuse.h - RTL8710BL = CHIP_TYPE(F_RTL8710B, 0xE0), // ??? - RTL8710BN = CHIP_TYPE(F_RTL8710B, 0xFF), // CHIPID_8710BN / QFN32 - RTL8710BU = CHIP_TYPE(F_RTL8710B, 0xFE), // CHIPID_8710BU / QFN48 - RTL8710BX = CHIP_TYPE(F_RTL8710B, 0xF6), // found on an actual RTL8710BX - RTL8710L0 = CHIP_TYPE(F_RTL8710B, 0xFB), // CHIPID_8710BN_L0 / QFN32 - RTL8711BN = CHIP_TYPE(F_RTL8710B, 0xFD), // CHIPID_8711BN / QFN48 - RTL8711BU = CHIP_TYPE(F_RTL8710B, 0xFC), // CHIPID_8711BG / QFN68 - // Beken 72XX - BK7231T = CHIP_TYPE(F_BK7231U, 0x1A), // *SCTRL_CHIP_ID = 0x7231a - 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 -}; diff --git a/arduino/libretuya/core/LibreTuyaAPI.cpp b/arduino/libretuya/core/LibreTuyaAPI.cpp deleted file mode 100644 index 3304f27..0000000 --- a/arduino/libretuya/core/LibreTuyaAPI.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* 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); -} - -/** - * @brief Generate random bytes using rand(). - * - * @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; - for (i = 0; len >= sizeof(int); len -= sizeof(int)) { - data[i++] = rand(); - } - if (len) { - int rem = rand(); - unsigned char *pRem = (unsigned char *)&rem; - memcpy(buf + i * sizeof(int), pRem, len); - } -} - -#undef putchar - -/** - * @brief Print data pointed to by buf in hexdump-like format (hex+ASCII). - * - * @param buf source pointer - * @param len how many bytes to print - * @param offset increment printed offset by this value - * @param width how many bytes on a line - */ -void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width) { - uint16_t pos = 0; - while (pos < len) { - // print hex offset - printf("%06x ", offset + pos); - // calculate current line width - uint8_t lineWidth = min(width, len - pos); - // print hexadecimal representation - for (uint8_t i = 0; i < lineWidth; i++) { - if (i % 8 == 0) { - printf(" "); - } - printf("%02x ", buf[pos + i]); - } - // print ascii representation - printf(" |"); - for (uint8_t i = 0; i < lineWidth; i++) { - char c = buf[pos + i]; - putchar((c >= 0x20 && c <= 0x7f) ? c : '.'); - } - puts("|\r"); - pos += lineWidth; - } -} -} diff --git a/arduino/libretuya/core/LibreTuyaAPI.h b/arduino/libretuya/core/LibreTuyaAPI.h deleted file mode 100644 index d649368..0000000 --- a/arduino/libretuya/core/LibreTuyaAPI.h +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-28. */ - -#pragma once - -// C standard libraries -#include -#include -#include -#include -#include -#include -#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 -#endif -#ifndef LT_BOARD -#define LT_BOARD unknown -#endif -#define STRINGIFY(x) #x -#define STRINGIFY_MACRO(x) STRINGIFY(x) -#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( \ - LT_LEVEL_INFO, \ - __FUNCTION__, \ - __LINE__, \ - "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 diff --git a/arduino/libretuya/core/LibreTuyaClass.cpp b/arduino/libretuya/core/LibreTuyaClass.cpp deleted file mode 100644 index 4cf53dd..0000000 --- a/arduino/libretuya/core/LibreTuyaClass.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-06. */ - -#include "LibreTuyaClass.h" - -/** - * @brief Get LibreTuya version string. - */ -const char *LibreTuya::getVersion() { - return LT_VERSION_STR; -} - -/** - * @brief Get board name. - */ -const char *LibreTuya::getBoard() { - return LT_BOARD_STR; -} - -/** - * @brief Get CPU family ID. - */ -ChipFamily LibreTuya::getChipFamily() { - return FAMILY; -} - -/** - * @brief Get CPU family name as string. - */ -const char *LibreTuya::getChipFamilyName() { - return STRINGIFY_MACRO(FAMILY) + 2; -} - -static char *deviceName = NULL; - -/** - * @brief Get device friendly name in format "LT--". - * Can be used as hostname. - */ -const char *LibreTuya::getDeviceName() { - if (deviceName) - return deviceName; - uint32_t chipId = getChipId(); - uint8_t *id = (uint8_t *)&chipId; - - const char *board = getBoard(); - uint8_t boardLen = strlen(board); - deviceName = (char *)malloc(3 + boardLen + 1 + 6 + 1); - - sprintf(deviceName, "LT-%s-%02x%02x%02x", board, id[0], id[1], id[2]); - return deviceName; -} - -/** - * @brief Get a textual representation of a reset reason. - * - * @param reason value to convert to text, uses getResetReason() by default - */ -const char *LibreTuya::getResetReasonName(ResetReason reason) { - if (reason >= RESET_REASON_MAX) - reason = getResetReason(); - switch (reason) { - case RESET_REASON_POWER: - return "Power-On"; - case RESET_REASON_BROWNOUT: - return "Brownout"; - case RESET_REASON_HARDWARE: - return "HW Reboot"; - case RESET_REASON_SOFTWARE: - return "SW Reboot"; - case RESET_REASON_WATCHDOG: - return "WDT Reset"; - case RESET_REASON_CRASH: - return "Crash"; - case RESET_REASON_SLEEP: - return "Sleep Wakeup"; - } - return "Unknown"; -} - -/** - * @brief Get CPU frequency in MHz. - */ -uint32_t LibreTuya::getCpuFreqMHz() { - return getCpuFreq() / 1000000; -} - -/** - * @brief Get flash chip total size. - * The default implementation uses the least significant - * byte of the chip ID to determine the size. - */ -__attribute__((weak)) uint32_t LibreTuya::getFlashChipSize() { - FlashId id = getFlashChipId(); - if (id.chipSizeId >= 0x14 && id.chipSizeId <= 0x19) { - return (1 << id.chipSizeId); - } -#ifdef FLASH_LENGTH - return FLASH_LENGTH; -#else - return 0; -#endif -} - -/** - * @brief Get the OTA index for updated firmware. - * - * Note: returns 1 for chips without dual-OTA. - */ -uint8_t LibreTuya::otaGetTarget() { - if (!otaSupportsDual()) - return 1; - return otaGetRunning() ^ 0b11; -} - -/** - * @brief Perform OTA rollback: switch to the previous image, or abort current - * switched OTA update, if not rebooted yet. - * - * @return false if no second image to run, writing failed or dual-OTA not supported - */ -bool LibreTuya::otaRollback() { - if (!otaCanRollback()) - return false; - if (otaGetRunning() != otaGetStoredIndex()) - // force switching back to current image - return otaSwitch(true); - return true; -} - -/** - * @brief Check if OTA rollback is supported and available (there is another image to run). - * @return false if no second image to run or dual-OTA not supported - */ -bool LibreTuya::otaCanRollback() { - if (!otaSupportsDual()) - return false; - if (otaGetRunning() == otaGetStoredIndex()) - return true; - if (otaGetRunning() == 1 && otaHasImage1()) - return true; - if (otaGetRunning() == 2 && otaHasImage2()) - return true; - return false; -} - -__attribute__((weak)) void LibreTuya::gpioRecover() { - // nop by default -} diff --git a/arduino/libretuya/core/LibreTuyaClass.h b/arduino/libretuya/core/LibreTuyaClass.h deleted file mode 100644 index be2a42a..0000000 --- a/arduino/libretuya/core/LibreTuyaClass.h +++ /dev/null @@ -1,193 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-06. */ - -#pragma once - -#ifdef __cplusplus - -#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. - */ -typedef struct { - uint8_t manufacturerId; - uint8_t chipId; - uint8_t chipSizeId; -} FlashId; - -/** - * @brief Main LibreTuya API class. - * - * This class contains all functions common amongst all families. - * Implementations of these methods may vary between families. - * - * The class is accessible using the `LT` global object (defined by the family). - */ -class LibreTuya { - public: /* Common methods - note: these are documented in LibreTuyaAPI.cpp */ - const char *getVersion(); - const char *getBoard(); - ChipFamily getChipFamily(); - const char *getChipFamilyName(); - const char *getDeviceName(); - const char *getResetReasonName(ResetReason reason = RESET_REASON_MAX); - uint32_t getCpuFreqMHz(); - uint32_t getFlashChipSize(); - uint8_t otaGetTarget(); - bool otaRollback(); - bool otaCanRollback(); - - public: /* Compatibility methods */ - /** - * @brief Alias of getMaxAllocHeap(). - */ - inline uint32_t getMaxFreeBlockSize() { - return getMaxAllocHeap(); - } - - public: /* Family-defined methods */ - /** - * @brief Reboot the CPU. - */ - void restart(); - /** - * @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. - */ - void gpioRecover(); - - public: /* CPU-related */ - /** - * @brief Get CPU model ID. - */ - ChipType getChipType(); - /** - * @brief Get CPU model name as string. - */ - const char *getChipModel(); - /** - * @brief Get CPU unique ID. This may be based on MAC, eFuse, etc. - * Note: the number should be 24-bit (with most significant byte being zero). - */ - uint32_t getChipId(); - /** - * @brief Get CPU core count. - */ - uint8_t getChipCores(); - /** - * @brief Get CPU core type name as string. - */ - const char *getChipCoreType(); - /** - * @brief Get CPU frequency in Hz. - */ - uint32_t getCpuFreq(); - /** - * @brief Get CPU cycle count. - */ - uint32_t getCycleCount(); - - public: /* Flash memory utilities */ - /** - * @brief Read flash chip ID and return a FlashId struct. - */ - FlashId getFlashChipId(); - - public: /* Memory management */ - /** - * @brief Get total RAM size. - */ - uint32_t getRamSize(); - /** - * @brief Get total heap size. - */ - uint32_t getHeapSize(); - /** - * @brief Get free heap size. - */ - uint32_t getFreeHeap(); - /** - * @brief Get lowest level of free heap memory. - */ - uint32_t getMinFreeHeap(); - /** - * @brief Get largest block of heap that can be allocated at once. - */ - uint32_t getMaxAllocHeap(); - - public: /* OTA-related */ - /** - * @brief Get the currently running firmware OTA index. - */ - uint8_t otaGetRunning(); - /** - * @brief Read the currently active OTA index, i.e. the one that will boot upon restart. - */ - uint8_t otaGetStoredIndex(); - /** - * @brief Check if the chip supports dual-OTA (i.e. OTA is flashed to a different partition). - * - * TODO: make this work for actual dual-OTA chips; remove checking this in otaGetTarget() etc. - */ - bool otaSupportsDual(); - /** - * @brief Check if OTA1 image is valid. - */ - bool otaHasImage1(); - /** - * @brief Check if OTA2 image is valid. - */ - bool otaHasImage2(); - /** - * @brief Try to switch OTA index to the other image. - * - * Note: should return true for chips without dual-OTA. Should return false if one of two images is not valid. - * - * @param force switch even if other image already marked as active - * @return false if writing failed; true otherwise - */ - bool otaSwitch(bool force = false); - - public: /* Watchdog */ - /** - * @brief Enable the hardware watchdog. - * - * @param timeout watchdog timeout, milliseconds (defaults to 10s) - * @return whether the chip has a hardware watchdog - */ - bool wdtEnable(uint32_t timeout = 10000); - /** - * @brief Disable the hardware watchdog. - */ - void wdtDisable(); - /** - * @brief Feed/reset the hardware watchdog timer. - */ - void wdtFeed(); -}; - -extern LibreTuya LT; -extern LibreTuya ESP; - -#endif diff --git a/arduino/libretuya/core/LibreTuyaCompat.cpp b/arduino/libretuya/core/LibreTuyaCompat.cpp deleted file mode 100644 index 203f390..0000000 --- a/arduino/libretuya/core/LibreTuyaCompat.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-04. */ - -#include "LibreTuyaCompat.h" - -#if LT_HAS_FREERTOS -BaseType_t xTaskCreateUniversal( - TaskFunction_t pxTaskCode, - const char *const pcName, - const uint32_t usStackDepth, - void *const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t *const pxCreatedTask, - const BaseType_t xCoreID -) { - // #ifndef CONFIG_FREERTOS_UNICORE - // if (xCoreID >= 0 && xCoreID < 2) { - // return xTaskCreatePinnedToCore( - // pxTaskCode, - // pcName, - // usStackDepth, - // pvParameters, - // uxPriority, - // pxCreatedTask, - // xCoreID - // ); - // } else { - // #endif - return xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask); - // #ifndef CONFIG_FREERTOS_UNICORE - // } - // #endif -} -#endif diff --git a/arduino/libretuya/core/SerialExtern.h b/arduino/libretuya/core/SerialExtern.h deleted file mode 100644 index e404333..0000000 --- a/arduino/libretuya/core/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/arduino/libretuya/core/main.cpp b/arduino/libretuya/core/main.cpp deleted file mode 100644 index bbad290..0000000 --- a/arduino/libretuya/core/main.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-19. */ - -#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 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) { - // 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(); - // 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; -} diff --git a/arduino/libretuya/libraries/Flash/Flash.cpp b/arduino/libretuya/libraries/Flash/Flash.cpp deleted file mode 100644 index f3dc2f9..0000000 --- a/arduino/libretuya/libraries/Flash/Flash.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-24. */ - -#include "Flash.h" - -extern "C" { -#include -} - -// Global Flash object. -FlashClass Flash; - -FlashId FlashClass::getChipId() { - return LT.getFlashChipId(); -} - -uint32_t FlashClass::getSize() { - return LT.getFlashChipSize(); -} - -bool FlashClass::eraseSector(uint32_t offset) { - return fal_partition_erase(fal_root_part, offset, 1) >= 0; -} - -bool FlashClass::readBlock(uint32_t offset, uint8_t *data, size_t size) { - return fal_partition_read(fal_root_part, offset, data, size) >= 0; -} - -bool FlashClass::writeBlock(uint32_t offset, uint8_t *data, size_t size) { - return fal_partition_write(fal_root_part, offset, data, size) >= 0; -} diff --git a/arduino/libretuya/libraries/Flash/Flash.h b/arduino/libretuya/libraries/Flash/Flash.h deleted file mode 100644 index 7e23a02..0000000 --- a/arduino/libretuya/libraries/Flash/Flash.h +++ /dev/null @@ -1,17 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-24. */ - -#pragma once - -#include - -class FlashClass { - public: - FlashId getChipId(); - uint32_t getSize(); - - bool eraseSector(uint32_t offset); - bool readBlock(uint32_t offset, uint8_t *data, size_t size); - bool writeBlock(uint32_t offset, uint8_t *data, size_t size); -}; - -extern FlashClass Flash; diff --git a/arduino/libretuya/libraries/HTTPClient/strptime.h b/arduino/libretuya/libraries/HTTPClient/strptime.h deleted file mode 100644 index 62b9b56..0000000 --- a/arduino/libretuya/libraries/HTTPClient/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/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.cpp b/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.cpp deleted file mode 100644 index 2db16c0..0000000 --- a/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-11. */ - -#if LT_ARD_HAS_MD5 - -#include "MD5.h" - -#if LT_MD5_USE_MBEDTLS - -extern "C" { - -void MD5Init(LT_MD5_CTX_T *context) { - mbedtls_md5_init(context); - mbedtls_md5_starts(context); -} - -void MD5Update(LT_MD5_CTX_T *context, const unsigned char *buf, unsigned len) { - mbedtls_md5_update(context, buf, len); -} - -void MD5Final(unsigned char digest[16], LT_MD5_CTX_T *context) { - mbedtls_md5_finish(context, digest); -} - -} // extern "C" - -#endif // LT_MD5_USE_MBEDTLS - -#endif // LT_ARD_HAS_MD5 diff --git a/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.h b/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.h deleted file mode 100644 index 68fcd48..0000000 --- a/arduino/libretuya/libraries/MD5/MD5MbedTLSImpl.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-11. */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#define LT_MD5_CTX_T mbedtls_md5_context - -#ifdef __cplusplus -} // extern "C" -#endif diff --git a/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.cpp b/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.cpp deleted file mode 100644 index b7265d5..0000000 --- a/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-03. */ - -#if LT_ARD_HAS_MD5 - -#include "MD5.h" - -#if LT_MD5_USE_POLARSSL - -extern "C" { - -void MD5Init(LT_MD5_CTX_T *context) { - md5_init(context); - md5_starts(context); -} - -void MD5Update(LT_MD5_CTX_T *context, const unsigned char *buf, unsigned len) { - md5_update(context, buf, len); -} - -void MD5Final(unsigned char digest[16], LT_MD5_CTX_T *context) { - md5_finish(context, digest); -} - -} // extern "C" - -#endif // LT_MD5_USE_POLARSSL - -#endif // LT_ARD_HAS_MD5 diff --git a/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.h b/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.h deleted file mode 100644 index 778d526..0000000 --- a/arduino/libretuya/libraries/MD5/MD5PolarSSLImpl.h +++ /dev/null @@ -1,14 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-03. */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#define LT_MD5_CTX_T md5_context - -#ifdef __cplusplus -} // extern "C" -#endif diff --git a/arduino/realtek-ambz/cores/arduino/Arduino.h b/arduino/realtek-ambz/cores/arduino/Arduino.h deleted file mode 100644 index 093f7f9..0000000 --- a/arduino/realtek-ambz/cores/arduino/Arduino.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-23. */ - -#pragma once - -#ifdef __cplusplus -#include "WCharacterFixup.h" -#endif - -#define PinMode PinModeArduino // this conflicts with SDK enum -#include -#include -#undef PinMode - -// 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 -#elif defined(PIN_SERIAL0_TX) -#define LT_UART_DEFAULT_PORT 0 -#else -#define LT_UART_DEFAULT_PORT 1 -#endif -#endif - -// Define available serial ports -#ifdef __cplusplus -#include "SerialClass.h" -#include -#endif diff --git a/arduino/realtek-ambz/cores/arduino/LibreTuyaAPI.cpp b/arduino/realtek-ambz/cores/arduino/LibreTuyaAPI.cpp deleted file mode 100644 index c3703d2..0000000 --- a/arduino/realtek-ambz/cores/arduino/LibreTuyaAPI.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-28. */ - -#include - -#include - -extern "C" { -#include -#include -#include -#include -} - -void LibreTuya::restart() { - // The Watchdog Way - wdtEnable(1L); - while (1) {} -} - -void LibreTuya::restartDownloadMode() { - // mww 0x40000138 0x8 - HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_NORESET_FF, 0x08); - // reboot it the ugly way - sys_reset(); - while (1) {} -} - -ResetReason LibreTuya::getResetReason() { - return RESET_REASON_UNKNOWN; -} - -void LibreTuya::gpioRecover() { - // PA14 and PA15 are apparently unusable with SWD enabled - sys_jtag_off(); - Pinmux_Config(PA_14, PINMUX_FUNCTION_GPIO); - Pinmux_Config(PA_15, PINMUX_FUNCTION_GPIO); -} - -/* CPU-related */ - -ChipType LibreTuya::getChipType() { - uint8_t chipId; - EFUSE_OneByteReadROM(9902, 0xF8, &chipId, L25EOUTVOLTAGE); - return CHIP_TYPE_ENUM(FAMILY, chipId); -} - -const char *LibreTuya::getChipModel() { - return STRINGIFY_MACRO(MCU); -} - -uint32_t LibreTuya::getChipId() { - uint32_t chipId = 0; - uint8_t *id = (uint8_t *)&chipId; - // 9902 was extracted from ROM disassembly, probably not needed - /* EFUSE_OneByteReadROM(9902, 0x3B, id + 0, L25EOUTVOLTAGE); - EFUSE_OneByteReadROM(9902, 0x3C, id + 1, L25EOUTVOLTAGE); - EFUSE_OneByteReadROM(9902, 0x3D, id + 2, L25EOUTVOLTAGE); */ - // new method, based on EFUSE logical map - uint8_t *efuse = (uint8_t *)malloc(512); - // TODO do what EFUSE_LogicalMapRead() does, and read only the used data - EFUSE_LogicalMap_Read(efuse); - memcpy(id, efuse + 0x11A + 3, 3); - free(efuse); - return chipId; -} - -uint8_t LibreTuya::getChipCores() { - return 1; -} - -const char *LibreTuya::getChipCoreType() { - return "ARM Cortex-M4F"; -} - -uint32_t LibreTuya::getCpuFreq() { - return CPU_ClkGet(false); -} - -uint32_t LibreTuya::getCycleCount() { - return microsecondsToClockCycles(micros()); -} - -/* Flash memory utilities */ - -FlashId LibreTuya::getFlashChipId() { - FlashId id; - uint8_t idBytes[3]; - flash_read_id(NULL, idBytes, 3); - id.manufacturerId = idBytes[0]; - id.chipId = idBytes[1]; - id.chipSizeId = idBytes[2]; - return id; -} - -/* Memory management */ - -uint32_t LibreTuya::getRamSize() { - return 256 * 1024; -} - -uint32_t LibreTuya::getHeapSize() { - return configTOTAL_HEAP_SIZE; -} - -uint32_t LibreTuya::getFreeHeap() { - return xPortGetFreeHeapSize(); -} - -uint32_t LibreTuya::getMinFreeHeap() { - return xPortGetMinimumEverFreeHeapSize(); -} - -uint32_t LibreTuya::getMaxAllocHeap() { - return 0; -} - -/* OTA-related */ - -uint8_t LibreTuya::otaGetRunning() { - // RTL8710B is XIP, so check the code offset in flash - uint32_t addr = (uint32_t)lt_log; - uint32_t offs = addr - SPI_FLASH_BASE; - return offs > FLASH_OTA2_OFFSET ? 2 : 1; -} - -uint8_t LibreTuya::otaGetStoredIndex() { - uint32_t *otaAddress = (uint32_t *)0x8009000; - if (*otaAddress == 0xFFFFFFFF) - return 1; - uint32_t otaCounter = *((uint32_t *)0x8009004); - // even count of zero-bits means OTA1, odd count means OTA2 - // this allows to switch OTA images by simply clearing next bits, - // without needing to erase the flash - uint8_t count = 0; - for (uint8_t i = 0; i < 32; i++) { - if ((otaCounter & (1 << i)) == 0) - count++; - } - return 1 + (count % 2); -} - -bool LibreTuya::otaSupportsDual() { - return true; -} - -bool LibreTuya::otaHasImage1() { - uint8_t *ota1Addr = (uint8_t *)(SPI_FLASH_BASE + FLASH_OTA1_OFFSET); - return memcmp(ota1Addr, "81958711", 8) == 0; -} - -bool LibreTuya::otaHasImage2() { - uint8_t *ota2Addr = (uint8_t *)(SPI_FLASH_BASE + FLASH_OTA2_OFFSET); - return memcmp(ota2Addr, "81958711", 8) == 0; -} - -bool LibreTuya::otaSwitch(bool force) { - if (!force && otaGetRunning() != otaGetStoredIndex()) - // OTA has already been switched - return true; - // - read current OTA switch value from 0x9004 - // - reset OTA switch to 0xFFFFFFFE if it's 0x0 - // - else check first non-zero bit of OTA switch - // - write OTA switch with first non-zero bit cleared - - if (!otaHasImage1() || !otaHasImage2()) - return false; - - uint32_t value = HAL_READ32(SPI_FLASH_BASE, FLASH_SYSTEM_OFFSET + 4); - if (value == 0) { - uint8_t *system = (uint8_t *)malloc(64); - Flash.readBlock(FLASH_SYSTEM_OFFSET, system, 64); - // reset OTA switch - ((uint32_t *)system)[1] = -2; - Flash.eraseSector(FLASH_SYSTEM_OFFSET); - return Flash.writeBlock(FLASH_SYSTEM_OFFSET, system, 64); - } - - uint8_t i; - // find first non-zero bit - for (i = 0; i < 32; i++) { - if (value & (1 << i)) - break; - } - // clear the bit - value &= ~(1 << i); - // write OTA switch to flash - flash_write_word(NULL, FLASH_SYSTEM_OFFSET + 4, value); - return true; -} - -/* Watchdog */ - -bool LibreTuya::wdtEnable(uint32_t timeout) { - watchdog_init(timeout); - watchdog_start(); -} - -void LibreTuya::wdtDisable() { - watchdog_stop(); -} - -void LibreTuya::wdtFeed() { - watchdog_refresh(); -} - -/* Global instance */ - -LibreTuya LT; -LibreTuya ESP = LT; diff --git a/arduino/realtek-ambz/cores/arduino/WVariant.h b/arduino/realtek-ambz/cores/arduino/WVariant.h deleted file mode 100644 index 71902f3..0000000 --- a/arduino/realtek-ambz/cores/arduino/WVariant.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include "sdk_extern.h" -#include "sdk_mem.h" -#include "sdk_os.h" - -#define DEFAULT 1 -#define EXTERNAL 0 - -#define round(x) ((x) >= 0 ? (long)((x) + 0.5) : (long)((x)-0.5)) - -// Additional Wiring functions -extern uint32_t digitalPinToPort(uint32_t pinNumber); -extern uint32_t digitalPinToBitMask(uint32_t pinNumber); -extern void analogOutputInit(void); -extern void wait_for_debug(); - -#ifdef __cplusplus -extern "C" uint32_t SystemCoreClock; -#else -extern uint32_t SystemCoreClock; -#endif -#define clockCyclesPerMicrosecond() (SystemCoreClock / 1000000L) -#define clockCyclesToMicroseconds(a) (a * 1000L / (SystemCoreClock / 1000L)) -#define microsecondsToClockCycles(a) (a * (SystemCoreClock / 1000000L)) - -#define interrupts() vPortClearInterruptMask(0) -#define noInterrupts() ulPortSetInterruptMask() - -#ifdef __cplusplus -} // extern "C" -#endif diff --git a/arduino/realtek-ambz/cores/arduino/sdk_mem.c b/arduino/realtek-ambz/cores/arduino/sdk_mem.c deleted file mode 100644 index a91b8c4..0000000 --- a/arduino/realtek-ambz/cores/arduino/sdk_mem.c +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-06. */ - -#include "sdk_mem.h" - -#include // for memset - -void *pvPortZalloc(size_t size) { - void *pvReturn = pvPortMalloc(size); - if (pvReturn) - memset(pvReturn, 0, size); - return pvReturn; -} - -void *pvPortCalloc(size_t nmemb, size_t size) { - return pvPortZalloc(nmemb * size); -} diff --git a/arduino/realtek-ambz/cores/arduino/sdk_mem.h b/arduino/realtek-ambz/cores/arduino/sdk_mem.h deleted file mode 100644 index a242d4a..0000000 --- a/arduino/realtek-ambz/cores/arduino/sdk_mem.h +++ /dev/null @@ -1,21 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-06. */ - -#pragma once - -#include - -// provide extern functions directly, as callers -// generally don't expect needing to include malloc() -extern void *pvPortMalloc(size_t xWantedSize); -extern void *pvPortZalloc(size_t size); -extern void *pvPortCalloc(size_t nmemb, size_t size); -extern void *pvPortReAlloc(void *pv, size_t xWantedSize); -extern void vPortFree(void *pv); - -#define malloc pvPortMalloc -#define zalloc pvPortZalloc -#define calloc pvPortCalloc -#define realloc pvPortReAlloc -#define free vPortFree - -#define LT_HEAP_FUNC xPortGetFreeHeapSize diff --git a/arduino/realtek-ambz/cores/arduino/sdk_os.c b/arduino/realtek-ambz/cores/arduino/sdk_os.c deleted file mode 100644 index 801ecdf..0000000 --- a/arduino/realtek-ambz/cores/arduino/sdk_os.c +++ /dev/null @@ -1,110 +0,0 @@ -#include "sdk_os.h" - -#include -#include - -uint32_t os_thread_create(void (*task)(const void *argument), void *argument, int priority, uint32_t stack_size) { - - osThreadDef_t thread_def; - - thread_def.pthread = task; - thread_def.tpriority = (osPriority)priority; - // the underlying freertos implementation on cmsis os divide stack size by 4 - thread_def.stacksize = stack_size * 4; - thread_def.name = "ARDUINO"; - - return (uint32_t)osThreadCreate(&thread_def, argument); -} - -uint32_t os_thread_get_id(void) { - return osThreadGetId(); -} - -uint32_t os_thread_terminate(uint32_t thread_id) { - return (uint32_t)osThreadTerminate(thread_id); -} - -uint32_t os_thread_yield(void) { - return (uint32_t)osThreadYield(); -} - -uint32_t os_thread_set_priority(uint32_t thread_id, int priority) { - return (uint32_t)osThreadSetPriority(thread_id, (osPriority)priority); -} - -int os_thread_get_priority(uint32_t thread_id) { - return (int)osThreadGetPriority(thread_id); -} - -int32_t os_signal_set(uint32_t thread_id, int32_t signals) { - return osSignalSet(thread_id, signals); -} - -int32_t os_signal_clear(uint32_t thread_id, int32_t signals) { - return osSignalClear(thread_id, signals); -} - -os_event_t os_signal_wait(int32_t signals, uint32_t millisec) { - - osEvent evt; - os_event_t ret; - - evt = osSignalWait(signals, millisec); - ret.status = (uint32_t)evt.status; - ret.value.signals = evt.value.signals; - ret.def.message_id = evt.def.message_id; - - return ret; -} - -typedef void (*os_ptimer)(const void *argument); - -uint32_t os_timer_create(void (*callback)(const void *argument), uint8_t isPeriodic, void *argument) { - - osTimerDef_t *pTimerDef; - - pTimerDef = (osTimerDef_t *)malloc(sizeof(osTimerDef_t)); - pTimerDef->ptimer = callback; - pTimerDef->custom = (struct os_timer_custom *)malloc(sizeof(struct os_timer_custom)); - - return osTimerCreate(pTimerDef, (isPeriodic ? osTimerPeriodic : osTimerOnce), argument); -} - -uint32_t os_timer_start(uint32_t timer_id, uint32_t millisec) { - return osTimerStart(timer_id, millisec); -} - -uint32_t os_timer_stop(uint32_t timer_id) { - return osTimerStop(timer_id); -} - -uint32_t os_timer_delete(uint32_t timer_id) { - - osTimerDef_t *pTimerDef; - - pTimerDef = (osTimerDef_t *)pvTimerGetTimerID(timer_id); - free(pTimerDef->custom); - free(pTimerDef); - - return osTimerDelete(timer_id); -} - -uint32_t os_semaphore_create(int32_t count) { - return (uint32_t)osSemaphoreCreate(NULL, count); -} - -int32_t os_semaphore_wait(uint32_t semaphore_id, uint32_t millisec) { - if (osSemaphoreWait((osSemaphoreId)semaphore_id, millisec) == 0) { - return 1; - } else { - return 0; - } -} - -uint32_t os_semaphore_release(uint32_t semaphore_id) { - return (uint32_t)osSemaphoreRelease((osSemaphoreId)semaphore_id); -} - -uint32_t os_semaphore_delete(uint32_t semaphore_id) { - return (uint32_t)osSemaphoreDelete((osSemaphoreId)semaphore_id); -} diff --git a/arduino/realtek-ambz/cores/arduino/sdk_os.h b/arduino/realtek-ambz/cores/arduino/sdk_os.h deleted file mode 100644 index c3483d9..0000000 --- a/arduino/realtek-ambz/cores/arduino/sdk_os.h +++ /dev/null @@ -1,302 +0,0 @@ -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/** - * @defgroup os_status os_status - * Redefinition from enum osStatus - * @{ - */ -/** function completed; no error or event occurred. */ -#define OS_OK 0x00 -/** function completed; signal event occurred. */ -#define OS_EVENT_SIGNAL 0x08 -/** function completed; message event occurred. */ -#define OS_EVENT_MESSAGE 0x10 -/** function completed; mail event occurred. */ -#define OS_EVENT_MAIL 0x20 -/** function completed; timeout occurred. */ -#define OS_EVENT_TIMEOUT 0x40 -/** parameter error: a mandatory parameter was missing or specified an incorrect object. */ -#define OS_ERROR_PARAMETER 0x80 -/** resource not available: a specified resource was not available. */ -#define OS_ERROR_RESOURCE 0x81 -/** resource not available within given time: a specified resource was not available within the timeout period. */ -#define OS_ERROR_TIMEOUT_RESOURCE 0xC1 -/** not allowed in ISR context: the function cannot be called from interrupt service routines. */ -#define OS_ERROR_ISR 0x82 -/** function called multiple times from ISR with same object. */ -#define OS_ERROR_ISR_RECURSIVE 0x83 -/** system cannot determine priority or thread has illegal priority. */ -#define OS_ERROR_PRIORITY 0x84 -/** system is out of memory: it was impossible to allocate or reserve memory for the operation. */ -#define OS_ERROR_NO_MEMORY 0x85 -/** value of a parameter is out of range. */ -#define OS_ERROR_VALUE 0x86 -/** unspecified RTOS error: run-time error but no other error message fits. */ -#define OS_ERROR_OS 0xFF -/** @} */ // end of group os_status - -/** - * @defgroup os_priority os_priority - * Redefinition from enum osPriority - * @{ - */ -/** priority: idle (lowest) */ -#define OS_PRIORITY_IDLE (-3) -/** priority: low */ -#define OS_PRIORITY_LOW (-2) -/** priority: below normal */ -#define OS_PRIORITY_BELOW_NORMAL (-1) -/** priority: normal (default) */ -#define OS_PRIORITY_NORMAL (0) -/** priority: above normal */ -#define OS_PRIORITY_ABOVENORMAL (+1) -/** priority: high */ -#define OS_PRIORITY_HIGH (+2) -/** priority: realtime (highest) */ -#define OS_PRIORITY_REALTIME (+3) -/** @} */ // end of group os_priority - -#ifndef DEFAULT_STACK_SIZE -/** - * @ingroup wiring_os - * @brief default stack size - * - * It is suggest that thread is assigned stack size more than DEFAULT_STACK_SIZE - */ -#define DEFAULT_STACK_SIZE 512 -#endif - -/** - * @ingroup wiring_os - * @struct os_event_t - * Redefine osEvent in cmsis_os.h - */ -typedef struct { - uint32_t status; ///< status code: event or error information - - union { - uint32_t v; ///< message as 32-bit value - void *p; ///< message or mail as void pointer - int32_t signals; ///< signal flags - } value; ///< event value - - union { - void *mail_id; ///< mail id obtained by osMailCreate - void *message_id; ///< message id obtained by osMessageCreate - } def; ///< event definition -} os_event_t; - -/** - * @defgroup thread_management thread_management - * Thread management include create, get thread id, terminate, yield, and set/get priority - **/ - -/** - * @ingroup thread_management - * @brief Create a thread and add it to Active Threads and set it to state READY. - * - * @param[in] task Function pointer which is the thread body. It should not run into the end of function unless - * os_thread_terminate is invoked - * @param[in] argument the data pointer which brings to task - * @param[in] priority The underlying os is FreeRTOS. It executes tasks with highest priority which are not in idle - * state.\n If there are more than 2 tasks to be executed, then they share the time slice. - * @param[in] stack_size The stack_size is used as memory heap only for this task. \n - * The local variables and call stacks would occupy this heap. Please make sure the the stack_size is big enough to - * avoid curroption - * @return The thread id which is used in thread operation and signaling. - */ -extern uint32_t os_thread_create(void (*task)(const void *argument), void *argument, int priority, uint32_t stack_size); - -/** - * @ingroup thread_management - * @brief Return the thread ID of the current running thread. - * - * @return Current thread id which calls os_thread_get_id - */ -extern uint32_t os_thread_get_id(void); - -/** - * @ingroup thread_management - * @brief Terminate execution of a thread and remove it from Active Threads. - * - * Thread should not ended without terminate first - * - * @param[in] thread_id Terminate the thread with specific thread_id - * @return os_status code - */ -extern uint32_t os_thread_terminate(uint32_t thread_id); - -/** - * @ingroup thread_management - * @brief Pass control to next thread that is in state \b READY. - * - * By default the minimal execution unit is 1 millisecond. In a scenario that if a thread with smaller want to handout - * execution right to a thread with higher priority immediately without waiting for the ending of current 1 millisecond, - * then invoke os_thread_yield can transfer exection right to OS's idle task and check which is the next execution - * thread. - * - * @return os_status code - */ -extern uint32_t os_thread_yield(void); - -/** - * @ingroup thread_management - * @brief Change priority of an active thread. - * - * @param[in] thread_id The target thread with the thread id to be changed - * @param[in] priority The updated priority - * @return os_status code - */ -extern uint32_t os_thread_set_priority(uint32_t thread_id, int priority); - -/** - * @ingroup thread_management - * @brief Get current priority of an active thread. - * - * @param[in] thread_id The target thread with the thread id to be searched - * @return os_priority - */ -extern int os_thread_get_priority(uint32_t thread_id); - -/** - * @defgroup signal_management signal_management - * Signaling between threads include set, clear, and wait - */ - -/** - * @ingroup signal_management - * @brief Set the specified Signal Flags of an active thread. - * - * @param[in] thread_id Send signal to a thread with the thread id - * @param[in] signals the signals to be send - * @return os_status code - */ -extern int32_t os_signal_set(uint32_t thread_id, int32_t signals); - -/** - * @ingroup signal_management - * @brief Clear the specified Signal Flags of an active thread. - * - * @param[in] thread_id Clear signal to a thread with the thread id - * @param[in] signals The signals to be clear - * @return os_status code - */ -extern int32_t os_signal_clear(uint32_t thread_id, int32_t signals); - -/** - * @ingroup signal_management - * @brief Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. - * - * @param[in] signals the signals to be wait - * @param[in] millisec the timeout value if no signal comes in. Fill in 0xFFFFFFFF for infinite wait. - * @return os_status code - */ -extern os_event_t os_signal_wait(int32_t signals, uint32_t millisec); - -/** - * @defgroup timer_management timer_management - * Software timer management include create, start, stop, delete. - */ - -/** - * @ingroup timer_management - * @brief specify timer type that invoke only once - */ -#define OS_TIMER_ONCE (0) - -/** - * @ingroup timer_management - * @brief specify timer type that invoke periodically - */ -#define OS_TIMER_PERIODIC (1) - -/** - * @ingroup timer_management - * @brief Create a timer. - * - * @param[in] callback The function to be invoke when timer timeout - * @param[in] isPeriodic \b OS_TIMER_ONCE or \b OS_TIMER_PERIODIC - * @param[in] argument The argument that is bring into callback function - * @return timer id - */ -extern uint32_t os_timer_create(void (*callback)(const void *argument), uint8_t isPeriodic, void *argument); - -/** - * @ingroup timer_management - * @brief Start or restart a timer. - * - * @param[in] timer_id The timer id obtained from by os_timer_create - * @param[in] millisec The delays after timer starts - * @return os_status code - */ -extern uint32_t os_timer_start(uint32_t timer_id, uint32_t millisec); - -/** - * @ingroup timer_management - * @brief Stop the timer. - * - * @param[in] timer_id The timer id obtained from by os_timer_create - * @return os_status code - */ -extern uint32_t os_timer_stop(uint32_t timer_id); - -/** - * @ingroup timer_management - * @brief Delete a timer that was created by os_timer_create - * - * @param[in] timer_id The timer id obtained from by os_timer_create - * @return os_status code - */ -extern uint32_t os_timer_delete(uint32_t timer_id); - -/** - * @defgroup semaphore_management semaphore_management - * Semaphore API between threads include create, wait, release, delete. - */ - -/** - * @ingroup semaphore_management - * @brief Create and Initialize a Semaphore object used for managing resources - * - * @param[in] count The number of available resources - * @return semaphore ID - */ -extern uint32_t os_semaphore_create(int32_t count); - -/** - * @ingroup semaphore_management - * @brief Wait until a Semaphore token becomes available - * - * @param[in] semaphore_id semaphore id obtained from os_semaphore_create - * @param[in] millisec timeout value - * @return os_status code - */ -extern int32_t os_semaphore_wait(uint32_t semaphore_id, uint32_t millisec); - -/** - * @ingroup semaphore_management - * @brief Release a Semaphore token - * - * @param[in] semaphore_id semaphore id obtained from os_semaphore_create - * @return os_status code - */ -extern uint32_t os_semaphore_release(uint32_t semaphore_id); - -/** - * @ingroup semaphore_management - * @brief Delete a Semaphore that was created by os_semaphore_create. - * - * @param[in] semaphore_id semaphore id obtained from os_semaphore_create - * @return os_status code - */ -extern uint32_t os_semaphore_delete(uint32_t semaphore_id); - -#ifdef __cplusplus -} -#endif diff --git a/arduino/realtek-ambz/libraries/MD5/MD5Impl.h b/arduino/realtek-ambz/libraries/MD5/MD5Impl.h deleted file mode 100644 index e9bb3d8..0000000 --- a/arduino/realtek-ambz/libraries/MD5/MD5Impl.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-03. */ - -#pragma once - -#define LT_MD5_USE_POLARSSL 1 diff --git a/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.cpp b/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.cpp deleted file mode 100644 index 978d4d6..0000000 --- a/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "PowerManagement.h" - -#include - -#ifdef __cplusplus -extern "C" { -#include -#include -#include -} -#endif - -#if defined(BOARD_RTL8195A) -#define SAVE_LOCK_PIN 18 -#elif defined(BOARD_RTL8710) -#define SAVE_LOCK_PIN 7 // PB_1 -#else -#define SAVE_LOCK_PIN 18 -#endif - -bool PowerManagementClass::reservePLL = true; - -void PowerManagementClass::sleep(uint32_t bitflg) { - if (!safeLock()) { - pmu_release_wakelock(bitflg); - } -} - -void PowerManagementClass::sleep(void) { - if (!safeLock()) { - pmu_release_wakelock(BIT(PMU_OS)); - } -} - -void PowerManagementClass::active(uint32_t bitflg) { - pmu_acquire_wakelock(bitflg); -} - -void PowerManagementClass::active(void) { - pmu_acquire_wakelock(BIT(PMU_OS)); -} - -void PowerManagementClass::deepsleep(uint32_t duration_ms) { - if (!safeLock()) { - deepsleep_ex(DSLEEP_WAKEUP_BY_TIMER, duration_ms); - } -} - -bool PowerManagementClass::safeLock() { - pinMode(SAVE_LOCK_PIN, INPUT_PULLUP); - return (digitalRead(SAVE_LOCK_PIN) == 1) ? false : true; -} - -void PowerManagementClass::softReset() { - sys_reset(); -} - -PowerManagementClass PowerManagement; diff --git a/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.h b/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.h deleted file mode 100644 index c2551d7..0000000 --- a/arduino/realtek-ambz/libraries/PowerManagement/PowerManagement.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include - -/** - * @class PowerManagementClass PowerManagement.h - * @brief Power management in Ameba - */ -class PowerManagementClass { - public: - /** - * @brief Allow OS automatically save power while idle - * - * As OS consider it would idle for more than 2s, it will invoke system suspend. - * If wlan is associated with AP, than it will under asslociated idle state. - */ - static void sleep(void); - static void sleep(uint32_t bitflg); - - /** - * @brief Disallow OS automatically save power while idle - */ - static void active(void); - static void active(uint32_t bitflg); - - /** - * @brief Reserved PLL while sleep - * - * Reserve PLL would keep FIFO of peripherals (Ex. UART) but cost more power (around 5mA). - * If we don't reserve PLL, it saves more power but we might missing data because FIFO is turned of this way. - * - * @param[in] reserve true for reserved, false for non-reserved - */ - static void setPllReserved(bool reserve); - - /** - * @brief Enter deepsleep immediately - * - * Invoke deepsleep would make system enter deepsleep state immediately. - * It's the state that saves most power. - * As it wakeup from deepsleep, the system would behave just like reboot. - * - * @param[in] duration_ms wakeup after specific time in unit of millisecond - */ - static void deepsleep(uint32_t duration_ms); - - /** - * @brief Check if system is allowed enter any power save state - * - * The pin 18 (GPIOE_5) is designed as safe lock. - * If pin 18 is HIGH, then we prevent Ameba enter any power save state.\n\n - * Under any power save state, we are not able to flash image to Ameba. - * Thus if user misuse deepsleep and make Ameba enter deepsleep immediately after boot up, - * then he would find it's hard to flash image. - * In this case, he can pull up pin 18. - * - * @return true if system not allowed enter any power save state, and false vise versa - */ - static bool safeLock(); - - /** - * @brief Reboot system - * - * Reboot system in soft way. Some registers is not powered off in this case, but mostly we could regard this as - * reboot. - */ - static void softReset(); - - private: - static bool reservePLL; -}; - -extern PowerManagementClass PowerManagement; diff --git a/arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.h b/arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.h deleted file mode 100644 index e711c8a..0000000 --- a/arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-03. */ - -#pragma once - -#include diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFi.h b/arduino/realtek-ambz/libraries/WiFi/WiFi.h deleted file mode 100644 index c386b1b..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFi.h +++ /dev/null @@ -1,10 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ - -#pragma once - -#include -#include - -#include "WiFiClient.h" -#include "WiFiClientSecure.h" -#include "WiFiServer.h" diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiClient.h b/arduino/realtek-ambz/libraries/WiFi/WiFiClient.h deleted file mode 100644 index eb27361..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiClient.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ - -#pragma once - -#include -#include - -typedef LwIPClient WiFiClient; diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiClientSecure.h b/arduino/realtek-ambz/libraries/WiFi/WiFiClientSecure.h deleted file mode 100644 index 3addedf..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiClientSecure.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-05-04. */ - -#pragma once - -#include -#include - -typedef MbedTLSClient WiFiClientSecure; diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiData.h b/arduino/realtek-ambz/libraries/WiFi/WiFiData.h deleted file mode 100644 index 2488579..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiData.h +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-23. */ - -#pragma once - -#include - -extern "C" { - -#include -#include - -} // extern "C" - -typedef struct { - bool initialized; - bool sleep; - SemaphoreHandle_t scanSem; -} WiFiData; diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiGeneric.cpp b/arduino/realtek-ambz/libraries/WiFi/WiFiGeneric.cpp deleted file mode 100644 index 2b5e1c5..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiGeneric.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ - -#include "WiFiPriv.h" - -int32_t WiFiClass::channel() { - int channel = 0; - wifi_get_channel(&channel); - return channel; -} - -bool WiFiClass::modePriv(WiFiMode mode, WiFiModeAction sta, WiFiModeAction ap) { - __wrap_rtl_printf_disable(); - __wrap_DiagPrintf_disable(); - startWifiTask(); - - if (!data.initialized) { - // initialize wifi first - LT_IM(WIFI, "Initializing LwIP"); - LwIP_Init(); - reset_wifi_struct(); - data.initialized = true; - } - LT_HEAP_I(); - if (getMode()) { - // stop wifi to change mode - LT_DM(WIFI, "Stopping WiFi to change mode"); - if (wifi_off() != RTW_SUCCESS) - goto error; - vTaskDelay(20); - if (mode == WIFI_MODE_NULL) - goto error; - } - - if (wifi_on((rtw_mode_t)mode) != RTW_SUCCESS) { - LT_EM(WIFI, "Error while changing mode(%u)", mode); - goto error; - } - - // send STA start/stop events and AP stop event (start is handled in softAP()) - if (sta == WLMODE_ENABLE) { - wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_STA_START, -2); - } else if (sta == WLMODE_DISABLE) { - wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_STA_STOP, -2); - } - if (ap == WLMODE_DISABLE) { - wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_AP_STOP, -2); - } - - LT_HEAP_I(); - __wrap_rtl_printf_enable(); - __wrap_DiagPrintf_enable(); - return true; - -error: - __wrap_rtl_printf_enable(); - __wrap_DiagPrintf_enable(); - return false; -} - -WiFiMode WiFiClass::getMode() { - if (!data.initialized) - return WIFI_MODE_NULL; - return (WiFiMode)wifi_mode; -} - -WiFiStatus WiFiClass::status() { - if (wifi_is_connected_to_ap() == 0) { - return WL_CONNECTED; - } else { - return WL_DISCONNECTED; - } -} - -bool WiFiClass::setSleep(bool enable) { - LT_DM(WIFI, "WiFi sleep mode %u", enable); - if (enable) { - if (wifi_enable_powersave() != RTW_SUCCESS) - return false; - } else { - if (wifi_disable_powersave() != RTW_SUCCESS) - return false; - } - data.sleep = enable; - return true; -} - -bool WiFiClass::getSleep() { - return data.sleep; -} - -bool WiFiClass::setTxPower(int power) { - return false; // wifi_set_txpower(power) == RTW_SUCCESS; -} - -int WiFiClass::getTxPower() { - return 0; - int power = 0; - wifi_get_txpower(&power); - return power; -} - -IPAddress WiFiClass::hostByName(const char *hostname) { - ip_addr_t ip; - int ret = netconn_gethostbyname(hostname, &ip); - if (ret == ERR_OK) { - return ip.addr; - } - return IPAddress(); -} diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiPriv.h b/arduino/realtek-ambz/libraries/WiFi/WiFiPriv.h deleted file mode 100644 index 37439d6..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiPriv.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ - -#pragma once - -#include - -extern "C" { - -// copy defines from PIO builder (for IDE to understand) -#define LWIP_TIMEVAL_PRIVATE 0 -#define LWIP_NETIF_HOSTNAME 1 -#define LWIP_SO_RCVBUF 1 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern struct netif xnetif[NET_IF_NUM]; - -} // extern "C" - -// WiFi.cpp -extern rtw_network_info_t wifi; -extern rtw_ap_info_t ap; -extern rtw_wifi_setting_t wifi_setting; -extern unsigned char sta_password[65]; -extern unsigned char ap_password[65]; -extern void reset_wifi_struct(void); -extern rtw_mode_t wifi_mode; -extern WiFiAuthMode securityTypeToAuthMode(uint8_t type); -// WiFiEvents.cpp -extern void startWifiTask(); -extern void handleRtwEvent(uint16_t event, char *data, int len, int flags); - -#define NETIF_RTW_STA &xnetif[RTW_STA_INTERFACE] -#define NETIF_RTW_AP (wifi_mode == WIFI_MODE_APSTA ? &xnetif[RTW_AP_INTERFACE] : NETIF_RTW_STA) - -#define NETNAME_STA WLAN0_NAME -#define NETNAME_AP (wifi_mode == WIFI_MODE_APSTA ? WLAN1_NAME : WLAN0_NAME) diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiServer.h b/arduino/realtek-ambz/libraries/WiFi/WiFiServer.h deleted file mode 100644 index db8df0b..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiServer.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ - -#pragma once - -#include -#include - -typedef LwIPServer WiFiServer; diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiUdp.h b/arduino/realtek-ambz/libraries/WiFi/WiFiUdp.h deleted file mode 100644 index 8b60be1..0000000 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiUdp.h +++ /dev/null @@ -1,8 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-09-10. */ - -#pragma once - -#include -#include - -typedef LwIPUDP WiFiUDP; diff --git a/boards/SUMMARY.md b/boards/SUMMARY.md deleted file mode 100644 index 2df5314..0000000 --- a/boards/SUMMARY.md +++ /dev/null @@ -1,32 +0,0 @@ - - -- [Generic - BK7231N (Tuya QFN32)](../boards/generic-bk7231n-qfn32-tuya/README.md) -- [Generic - BK7231T (Tuya QFN32)](../boards/generic-bk7231t-qfn32-tuya/README.md) -- [Generic - BK7252](../boards/generic-bk7252/README.md) -- [Generic - RTL8710BN (2M/468k)](../boards/generic-rtl8710bn-2mb-468k/README.md) -- [Generic - RTL8710BN (2M/788k)](../boards/generic-rtl8710bn-2mb-788k/README.md) -- [Generic - RTL8710BX (4M/980k)](../boards/generic-rtl8710bx-4mb-980k/README.md) -- [Generic - RTL8720CF (2M/992k)](../boards/generic-rtl8720cf-2mb-992k/README.md) -- [BW12](../boards/bw12/README.md) -- [BW15](../boards/bw15/README.md) -- [CB2L](../boards/cb2l/README.md) -- [CB2S](../boards/cb2s/README.md) -- [CB3L](../boards/cb3l/README.md) -- [CB3S](../boards/cb3s/README.md) -- [CB3SE](../boards/cb3se/README.md) -- [WB2L](../boards/wb2l/README.md) -- [WB2S](../boards/wb2s/README.md) -- [WB3L](../boards/wb3l/README.md) -- [WB3S](../boards/wb3s/README.md) -- [WR2](../boards/wr2/README.md) -- [WR2E](../boards/wr2e/README.md) -- [WR3](../boards/wr3/README.md) -- [WR3E](../boards/wr3e/README.md) -- [WR3N](../boards/wr3n/README.md) -- [WR2L](../boards/wr2l/README.md) -- [WR2LE](../boards/wr2le/README.md) -- [WR3L](../boards/wr3l/README.md) -- [WR3LE](../boards/wr3le/README.md) -- [LSC LMA35](../boards/lsc-lma35/README.md) -- [LSC LMA35 T](../boards/lsc-lma35-t/README.md) -- [Generic - Host-native](../boards/generic-native/README.md) diff --git a/boards/_base/beken-7231n.json b/boards/_base/beken-7231n.json index 4a1421b..308a3ba 100644 --- a/boards/_base/beken-7231n.json +++ b/boards/_base/beken-7231n.json @@ -1,9 +1,9 @@ { "build": { "family": "BK7231N", - "ldscript_sdk": "bk7231n_bsp.ld", - "ldscript_arduino": "bk7231n_bsp.ld", + "ldscript": "bk7231n_bsp.ld", "bkboot_version": "1.0.1-bk7231n", + "bkoffset_app": "0x10000", "bkrbl_size_app": "0x108700" }, "flash": { diff --git a/boards/_base/beken-7231u.json b/boards/_base/beken-7231u.json index 7199113..7516035 100644 --- a/boards/_base/beken-7231u.json +++ b/boards/_base/beken-7231u.json @@ -1,9 +1,9 @@ { "build": { "family": "BK7231U", - "ldscript_sdk": "bk7231_bsp.ld", - "ldscript_arduino": "bk7231_bsp.ld", + "ldscript": "bk7231_bsp.ld", "bkboot_version": "1.0.8-bk7231u", + "bkoffset_app": "0x10000", "bkrbl_size_app": "0x108700" }, "flash": { diff --git a/boards/_base/beken-7252.json b/boards/_base/beken-7252.json index e9efae5..cc86e67 100644 --- a/boards/_base/beken-7252.json +++ b/boards/_base/beken-7252.json @@ -2,9 +2,9 @@ "build": { "family": "BK7251", "f_cpu": "180000000L", - "ldscript_sdk": "bk7231_bsp.ld", - "ldscript_arduino": "bk7231_bsp.ld", + "ldscript": "bk7231_bsp.ld", "bkboot_version": "0.1.3-bk7252", + "bkoffset_app": "0x10000", "bkrbl_size_app": "0x1A0000" }, "flash": { diff --git a/boards/_base/beken-72xx.json b/boards/_base/beken-72xx.json index bbbaef8..f466879 100644 --- a/boards/_base/beken-72xx.json +++ b/boards/_base/beken-72xx.json @@ -22,10 +22,6 @@ "mem 0x000000 0x200000 ro" ] }, - "frameworks": [ - "beken-72xx-sdk", - "beken-72xx-arduino" - ], "upload": { "maximum_ram_size": 262144, "flash_size": 2097152, diff --git a/boards/_base/ic/rtl8710bn.json b/boards/_base/ic/rtl8710bn.json index 7a376d4..0a3d6e7 100644 --- a/boards/_base/ic/rtl8710bn.json +++ b/boards/_base/ic/rtl8710bn.json @@ -92,6 +92,7 @@ }, "27": { "C_NAME": "AD_2", + "GPIONUM": 41, "IO": "I", "ADC": 2 }, diff --git a/boards/_base/realtek-ambz-2mb-468k.json b/boards/_base/realtek-ambz-2mb-468k.json index 539f23e..6b8346c 100644 --- a/boards/_base/realtek-ambz-2mb-468k.json +++ b/boards/_base/realtek-ambz-2mb-468k.json @@ -1,7 +1,5 @@ { "build": { - "ldscript_sdk": "rlx8711B-symbol-v02-img2_xip1_2M_468k_cpp.ld", - "ldscript_arduino": "rlx8711B-symbol-v02-img2_xip1_2M_468k_cpp.ld", "amb_boot_all": "boot_all_77F7.bin" }, "flash": { diff --git a/boards/_base/realtek-ambz-2mb-788k.json b/boards/_base/realtek-ambz-2mb-788k.json index 0af4b40..7df3e6e 100644 --- a/boards/_base/realtek-ambz-2mb-788k.json +++ b/boards/_base/realtek-ambz-2mb-788k.json @@ -1,7 +1,5 @@ { "build": { - "ldscript_sdk": "rlx8711B-symbol-v02-img2_xip1_2M_cpp.ld", - "ldscript_arduino": "rlx8711B-symbol-v02-img2_xip1_2M_cpp.ld", "amb_boot_all": "boot_all_77F7.bin" }, "flash": { diff --git a/boards/_base/realtek-ambz-4mb-980k.json b/boards/_base/realtek-ambz-4mb-980k.json index ce08d8b..5f5fd0e 100644 --- a/boards/_base/realtek-ambz-4mb-980k.json +++ b/boards/_base/realtek-ambz-4mb-980k.json @@ -1,7 +1,5 @@ { "build": { - "ldscript_sdk": "rlx8711B-symbol-v02-img2_xip1_4M_980k_cpp.ld", - "ldscript_arduino": "rlx8711B-symbol-v02-img2_xip1_4M_980k_cpp.ld", "amb_boot_all": "boot_all_C556.bin" }, "flash": { diff --git a/boards/_base/realtek-ambz.json b/boards/_base/realtek-ambz.json index 9585c44..8fbbdae 100644 --- a/boards/_base/realtek-ambz.json +++ b/boards/_base/realtek-ambz.json @@ -1,6 +1,7 @@ { "build": { "family": "RTL8710B", + "ldscript": "rlx8711B-symbol-v02-img2_xip1.ld", "f_cpu": "125000000L", "prefix": "arm-none-eabi-", "amb_flash_addr": "0x08000000" @@ -24,10 +25,6 @@ "mem 0x8000000 0x8200000 ro" ] }, - "frameworks": [ - "realtek-ambz-sdk", - "realtek-ambz-arduino" - ], "upload": { "maximum_ram_size": 262144, "require_upload_port": true, diff --git a/boards/_base/realtek-ambz2.json b/boards/_base/realtek-ambz2.json index c7f451a..be1f316 100644 --- a/boards/_base/realtek-ambz2.json +++ b/boards/_base/realtek-ambz2.json @@ -3,8 +3,7 @@ "family": "RTL8720C", "f_cpu": "100000000L", "prefix": "arm-none-eabi-", - "ldscript_sdk": "rtl8710c_ram.ld", - "ldscript_arduino": "rtl8710c_ram.ld" + "ldscript": "rtl8710c_ram.ld" }, "flash": { "part_table": "0x000000+0x1000", @@ -16,9 +15,6 @@ "protocol": "openocd", "protocols": [] }, - "frameworks": [ - "realtek-ambz2-sdk" - ], "upload": { "maximum_ram_size": 262144 }, diff --git a/boards/bw12/README.md b/boards/bw12/README.md deleted file mode 100644 index db2e50c..0000000 --- a/boards/bw12/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# BW12 - -*by Ai-Thinker Co., Ltd.* - -[Product page](http://www.ai-thinker.com/pro_view-13.html) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) -- [Vendor datasheet](https://docs.ai-thinker.com/_media/rtl8710/hardware/bw12_datasheet_en.pdf) - -Parameter | Value --------------|------------------------------------------ -Board code | `bw12` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ARI3-BW1X](https://fccid.io/2ARI3-BW1X) - -## Usage - -**Board code:** `bw12` - -In `platformio.ini`: - -```ini -[env:bw12] -platform = libretuya -board = bw12 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: bw12 - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_bw12.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA05 | | | | PWM4 | -D1 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D2 | PA00 | | | | PWM2 | -D3 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D4 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D5 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D6 | PA14 | | | | PWM0 | SWCLK -D7 | PA12 | | | | PWM3 | -D8 | PA15 | | | | PWM1 | SWDIO -D9 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D10 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A0 | PA19, ADC1 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 468 KiB / 0x75000 | 0x080000 -OTA2 Image | 0x080000 | 468 KiB / 0x75000 | 0x0F5000 -Key-Value Store | 0x0F5000 | 24 KiB / 0x6000 | 0x0FB000 -User Data | 0x0FB000 | 1 MiB / 0x104000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/bw12/pinout_bw12.svg b/boards/bw12/pinout_bw12.svg deleted file mode 100644 index 97456f5..0000000 --- a/boards/bw12/pinout_bw12.svg +++ /dev/null @@ -1,315 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PA15 - - - - D8 - - - - PWM1 - - - - SWDIO - - - - - - CEN - - - - - PA05 - - - - D0 - - - - PWM4 - - - - - PA29 - - - - D1 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA00 - - - - D2 - - - - PWM2 - - - - - PA19 - - - - ADC1 - - - - D3 - - - - A0 - - - - SDA0 - - - - CS0 - - - - CS1 - - - - - 3V3 - - - - - GND - - - - - PA22 - - - - D4 - - - - SCL0 - - - - MISO0 - - - - MISO1 - - - - PWM5 - - - - - PA30 - - - - D5 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - PA14 - - - - D6 - - - - PWM0 - - - - SWCLK - - - - - PA12 - - - - D7 - - - - PWM3 - - - - - PA15 - - - - D8 - - - - PWM1 - - - - SWDIO - - - - - PA18 - - - - D9 - - - - RX0 - - - - SCL1 - - - - SCK0 - - - - SCK1 - - - - - PA23 - - - - D10 - - - - TX0 - - - - SDA1 - - - - MOSI0 - - - - MOSI1 - - - - PWM0 - diff --git a/boards/bw12/pins_arduino.h b/boards/bw12/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/bw12/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/bw12/variant.h b/boards/bw12/variant.h deleted file mode 100644 index a895a4d..0000000 --- a/boards/bw12/variant.h +++ /dev/null @@ -1,80 +0,0 @@ -/* This file was auto-generated from bw12.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 11 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 3u // PA_19 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 3u // PA_19 -#define PIN_SPI0_MISO 4u // PA_22 -#define PIN_SPI0_MOSI 10u // PA_23 -#define PIN_SPI0_SCK 9u // PA_18 -#define PIN_SPI1_CS 3u // PA_19 -#define PIN_SPI1_MISO 4u // PA_22 -#define PIN_SPI1_MOSI 10u // PA_23 -#define PIN_SPI1_SCK 9u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 1u // PA_29 -#define PIN_WIRE0_SCL_1 4u // PA_22 -#define PIN_WIRE0_SDA_0 3u // PA_19 -#define PIN_WIRE0_SDA_1 5u // PA_30 -#define PIN_WIRE1_SCL 9u // PA_18 -#define PIN_WIRE1_SDA 10u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 3u // PA_19 -#define PIN_SERIAL0_RTS 4u // PA_22 -#define PIN_SERIAL0_RX 9u // PA_18 -#define PIN_SERIAL0_TX 10u // PA_23 -#define PIN_SERIAL2_RX 1u // PA_29 -#define PIN_SERIAL2_TX 5u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 3u // PA_19 -#define PIN_FUNCTION_CS0 3u // PA_19 -#define PIN_FUNCTION_CS1 3u // PA_19 -#define PIN_FUNCTION_CTS0 3u // PA_19 -#define PIN_FUNCTION_MISO0 4u // PA_22 -#define PIN_FUNCTION_MISO1 4u // PA_22 -#define PIN_FUNCTION_MOSI0 10u // PA_23 -#define PIN_FUNCTION_MOSI1 10u // PA_23 -#define PIN_FUNCTION_PA00 2u // PA_0 -#define PIN_FUNCTION_PA05 0u // PA_5 -#define PIN_FUNCTION_PA12 7u // PA_12 -#define PIN_FUNCTION_PA14 6u // PA_14 -#define PIN_FUNCTION_PA15 8u // PA_15 -#define PIN_FUNCTION_PA18 9u // PA_18 -#define PIN_FUNCTION_PA19 3u // PA_19 -#define PIN_FUNCTION_PA22 4u // PA_22 -#define PIN_FUNCTION_PA23 10u // PA_23 -#define PIN_FUNCTION_PA29 1u // PA_29 -#define PIN_FUNCTION_PA30 5u // PA_30 -#define PIN_FUNCTION_RTS0 4u // PA_22 -#define PIN_FUNCTION_RX0 9u // PA_18 -#define PIN_FUNCTION_RX2 1u // PA_29 -#define PIN_FUNCTION_SCK0 9u // PA_18 -#define PIN_FUNCTION_SCK1 9u // PA_18 -#define PIN_FUNCTION_TX0 10u // PA_23 -#define PIN_FUNCTION_TX2 5u // PA_30 diff --git a/boards/bw15/README.md b/boards/bw15/README.md deleted file mode 100644 index 9c5c778..0000000 --- a/boards/bw15/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# BW15 - -*by Ai-Thinker Co., Ltd.* - -[Product page](https://docs.ai-thinker.com/_media/rtl8710/docs/bw15_datasheet_en.pdf) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Vendor datasheet](https://docs.ai-thinker.com/_media/rtl8710/docs/bw15_datasheet_en.pdf) - -Parameter | Value --------------|------------------------------------------ -Board code | `bw15` -MCU | RTL8720CF -Manufacturer | Realtek -Series | AmebaZ2 -Frequency | 100 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 13x GPIO, 8x PWM, 3x UART -Wi-Fi | 802.11 b/g/n -BLE | v4.2 -FCC ID | [2AXVG-BW15](https://fccid.io/2AXVG-BW15) - -## Usage - -**Board code:** `bw15` - -In `platformio.ini`: - -```ini -[env:bw15] -platform = libretuya -board = bw15 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: bw15 - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_bw15.svg) - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Partition Table | 0x000000 | 4 KiB / 0x1000 | 0x001000 -System Data | 0x001000 | 4 KiB / 0x1000 | 0x002000 -Calibration | 0x002000 | 4 KiB / 0x1000 | 0x003000 -(reserved) | 0x003000 | 4 KiB / 0x1000 | 0x004000 -Boot Image | 0x004000 | 32 KiB / 0x8000 | 0x00C000 -OTA1 Image | 0x00C000 | 992 KiB / 0xF8000 | 0x104000 -OTA2 Image | 0x104000 | 992 KiB / 0xF8000 | 0x1FC000 -Key-Value Store | 0x1FC000 | 8 KiB / 0x2000 | 0x1FE000 -User Data | 0x1FE000 | 8 KiB / 0x2000 | 0x200000 diff --git a/boards/bw15/pinout_bw15.svg b/boards/bw15/pinout_bw15.svg deleted file mode 100644 index fc777d0..0000000 --- a/boards/bw15/pinout_bw15.svg +++ /dev/null @@ -1,355 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PA17 - - - - D0 - - - - PWM5 - - - - - PA18 - - - - D1 - - - - PWM6 - - - - - CEN - - - - - PA02 - - - - D2 - - - - RX1 - - - - SCL0 - - - - CS0 - - - - PWM2 - - - - TDO - - - - - PA15 - - - - D3 - - - - RX2 - - - - SCL0 - - - - CS0 - - - - PWM3 - - - - - PA04 - - - - D4 - - - - MOSI0 - - - - PWM4 - - - - tRST - - - - - PA19 - - - - D5 - - - - SCL0 - - - - MOSI0 - - - - PWM7 - - - - - 3V3 - - - - - GND - - - - - PA20 - - - - D6 - - - - SDA0 - - - - MISO0 - - - - PWM0 - - - - - PA16 - - - - D7 - - - - TX2 - - - - SDA0 - - - - SCK0 - - - - PWM4 - - - - - PA00 - - - - D8 - - - - RX1 - - - - PWM0 - - - - TCK - - - - SWCLK - - - - - PA03 - - - - D9 - - - - TX1 - - - - SDA0 - - - - SCK0 - - - - PWM3 - - - - TDI - - - - - PA01 - - - - D10 - - - - TX1 - - - - PWM1 - - - - TMS - - - - SWDIO - - - - - PA13 - - - - D11 - - - - RX0 - - - - PWM7 - - - - - PA14 - - - - D12 - - - - TX0 - - - - PWM2 - diff --git a/boards/bw15/pins_arduino.h b/boards/bw15/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/bw15/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/bw15/variant.h b/boards/bw15/variant.h deleted file mode 100644 index 32b21b3..0000000 --- a/boards/bw15/variant.h +++ /dev/null @@ -1,7 +0,0 @@ -/* This file was auto-generated from bw15.json using boardgen */ - -#pragma once - -#include - -// clang-format off diff --git a/boards/cb2l/README.md b/boards/cb2l/README.md deleted file mode 100644 index 103c865..0000000 --- a/boards/cb2l/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# CB2L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/cb2l-module-datasheet?id=Kai2eku1m3pyl) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `cb2l` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 9x GPIO, 5x PWM, 2x UART -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 -FCC ID | [2ANDL-CB2L](https://fccid.io/2ANDL-CB2L) - -## Usage - -**Board code:** `cb2l` - -In `platformio.ini`: - -```ini -[env:cb2l] -platform = libretuya -board = cb2l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: cb2l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_cb2l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----|----------|----------|-----|------|------ -D0 | P8 | | | | PWM2 | -D1 | P7 | | | | PWM1 | -D2 | P6 | | | | PWM0 | -D3 | P26 | | | | PWM5 | -D4 | P24 | | | | PWM4 | -D5 | P10 | UART1_RX | | | | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P11 | UART1_TX | | | | -D8 | P21 | | I2C1_SDA | | | TMS - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/cb2l/pinout_cb2l.svg b/boards/cb2l/pinout_cb2l.svg deleted file mode 100644 index f41a95e..0000000 --- a/boards/cb2l/pinout_cb2l.svg +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CB2L - - - - - - - - - - - - - - - - - - - - - - P8 - - - - D0 - - - - PWM2 - - - - - P7 - - - - D1 - - - - PWM1 - - - - - P6 - - - - D2 - - - - PWM0 - - - - - P26 - - - - D3 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D4 - - - - PWM4 - - - - - GND - - - - - 3V3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GND - - - - - CEN - - - - - P10 - - - - D5 - - - - RX1 - - - - - P0 - - - - D6 - - - - TX2 - - - - - P11 - - - - D7 - - - - TX1 - - - - - P21 - - - - D8 - diff --git a/boards/cb2l/pins_arduino.h b/boards/cb2l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/cb2l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/cb2l/variant.h b/boards/cb2l/variant.h deleted file mode 100644 index a09b1e7..0000000 --- a/boards/cb2l/variant.h +++ /dev/null @@ -1,49 +0,0 @@ -/* This file was auto-generated from cb2l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 9 -#define NUM_DIGITAL_PINS 9 -#define NUM_ANALOG_OUTPUTS 0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 0 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 1 -#define PIN_SERIAL1_RX 5u // GPIO10 -#define PIN_SERIAL1_TX 7u // GPIO11 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P6 2u // GPIO6 -#define PIN_FUNCTION_P7 1u // GPIO7 -#define PIN_FUNCTION_P8 0u // GPIO8 -#define PIN_FUNCTION_P10 5u // GPIO10 -#define PIN_FUNCTION_P11 7u // GPIO11 -#define PIN_FUNCTION_P21 8u // GPIO21 -#define PIN_FUNCTION_P24 4u // GPIO24 -#define PIN_FUNCTION_P26 3u // GPIO26 -#define PIN_FUNCTION_PWM0 2u // GPIO6 -#define PIN_FUNCTION_PWM1 1u // GPIO7 -#define PIN_FUNCTION_PWM2 0u // GPIO8 -#define PIN_FUNCTION_PWM4 4u // GPIO24 -#define PIN_FUNCTION_PWM5 3u // GPIO26 -#define PIN_FUNCTION_RX1 5u // GPIO10 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA1 8u // GPIO21 -#define PIN_FUNCTION_TX1 7u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/cb2s/README.md b/boards/cb2s/README.md deleted file mode 100644 index bdaf6f8..0000000 --- a/boards/cb2s/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# CB2S Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/cb2s-module-datasheet?id=Kafgfsa2aaypq) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `cb2s` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 5x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 -FCC ID | [2ANDL-CB2S](https://fccid.io/2ANDL-CB2S) - -## Usage - -**Board code:** `cb2s` - -In `platformio.ini`: - -```ini -[env:cb2s] -platform = libretuya -board = cb2s -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: cb2s - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_cb2s.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P6 | | | | PWM0 | -D1 | P7 | | | | PWM1 | -D2 | P8 | | | | PWM2 | -D3 | P23 | | | | | TDO -D4 | P10 | UART1_RX | | | | -D5 | P11 | UART1_TX | | | | -D6 | P24 | | | | PWM4 | -D7 | P26 | | | | PWM5 | -D8 | P0 | UART2_TX | I2C2_SCL | | | -D9 | P1 | UART2_RX | I2C2_SDA | | | -D10 | P21 | | I2C1_SDA | | | TMS -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/cb2s/pinout_cb2s.svg b/boards/cb2s/pinout_cb2s.svg deleted file mode 100644 index bb69c2f..0000000 --- a/boards/cb2s/pinout_cb2s.svg +++ /dev/null @@ -1,276 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CB2S - - - - - - - - - - - - - - - - - - - - - - P6 - - - - D0 - - - - PWM0 - - - - - P7 - - - - D1 - - - - PWM1 - - - - - P8 - - - - D2 - - - - PWM2 - - - - - P23 - - - - ADC3 - - - - D3 - - - - A0 - - - - - CEN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - GND - - - - - P10 - - - - D4 - - - - RX1 - - - - - P11 - - - - D5 - - - - TX1 - - - - - P24 - - - - D6 - - - - PWM4 - - - - - P26 - - - - D7 - - - - IRDA - - - - PWM5 - - - - - P1 - - - - D9 - - - - RX2 - - - - SDA2 - - - - - P0 - - - - D8 - - - - TX2 - - - - SCL2 - - - - - P21 - - - - D10 - - - - SDA1 - diff --git a/boards/cb2s/pins_arduino.h b/boards/cb2s/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/cb2s/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/cb2s/variant.h b/boards/cb2s/variant.h deleted file mode 100644 index f47ff6d..0000000 --- a/boards/cb2s/variant.h +++ /dev/null @@ -1,64 +0,0 @@ -/* This file was auto-generated from cb2s.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 11 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 3u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE2_SCL 8u // GPIO0 -#define PIN_WIRE2_SDA 9u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 4u // GPIO10 -#define PIN_SERIAL1_TX 5u // GPIO11 -#define PIN_SERIAL2_RX 9u // GPIO1 -#define PIN_SERIAL2_TX 8u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 3u // GPIO23 -#define PIN_FUNCTION_P0 8u // GPIO0 -#define PIN_FUNCTION_P1 9u // GPIO1 -#define PIN_FUNCTION_P6 0u // GPIO6 -#define PIN_FUNCTION_P7 1u // GPIO7 -#define PIN_FUNCTION_P8 2u // GPIO8 -#define PIN_FUNCTION_P10 4u // GPIO10 -#define PIN_FUNCTION_P11 5u // GPIO11 -#define PIN_FUNCTION_P21 10u // GPIO21 -#define PIN_FUNCTION_P23 3u // GPIO23 -#define PIN_FUNCTION_P24 6u // GPIO24 -#define PIN_FUNCTION_P26 7u // GPIO26 -#define PIN_FUNCTION_PWM0 0u // GPIO6 -#define PIN_FUNCTION_PWM1 1u // GPIO7 -#define PIN_FUNCTION_PWM2 2u // GPIO8 -#define PIN_FUNCTION_PWM4 6u // GPIO24 -#define PIN_FUNCTION_PWM5 7u // GPIO26 -#define PIN_FUNCTION_RX1 4u // GPIO10 -#define PIN_FUNCTION_RX2 9u // GPIO1 -#define PIN_FUNCTION_SCL2 8u // GPIO0 -#define PIN_FUNCTION_SDA1 10u // GPIO21 -#define PIN_FUNCTION_SDA2 9u // GPIO1 -#define PIN_FUNCTION_TX1 5u // GPIO11 -#define PIN_FUNCTION_TX2 8u // GPIO0 diff --git a/boards/cb3l/README.md b/boards/cb3l/README.md deleted file mode 100644 index 3d0a043..0000000 --- a/boards/cb3l/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# CB3L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/cb3l-module-datasheet?id=Kai51ngmrh3qm) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `cb3l` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 12x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 -FCC ID | [2ANDL-CB3L](https://fccid.io/2ANDL-CB3L) - -## Usage - -**Board code:** `cb3l` - -In `platformio.ini`: - -```ini -[env:cb3l] -platform = libretuya -board = cb3l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: cb3l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_cb3l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P23 | | | | | TDO -D1 | P14 | | | SCK | | -D2 | P26 | | | | PWM5 | -D3 | P24 | | | | PWM4 | -D4 | P6 | | | | PWM0 | -D5 | P9 | | | | PWM3 | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P21 | | I2C1_SDA | | | TMS -D8 | P8 | | | | PWM2 | -D9 | P7 | | | | PWM1 | -D10 | P10 | UART1_RX | | | | -D11 | P11 | UART1_TX | | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/cb3l/pinout_cb3l.svg b/boards/cb3l/pinout_cb3l.svg deleted file mode 100644 index 35eb017..0000000 --- a/boards/cb3l/pinout_cb3l.svg +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CB3L - - - - - - - - - - - - - - - - - CEN - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - - CEN - - - - - P14 - - - - D1 - - - - - P26 - - - - D2 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - P6 - - - - D4 - - - - PWM0 - - - - - 3V3 - - - - - GND - - - - - P9 - - - - D5 - - - - PWM3 - - - - - P0 - - - - D6 - - - - TX2 - - - - - P21 - - - - D7 - - - - - P8 - - - - D8 - - - - PWM2 - - - - - P7 - - - - D9 - - - - PWM1 - - - - - P10 - - - - D10 - - - - RX1 - - - - - P11 - - - - D11 - - - - TX1 - diff --git a/boards/cb3l/pins_arduino.h b/boards/cb3l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/cb3l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/cb3l/variant.h b/boards/cb3l/variant.h deleted file mode 100644 index b787cde..0000000 --- a/boards/cb3l/variant.h +++ /dev/null @@ -1,61 +0,0 @@ -/* This file was auto-generated from cb3l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 12 -#define NUM_DIGITAL_PINS 12 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 0u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 0 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 1 -#define PIN_SERIAL1_RX 10u // GPIO10 -#define PIN_SERIAL1_TX 11u // GPIO11 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 0u // GPIO23 -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P6 4u // GPIO6 -#define PIN_FUNCTION_P7 9u // GPIO7 -#define PIN_FUNCTION_P8 8u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 10u // GPIO10 -#define PIN_FUNCTION_P11 11u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P21 7u // GPIO21 -#define PIN_FUNCTION_P23 0u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 2u // GPIO26 -#define PIN_FUNCTION_PWM0 4u // GPIO6 -#define PIN_FUNCTION_PWM1 9u // GPIO7 -#define PIN_FUNCTION_PWM2 8u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 2u // GPIO26 -#define PIN_FUNCTION_RX1 10u // GPIO10 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA1 7u // GPIO21 -#define PIN_FUNCTION_TX1 11u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/cb3s/README.md b/boards/cb3s/README.md deleted file mode 100644 index 825ed95..0000000 --- a/boards/cb3s/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# CB3S Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/cb3s?id=Kai94mec0s076) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `cb3s` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 14x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 -FCC ID | [2ANDL-CB3S](https://fccid.io/2ANDL-CB3S) - -## Usage - -**Board code:** `cb3s` - -In `platformio.ini`: - -```ini -[env:cb3s] -platform = libretuya -board = cb3s -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: cb3s - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_cb3s.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P23 | | | | | TDO -D1 | P14 | | | SCK | | -D2 | P26 | | | | PWM5 | -D3 | P24 | | | | PWM4 | -D4 | P6 | | | | PWM0 | -D5 | P9 | | | | PWM3 | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P21 | | I2C1_SDA | | | TMS -D8 | P8 | | | | PWM2 | -D9 | P7 | | | | PWM1 | -D10 | P10 | UART1_RX | | | | -D11 | P11 | UART1_TX | | | | -D12 | P22 | | | | | TDI -D13 | P20 | | I2C1_SCL | | | TCK -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/cb3s/pinout_cb3s.svg b/boards/cb3s/pinout_cb3s.svg deleted file mode 100644 index a35a0eb..0000000 --- a/boards/cb3s/pinout_cb3s.svg +++ /dev/null @@ -1,375 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CB3S - - - - - - - - - - - - - - - - - CEN - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - CEN - - - - - P14 - - - - D1 - - - - - P26 - - - - D2 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - P6 - - - - D4 - - - - PWM0 - - - - - 3V3 - - - - - GND - - - - - P9 - - - - D5 - - - - PWM3 - - - - - P0 - - - - D6 - - - - TX2 - - - - - P21 - - - - D7 - - - - SDA1 - - - - TMS - - - - ___ - FCS - - - - - P8 - - - - D8 - - - - PWM2 - - - - - P7 - - - - D9 - - - - PWM1 - - - - - P10 - - - - D10 - - - - RX1 - - - - - P11 - - - - D11 - - - - TX1 - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - P22 - - - - D12 - - - - TDI - - - - FSI - - - - - P21 - - - - D7 - - - - SDA1 - - - - TMS - - - - ___ - FCS - - - - - P20 - - - - D13 - - - - SCL1 - - - - TCK - - - - FSCK - - - diff --git a/boards/cb3s/pins_arduino.h b/boards/cb3s/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/cb3s/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/cb3s/variant.h b/boards/cb3s/variant.h deleted file mode 100644 index 991948c..0000000 --- a/boards/cb3s/variant.h +++ /dev/null @@ -1,69 +0,0 @@ -/* This file was auto-generated from cb3s.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 14 -#define NUM_DIGITAL_PINS 14 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 0u // GPIO23 -#define PIN_A0 0u // GPIO23 -#define A0 PIN_A0 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE1_SCL 13u // GPIO20 -#define PIN_WIRE1_SDA_0 7u // GPIO21 -#define PIN_WIRE1_SDA_1 7u // GPIO21 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 1 -#define PIN_SERIAL1_RX 10u // GPIO10 -#define PIN_SERIAL1_TX 11u // GPIO11 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 0u // GPIO23 -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P6 4u // GPIO6 -#define PIN_FUNCTION_P7 9u // GPIO7 -#define PIN_FUNCTION_P8 8u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 10u // GPIO10 -#define PIN_FUNCTION_P11 11u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P20 13u // GPIO20 -#define PIN_FUNCTION_P21 7u // GPIO21 -#define PIN_FUNCTION_P22 12u // GPIO22 -#define PIN_FUNCTION_P23 0u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 2u // GPIO26 -#define PIN_FUNCTION_PWM0 4u // GPIO6 -#define PIN_FUNCTION_PWM1 9u // GPIO7 -#define PIN_FUNCTION_PWM2 8u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 2u // GPIO26 -#define PIN_FUNCTION_RX1 10u // GPIO10 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL1 13u // GPIO20 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA1 7u // GPIO21 -#define PIN_FUNCTION_TX1 11u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/cb3se/README.md b/boards/cb3se/README.md deleted file mode 100644 index 584b8be..0000000 --- a/boards/cb3se/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# CB3SE Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/CB3SE-Module-Datasheet?id=Kanoiluul7nl2) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|-------------------------------------------- -Board code | `cb3se` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 17x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 -FCC ID | [2ANDL-CB3SE](https://fccid.io/2ANDL-CB3SE) - -## Usage - -**Board code:** `cb3se` - -In `platformio.ini`: - -```ini -[env:cb3se] -platform = libretuya -board = cb3se -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: cb3se - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_cb3se.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P23 | | | | | TDO -D1 | P14 | | | SCK | | -D2 | P26 | | | | PWM5 | -D3 | P24 | | | | PWM4 | -D4 | P6 | | | | PWM0 | -D5 | P9 | | | | PWM3 | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P1 | UART2_RX | I2C2_SDA | | | -D8 | P8 | | | | PWM2 | -D9 | P7 | | | | PWM1 | -D10 | P10 | UART1_RX | | | | -D11 | P11 | UART1_TX | | | | -D12 | P15 | | | CS | | -D13 | P22 | | | | | TDI -D14 | P20 | | I2C1_SCL | | | TCK -D15 | P17 | | | MISO | | -D16 | P16 | | | MOSI | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/cb3se/pinout_cb3se.svg b/boards/cb3se/pinout_cb3se.svg deleted file mode 100644 index 4b9e01a..0000000 --- a/boards/cb3se/pinout_cb3se.svg +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CB3SE - - - - - - - - - - - - - - - - - CEN - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - - CEN - - - - - P14 - - - - D1 - - - - SCK - - - - - P26 - - - - D2 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - P6 - - - - D4 - - - - PWM0 - - - - - 3V3 - - - - - GND - - - - - P9 - - - - D5 - - - - PWM3 - - - - - P0 - - - - D6 - - - - TX2 - - - - SCL2 - - - - - P1 - - - - D7 - - - - RX2 - - - - SDA2 - - - - - P8 - - - - D8 - - - - PWM2 - - - - - P7 - - - - D9 - - - - PWM1 - - - - - P10 - - - - D10 - - - - RX1 - - - - - P11 - - - - D11 - - - - TX1 - - - - - P15 - - - - D12 - - - - CS - - - - - P22 - - - - D13 - - - - - GND - - - - - P20 - - - - D14 - - - - - P17 - - - - D15 - - - - MISO - - - - - P16 - - - - D16 - - - - MOSI - diff --git a/boards/cb3se/pins_arduino.h b/boards/cb3se/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/cb3se/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/cb3se/variant.h b/boards/cb3se/variant.h deleted file mode 100644 index ad56ccd..0000000 --- a/boards/cb3se/variant.h +++ /dev/null @@ -1,75 +0,0 @@ -/* This file was auto-generated from cb3se.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 17 -#define NUM_DIGITAL_PINS 17 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 0u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE2_SCL 6u // GPIO0 -#define PIN_WIRE2_SDA 7u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 10u // GPIO10 -#define PIN_SERIAL1_TX 11u // GPIO11 -#define PIN_SERIAL2_RX 7u // GPIO1 -#define PIN_SERIAL2_TX 6u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 0u // GPIO23 -#define PIN_FUNCTION_CS 12u // GPIO15 -#define PIN_FUNCTION_MISO 15u // GPIO17 -#define PIN_FUNCTION_MOSI 16u // GPIO16 -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P1 7u // GPIO1 -#define PIN_FUNCTION_P6 4u // GPIO6 -#define PIN_FUNCTION_P7 9u // GPIO7 -#define PIN_FUNCTION_P8 8u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 10u // GPIO10 -#define PIN_FUNCTION_P11 11u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P15 12u // GPIO15 -#define PIN_FUNCTION_P16 16u // GPIO16 -#define PIN_FUNCTION_P17 15u // GPIO17 -#define PIN_FUNCTION_P20 14u // GPIO20 -#define PIN_FUNCTION_P22 13u // GPIO22 -#define PIN_FUNCTION_P23 0u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 2u // GPIO26 -#define PIN_FUNCTION_PWM0 4u // GPIO6 -#define PIN_FUNCTION_PWM1 9u // GPIO7 -#define PIN_FUNCTION_PWM2 8u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 2u // GPIO26 -#define PIN_FUNCTION_RX1 10u // GPIO10 -#define PIN_FUNCTION_RX2 7u // GPIO1 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL1 14u // GPIO20 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA2 7u // GPIO1 -#define PIN_FUNCTION_TX1 11u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/generic-bk7231n-qfn32-tuya.json b/boards/generic-bk7231n-qfn32-tuya.json index 127451a..03f346c 100644 --- a/boards/generic-bk7231n-qfn32-tuya.json +++ b/boards/generic-bk7231n-qfn32-tuya.json @@ -12,7 +12,7 @@ }, "name": "Generic - BK7231N (Tuya QFN32)", "symbol": "BK7231N (Tuya QFN32)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-bk7231n-qfn32-tuya/", + "url": "https://docs.libretiny.eu/boards/generic-bk7231n-qfn32-tuya/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-bk7231n-qfn32-tuya/README.md b/boards/generic-bk7231n-qfn32-tuya/README.md deleted file mode 100644 index a6a34c7..0000000 --- a/boards/generic-bk7231n-qfn32-tuya/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# Generic - BK7231N (Tuya QFN32) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-bk7231n-qfn32-tuya/) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-bk7231n-qfn32-tuya` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 19x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 - -## Usage - -**Board code:** `generic-bk7231n-qfn32-tuya` - -In `platformio.ini`: - -```ini -[env:generic-bk7231n-qfn32-tuya] -platform = libretuya -board = generic-bk7231n-qfn32-tuya -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-bk7231n-qfn32-tuya - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P0 | UART2_TX | I2C2_SCL | | | -D1 | P1 | UART2_RX | I2C2_SDA | | | -D2 | P6 | | | | PWM0 | -D3 | P7 | | | | PWM1 | -D4 | P8 | | | | PWM2 | -D5 | P9 | | | | PWM3 | -D6 | P10 | UART1_RX | | | | -D7 | P11 | UART1_TX | | | | -D8 | P14 | | | SCK | | -D9 | P15 | | | CS | | -D10 | P16 | | | MOSI | | -D11 | P17 | | | MISO | | -D12 | P20 | | I2C1_SCL | | | TCK -D13 | P21 | | I2C1_SDA | | | TMS -D14 | P22 | | | | | TDI -D15 | P23 | | | | | TDO -D16 | P24 | | | | PWM4 | -D17 | P26 | | | | PWM5 | -D18 | P28 | | | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/generic-bk7231n-qfn32-tuya/pins_arduino.h b/boards/generic-bk7231n-qfn32-tuya/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-bk7231n-qfn32-tuya/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-bk7231n-qfn32-tuya/variant.h b/boards/generic-bk7231n-qfn32-tuya/variant.h deleted file mode 100644 index 11cd0e6..0000000 --- a/boards/generic-bk7231n-qfn32-tuya/variant.h +++ /dev/null @@ -1,80 +0,0 @@ -/* This file was auto-generated from generic-bk7231n-qfn32-tuya.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 19 -#define NUM_DIGITAL_PINS 19 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 15u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 12u // GPIO20 -#define PIN_WIRE1_SDA 13u // GPIO21 -#define PIN_WIRE2_SCL 0u // GPIO0 -#define PIN_WIRE2_SDA 1u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 6u // GPIO10 -#define PIN_SERIAL1_TX 7u // GPIO11 -#define PIN_SERIAL2_RX 1u // GPIO1 -#define PIN_SERIAL2_TX 0u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 15u // GPIO23 -#define PIN_FUNCTION_CS 9u // GPIO15 -#define PIN_FUNCTION_MISO 11u // GPIO17 -#define PIN_FUNCTION_MOSI 10u // GPIO16 -#define PIN_FUNCTION_P0 0u // GPIO0 -#define PIN_FUNCTION_P1 1u // GPIO1 -#define PIN_FUNCTION_P6 2u // GPIO6 -#define PIN_FUNCTION_P7 3u // GPIO7 -#define PIN_FUNCTION_P8 4u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 6u // GPIO10 -#define PIN_FUNCTION_P11 7u // GPIO11 -#define PIN_FUNCTION_P14 8u // GPIO14 -#define PIN_FUNCTION_P15 9u // GPIO15 -#define PIN_FUNCTION_P16 10u // GPIO16 -#define PIN_FUNCTION_P17 11u // GPIO17 -#define PIN_FUNCTION_P20 12u // GPIO20 -#define PIN_FUNCTION_P21 13u // GPIO21 -#define PIN_FUNCTION_P22 14u // GPIO22 -#define PIN_FUNCTION_P23 15u // GPIO23 -#define PIN_FUNCTION_P24 16u // GPIO24 -#define PIN_FUNCTION_P26 17u // GPIO26 -#define PIN_FUNCTION_P28 18u // GPIO28 -#define PIN_FUNCTION_PWM0 2u // GPIO6 -#define PIN_FUNCTION_PWM1 3u // GPIO7 -#define PIN_FUNCTION_PWM2 4u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 16u // GPIO24 -#define PIN_FUNCTION_PWM5 17u // GPIO26 -#define PIN_FUNCTION_RX1 6u // GPIO10 -#define PIN_FUNCTION_RX2 1u // GPIO1 -#define PIN_FUNCTION_SCK 8u // GPIO14 -#define PIN_FUNCTION_SCL1 12u // GPIO20 -#define PIN_FUNCTION_SCL2 0u // GPIO0 -#define PIN_FUNCTION_SDA1 13u // GPIO21 -#define PIN_FUNCTION_SDA2 1u // GPIO1 -#define PIN_FUNCTION_TX1 7u // GPIO11 -#define PIN_FUNCTION_TX2 0u // GPIO0 diff --git a/boards/generic-bk7231t-qfn32-tuya.json b/boards/generic-bk7231t-qfn32-tuya.json index 473efe5..d748612 100644 --- a/boards/generic-bk7231t-qfn32-tuya.json +++ b/boards/generic-bk7231t-qfn32-tuya.json @@ -12,7 +12,7 @@ }, "name": "Generic - BK7231T (Tuya QFN32)", "symbol": "BK7231T (Tuya QFN32)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-bk7231t-qfn32-tuya/", + "url": "https://docs.libretiny.eu/boards/generic-bk7231t-qfn32-tuya/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-bk7231t-qfn32-tuya/README.md b/boards/generic-bk7231t-qfn32-tuya/README.md deleted file mode 100644 index 8554058..0000000 --- a/boards/generic-bk7231t-qfn32-tuya/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# Generic - BK7231T (Tuya QFN32) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-bk7231t-qfn32-tuya/) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-bk7231t-qfn32-tuya` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 19x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 - -## Usage - -**Board code:** `generic-bk7231t-qfn32-tuya` - -In `platformio.ini`: - -```ini -[env:generic-bk7231t-qfn32-tuya] -platform = libretuya -board = generic-bk7231t-qfn32-tuya -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-bk7231t-qfn32-tuya - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P0 | UART2_TX | I2C2_SCL | | | -D1 | P1 | UART2_RX | I2C2_SDA | | | -D2 | P6 | | | | PWM0 | -D3 | P7 | | | | PWM1 | -D4 | P8 | | | | PWM2 | -D5 | P9 | | | | PWM3 | -D6 | P10 | UART1_RX | | | | -D7 | P11 | UART1_TX | | | | -D8 | P14 | | | SCK | | -D9 | P15 | | | CS | | -D10 | P16 | | | MOSI | | -D11 | P17 | | | MISO | | -D12 | P20 | | I2C1_SCL | | | TCK -D13 | P21 | | I2C1_SDA | | | TMS -D14 | P22 | | | | | TDI -D15 | P23 | | | | | TDO -D16 | P24 | | | | PWM4 | -D17 | P26 | | | | PWM5 | -D18 | P28 | | | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/generic-bk7231t-qfn32-tuya/pins_arduino.h b/boards/generic-bk7231t-qfn32-tuya/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-bk7231t-qfn32-tuya/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-bk7231t-qfn32-tuya/variant.h b/boards/generic-bk7231t-qfn32-tuya/variant.h deleted file mode 100644 index bf4e5ae..0000000 --- a/boards/generic-bk7231t-qfn32-tuya/variant.h +++ /dev/null @@ -1,80 +0,0 @@ -/* This file was auto-generated from generic-bk7231t-qfn32-tuya.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 19 -#define NUM_DIGITAL_PINS 19 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 15u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 12u // GPIO20 -#define PIN_WIRE1_SDA 13u // GPIO21 -#define PIN_WIRE2_SCL 0u // GPIO0 -#define PIN_WIRE2_SDA 1u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 6u // GPIO10 -#define PIN_SERIAL1_TX 7u // GPIO11 -#define PIN_SERIAL2_RX 1u // GPIO1 -#define PIN_SERIAL2_TX 0u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 15u // GPIO23 -#define PIN_FUNCTION_CS 9u // GPIO15 -#define PIN_FUNCTION_MISO 11u // GPIO17 -#define PIN_FUNCTION_MOSI 10u // GPIO16 -#define PIN_FUNCTION_P0 0u // GPIO0 -#define PIN_FUNCTION_P1 1u // GPIO1 -#define PIN_FUNCTION_P6 2u // GPIO6 -#define PIN_FUNCTION_P7 3u // GPIO7 -#define PIN_FUNCTION_P8 4u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 6u // GPIO10 -#define PIN_FUNCTION_P11 7u // GPIO11 -#define PIN_FUNCTION_P14 8u // GPIO14 -#define PIN_FUNCTION_P15 9u // GPIO15 -#define PIN_FUNCTION_P16 10u // GPIO16 -#define PIN_FUNCTION_P17 11u // GPIO17 -#define PIN_FUNCTION_P20 12u // GPIO20 -#define PIN_FUNCTION_P21 13u // GPIO21 -#define PIN_FUNCTION_P22 14u // GPIO22 -#define PIN_FUNCTION_P23 15u // GPIO23 -#define PIN_FUNCTION_P24 16u // GPIO24 -#define PIN_FUNCTION_P26 17u // GPIO26 -#define PIN_FUNCTION_P28 18u // GPIO28 -#define PIN_FUNCTION_PWM0 2u // GPIO6 -#define PIN_FUNCTION_PWM1 3u // GPIO7 -#define PIN_FUNCTION_PWM2 4u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 16u // GPIO24 -#define PIN_FUNCTION_PWM5 17u // GPIO26 -#define PIN_FUNCTION_RX1 6u // GPIO10 -#define PIN_FUNCTION_RX2 1u // GPIO1 -#define PIN_FUNCTION_SCK 8u // GPIO14 -#define PIN_FUNCTION_SCL1 12u // GPIO20 -#define PIN_FUNCTION_SCL2 0u // GPIO0 -#define PIN_FUNCTION_SDA1 13u // GPIO21 -#define PIN_FUNCTION_SDA2 1u // GPIO1 -#define PIN_FUNCTION_TX1 7u // GPIO11 -#define PIN_FUNCTION_TX2 0u // GPIO0 diff --git a/boards/generic-bk7252.json b/boards/generic-bk7252.json index 2cc46fc..4705351 100644 --- a/boards/generic-bk7252.json +++ b/boards/generic-bk7252.json @@ -11,7 +11,7 @@ }, "name": "Generic - BK7252", "symbol": "BK7252", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-bk7252/", + "url": "https://docs.libretiny.eu/boards/generic-bk7252/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-bk7252/README.md b/boards/generic-bk7252/README.md deleted file mode 100644 index 6517fed..0000000 --- a/boards/generic-bk7252/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# Generic - BK7252 - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-bk7252/) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-bk7252` -MCU | BK7252 -Manufacturer | Beken -Series | BK72XX -Frequency | 180 MHz -Flash size | 4 MiB -RAM size | 512 KiB -Voltage | 3.0V - 3.6V -I/O | 38x GPIO, 4x PWM, 2x UART, 7x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.0 - -## Usage - -**Board code:** `generic-bk7252` - -In `platformio.ini`: - -```ini -[env:generic-bk7252] -platform = libretuya -board = generic-bk7252 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-bk7252 - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|-----------|----------|------|------|---------- -D0 | P0 | UART2_TX | I2C2_SCL | | | -D1 | P1 | UART2_RX | I2C2_SDA | | | -D2 | P2 | | | | | -D3 | P3 | | | | | -D4 | P4 | | | | | -D5 | P5 | | | | | -D6 | P6 | | | | PWM0 | -D7 | P7 | | | | PWM1 | -D8 | P10 | UART1_RX | | | | -D9 | P11 | UART1_TX | | | | -D10 | P12 | UART1_CTS | | | | -D11 | P13 | UART1_RTS | | | | -D12 | P14 | | | SCK | | -D13 | P15 | | | CS | | -D14 | P16 | | | MOSI | | -D15 | P17 | | | MISO | | -D16 | P18 | | | | | -D17 | P19 | | | | | -D18 | P20 | | I2C1_SCL | | | TCK -D19 | P21 | | I2C1_SDA | | | TMS -D20 | P22 | | | | | TDI -D21 | P23 | | | | | TDO -D22 | P24 | | | | PWM4 | -D23 | P25 | | | | | -D24 | P26 | | | | PWM5 | -D25 | P27 | | | | | DVP_MCLK -D26 | P28 | | | | | -D27 | P29 | | | | | DVP_PCLK -D28 | P30 | | | | | DVP_HSYNC -D29 | P31 | | | | | DVP_VSYNC -D30 | P32 | | | | | DVP_PD0 -D31 | P33 | | | | | DVP_PD1 -D32 | P34 | | | | | DVP_PD2 -D33 | P35 | | | | | DVP_PD3 -D34 | P36 | | | | | DVP_PD4 -D35 | P37 | | | | | DVP_PD5 -D36 | P38 | | | | | DVP_PD6 -D37 | P39 | | | | | DVP_PD7 -A1 | P4, ADC1 | | | | | -A2 | P5, ADC2 | | | | | -A3 | P23, ADC3 | | | | | -A4 | P3, ADC5 | | | | | -A5 | P2, ADC4 | | | | | -A6 | P12, ADC6 | | | | | -A7 | P13, ADC7 | | | | | - -## Flash memory map - -Flash size: 4 MiB / 4,194,304 B / 0x400000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.7 MiB / 0x1BA000 | 0x1CB000 -File System | 0x1CB000 | 1.1 MiB / 0x119000 | 0x2E4000 -Key-Value Store | 0x2E4000 | 32 KiB / 0x8000 | 0x2EC000 -OTA Image | 0x2EC000 | 1.1 MiB / 0x112000 | 0x3FE000 -Calibration | 0x3FE000 | 4 KiB / 0x1000 | 0x3FF000 -TLV Store | 0x3FF000 | 4 KiB / 0x1000 | 0x400000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/generic-bk7252/pins_arduino.h b/boards/generic-bk7252/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-bk7252/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-bk7252/variant.h b/boards/generic-bk7252/variant.h deleted file mode 100644 index 47c4a52..0000000 --- a/boards/generic-bk7252/variant.h +++ /dev/null @@ -1,119 +0,0 @@ -/* This file was auto-generated from generic-bk7252.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 38 -#define NUM_DIGITAL_PINS 38 -#define NUM_ANALOG_INPUTS 7 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A5 2u // GPIO2 -#define PIN_A4 3u // GPIO3 -#define PIN_A1 4u // GPIO4 -#define PIN_A2 5u // GPIO5 -#define PIN_A6 10u // GPIO12 -#define PIN_A7 11u // GPIO13 -#define PIN_A3 21u // GPIO23 -#define A5 PIN_A5 -#define A4 PIN_A4 -#define A1 PIN_A1 -#define A2 PIN_A2 -#define A6 PIN_A6 -#define A7 PIN_A7 -#define A3 PIN_A3 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 18u // GPIO20 -#define PIN_WIRE1_SDA 19u // GPIO21 -#define PIN_WIRE2_SCL 0u // GPIO0 -#define PIN_WIRE2_SDA 1u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_CTS 10u // GPIO12 -#define PIN_SERIAL1_RTS 11u // GPIO13 -#define PIN_SERIAL1_RX 8u // GPIO10 -#define PIN_SERIAL1_TX 9u // GPIO11 -#define PIN_SERIAL2_RX 1u // GPIO1 -#define PIN_SERIAL2_TX 0u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 4u // GPIO4 -#define PIN_FUNCTION_ADC2 5u // GPIO5 -#define PIN_FUNCTION_ADC3 21u // GPIO23 -#define PIN_FUNCTION_ADC4 2u // GPIO2 -#define PIN_FUNCTION_ADC5 3u // GPIO3 -#define PIN_FUNCTION_ADC6 10u // GPIO12 -#define PIN_FUNCTION_ADC7 11u // GPIO13 -#define PIN_FUNCTION_CS 13u // GPIO15 -#define PIN_FUNCTION_CTS1 10u // GPIO12 -#define PIN_FUNCTION_MISO 15u // GPIO17 -#define PIN_FUNCTION_MOSI 14u // GPIO16 -#define PIN_FUNCTION_P0 0u // GPIO0 -#define PIN_FUNCTION_P1 1u // GPIO1 -#define PIN_FUNCTION_P2 2u // GPIO2 -#define PIN_FUNCTION_P3 3u // GPIO3 -#define PIN_FUNCTION_P4 4u // GPIO4 -#define PIN_FUNCTION_P5 5u // GPIO5 -#define PIN_FUNCTION_P6 6u // GPIO6 -#define PIN_FUNCTION_P7 7u // GPIO7 -#define PIN_FUNCTION_P10 8u // GPIO10 -#define PIN_FUNCTION_P11 9u // GPIO11 -#define PIN_FUNCTION_P12 10u // GPIO12 -#define PIN_FUNCTION_P13 11u // GPIO13 -#define PIN_FUNCTION_P14 12u // GPIO14 -#define PIN_FUNCTION_P15 13u // GPIO15 -#define PIN_FUNCTION_P16 14u // GPIO16 -#define PIN_FUNCTION_P17 15u // GPIO17 -#define PIN_FUNCTION_P18 16u // GPIO18 -#define PIN_FUNCTION_P19 17u // GPIO19 -#define PIN_FUNCTION_P20 18u // GPIO20 -#define PIN_FUNCTION_P21 19u // GPIO21 -#define PIN_FUNCTION_P22 20u // GPIO22 -#define PIN_FUNCTION_P23 21u // GPIO23 -#define PIN_FUNCTION_P24 22u // GPIO24 -#define PIN_FUNCTION_P25 23u // GPIO25 -#define PIN_FUNCTION_P26 24u // GPIO26 -#define PIN_FUNCTION_P27 25u // GPIO27 -#define PIN_FUNCTION_P28 26u // GPIO28 -#define PIN_FUNCTION_P29 27u // GPIO29 -#define PIN_FUNCTION_P30 28u // GPIO30 -#define PIN_FUNCTION_P31 29u // GPIO31 -#define PIN_FUNCTION_P32 30u // GPIO32 -#define PIN_FUNCTION_P33 31u // GPIO33 -#define PIN_FUNCTION_P34 32u // GPIO34 -#define PIN_FUNCTION_P35 33u // GPIO35 -#define PIN_FUNCTION_P36 34u // GPIO36 -#define PIN_FUNCTION_P37 35u // GPIO37 -#define PIN_FUNCTION_P38 36u // GPIO38 -#define PIN_FUNCTION_P39 37u // GPIO39 -#define PIN_FUNCTION_PWM0 6u // GPIO6 -#define PIN_FUNCTION_PWM1 7u // GPIO7 -#define PIN_FUNCTION_PWM4 22u // GPIO24 -#define PIN_FUNCTION_PWM5 24u // GPIO26 -#define PIN_FUNCTION_RTS1 11u // GPIO13 -#define PIN_FUNCTION_RX1 8u // GPIO10 -#define PIN_FUNCTION_RX2 1u // GPIO1 -#define PIN_FUNCTION_SCK 12u // GPIO14 -#define PIN_FUNCTION_SCL1 18u // GPIO20 -#define PIN_FUNCTION_SCL2 0u // GPIO0 -#define PIN_FUNCTION_SDA1 19u // GPIO21 -#define PIN_FUNCTION_SDA2 1u // GPIO1 -#define PIN_FUNCTION_TX1 9u // GPIO11 -#define PIN_FUNCTION_TX2 0u // GPIO0 diff --git a/boards/generic-native.json b/boards/generic-native.json deleted file mode 100644 index 00dfd6e..0000000 --- a/boards/generic-native.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "build": { - "family": "NATIVE", - "mcu": "native", - "f_cpu": "1000000000L", - "variant": "generic-native" - }, - "flash": { - "bootloader": "0x000000+0x10000", - "system": "0x010000+0x10000", - "ota1": "0x020000+0x100000", - "ota2": "0x120000+0x100000", - "download": "0x220000+0x100000", - "kvs": "0x320000+0x40000", - "userdata": "0x360000+0xA0000" - }, - "connectivity": [ - "wifi" - ], - "frameworks": [ - "host-native-sdk", - "host-native-arduino" - ], - "upload": { - "maximum_ram_size": 4194304, - "flash_size": 4194304, - "maximum_size": 1048576 - }, - "doc": { - "params": { - "manufacturer": "N/A", - "series": "N/A", - "voltage": "5V" - }, - "extra": [ - "## Description", - "`generic-native` is a dummy board using the `host-native` family, which also serves as a template for building new families, as well as for testing flash-related modules (i.e. Fat FS, OTA, etc)." - ] - }, - "name": "Generic - Host-native", - "vendor": "N/A", - "url": "https://kuba2k2.github.io/libretuya/", - "symbol": "Native" -} diff --git a/boards/generic-native/README.md b/boards/generic-native/README.md deleted file mode 100644 index 48a61a4..0000000 --- a/boards/generic-native/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# Generic - Host-native - -*by N/A* - -[Product page](https://kuba2k2.github.io/libretuya/) - -Parameter | Value --------------|----------------- -Board code | `generic-native` -MCU | NATIVE -Manufacturer | N/A -Series | N/A -Frequency | 1 GHz -Flash size | 4 MiB -RAM size | 4 MiB -Voltage | 5V - -## Usage - -**Board code:** `generic-native` - -In `platformio.ini`: - -```ini -[env:generic-native] -platform = libretuya -board = generic-native -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-native - framework: - version: dev -``` - -## Flash memory map - -Flash size: 4 MiB / 4,194,304 B / 0x400000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Bootloader | 0x000000 | 64 KiB / 0x10000 | 0x010000 -System Data | 0x010000 | 64 KiB / 0x10000 | 0x020000 -OTA1 Image | 0x020000 | 1 MiB / 0x100000 | 0x120000 -OTA2 Image | 0x120000 | 1 MiB / 0x100000 | 0x220000 -OTA Image | 0x220000 | 1 MiB / 0x100000 | 0x320000 -Key-Value Store | 0x320000 | 256 KiB / 0x40000 | 0x360000 -User Data | 0x360000 | 640 KiB / 0xA0000 | 0x400000 - -## Description - -`generic-native` is a dummy board using the `host-native` family, which also serves as a template for building new families, as well as for testing flash-related modules (i.e. Fat FS, OTA, etc). diff --git a/boards/generic-native/pins_arduino.h b/boards/generic-native/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-native/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-native/variant.h b/boards/generic-native/variant.h deleted file mode 100644 index 4c3b6cd..0000000 --- a/boards/generic-native/variant.h +++ /dev/null @@ -1,7 +0,0 @@ -/* This file was auto-generated from generic-native.json using boardgen */ - -#pragma once - -#include - -// clang-format off diff --git a/boards/generic-rtl8710bn-2mb-468k.json b/boards/generic-rtl8710bn-2mb-468k.json index 06148fe..c3206b8 100644 --- a/boards/generic-rtl8710bn-2mb-468k.json +++ b/boards/generic-rtl8710bn-2mb-468k.json @@ -11,7 +11,7 @@ }, "name": "Generic - RTL8710BN (2M/468k)", "symbol": "RTL8710BN (2M/468k)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bn-2mb-468k/", + "url": "https://docs.libretiny.eu/boards/generic-rtl8710bn-2mb-468k/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-rtl8710bn-2mb-468k/README.md b/boards/generic-rtl8710bn-2mb-468k/README.md deleted file mode 100644 index 8d692ca..0000000 --- a/boards/generic-rtl8710bn-2mb-468k/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# Generic - RTL8710BN (2M/468k) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bn-2mb-468k/) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-rtl8710bn-2mb-468k` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 17x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n - -## Usage - -**Board code:** `generic-rtl8710bn-2mb-468k` - -In `platformio.ini`: - -```ini -[env:generic-rtl8710bn-2mb-468k] -platform = libretuya -board = generic-rtl8710bn-2mb-468k -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-rtl8710bn-2mb-468k - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA00 | | | | PWM2 | -D1 | PA05 | | | | PWM4 | -D2 | PA06 | | | FCS | | -D3 | PA07 | | | FD1 | | -D4 | PA08 | | | FD2 | | -D5 | PA09 | | | FD0 | | -D6 | PA10 | | | FSCK | | -D7 | PA11 | | | FD3 | | -D8 | PA12 | | | | PWM3 | -D9 | PA14 | | | | PWM0 | SWCLK -D10 | PA15 | | | | PWM1 | SWDIO -D11 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D12 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D13 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D14 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -D15 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D16 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 468 KiB / 0x75000 | 0x080000 -OTA2 Image | 0x080000 | 468 KiB / 0x75000 | 0x0F5000 -Key-Value Store | 0x0F5000 | 24 KiB / 0x6000 | 0x0FB000 -User Data | 0x0FB000 | 1 MiB / 0x104000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/generic-rtl8710bn-2mb-468k/pins_arduino.h b/boards/generic-rtl8710bn-2mb-468k/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-rtl8710bn-2mb-468k/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-rtl8710bn-2mb-468k/variant.h b/boards/generic-rtl8710bn-2mb-468k/variant.h deleted file mode 100644 index 8906bd4..0000000 --- a/boards/generic-rtl8710bn-2mb-468k/variant.h +++ /dev/null @@ -1,95 +0,0 @@ -/* This file was auto-generated from generic-rtl8710bn-2mb-468k.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 18 -#define NUM_DIGITAL_PINS 17 -#define NUM_ANALOG_INPUTS 2 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 12u // PA_19 -#define PIN_A1 17u // AD_2 -#define A0 PIN_A0 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 12u // PA_19 -#define PIN_SPI0_MISO 13u // PA_22 -#define PIN_SPI0_MOSI 14u // PA_23 -#define PIN_SPI0_SCK 11u // PA_18 -#define PIN_SPI1_CS 12u // PA_19 -#define PIN_SPI1_MISO 13u // PA_22 -#define PIN_SPI1_MOSI 14u // PA_23 -#define PIN_SPI1_SCK 11u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 13u // PA_22 -#define PIN_WIRE0_SCL_1 15u // PA_29 -#define PIN_WIRE0_SDA_0 12u // PA_19 -#define PIN_WIRE0_SDA_1 16u // PA_30 -#define PIN_WIRE1_SCL 11u // PA_18 -#define PIN_WIRE1_SDA 14u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 12u // PA_19 -#define PIN_SERIAL0_RTS 13u // PA_22 -#define PIN_SERIAL0_RX 11u // PA_18 -#define PIN_SERIAL0_TX 14u // PA_23 -#define PIN_SERIAL2_RX 15u // PA_29 -#define PIN_SERIAL2_TX 16u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 12u // PA_19 -#define PIN_FUNCTION_ADC2 17u // AD_2 -#define PIN_FUNCTION_CS0 12u // PA_19 -#define PIN_FUNCTION_CS1 12u // PA_19 -#define PIN_FUNCTION_CTS0 12u // PA_19 -#define PIN_FUNCTION_FCS 2u // PA_6 -#define PIN_FUNCTION_FD0 5u // PA_9 -#define PIN_FUNCTION_FD1 3u // PA_7 -#define PIN_FUNCTION_FD2 4u // PA_8 -#define PIN_FUNCTION_FD3 7u // PA_11 -#define PIN_FUNCTION_FSCK 6u // PA_10 -#define PIN_FUNCTION_MISO0 13u // PA_22 -#define PIN_FUNCTION_MISO1 13u // PA_22 -#define PIN_FUNCTION_MOSI0 14u // PA_23 -#define PIN_FUNCTION_MOSI1 14u // PA_23 -#define PIN_FUNCTION_PA00 0u // PA_0 -#define PIN_FUNCTION_PA05 1u // PA_5 -#define PIN_FUNCTION_PA06 2u // PA_6 -#define PIN_FUNCTION_PA07 3u // PA_7 -#define PIN_FUNCTION_PA08 4u // PA_8 -#define PIN_FUNCTION_PA09 5u // PA_9 -#define PIN_FUNCTION_PA10 6u // PA_10 -#define PIN_FUNCTION_PA11 7u // PA_11 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 9u // PA_14 -#define PIN_FUNCTION_PA15 10u // PA_15 -#define PIN_FUNCTION_PA18 11u // PA_18 -#define PIN_FUNCTION_PA19 12u // PA_19 -#define PIN_FUNCTION_PA22 13u // PA_22 -#define PIN_FUNCTION_PA23 14u // PA_23 -#define PIN_FUNCTION_PA29 15u // PA_29 -#define PIN_FUNCTION_PA30 16u // PA_30 -#define PIN_FUNCTION_RTS0 13u // PA_22 -#define PIN_FUNCTION_RX0 11u // PA_18 -#define PIN_FUNCTION_RX2 15u // PA_29 -#define PIN_FUNCTION_SCK0 11u // PA_18 -#define PIN_FUNCTION_SCK1 11u // PA_18 -#define PIN_FUNCTION_TX0 14u // PA_23 -#define PIN_FUNCTION_TX2 16u // PA_30 diff --git a/boards/generic-rtl8710bn-2mb-788k.json b/boards/generic-rtl8710bn-2mb-788k.json index d9d9305..a4b8dcc 100644 --- a/boards/generic-rtl8710bn-2mb-788k.json +++ b/boards/generic-rtl8710bn-2mb-788k.json @@ -11,7 +11,7 @@ }, "name": "Generic - RTL8710BN (2M/788k)", "symbol": "RTL8710BN (2M/788k)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bn-2mb-788k/", + "url": "https://docs.libretiny.eu/boards/generic-rtl8710bn-2mb-788k/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-rtl8710bn-2mb-788k/README.md b/boards/generic-rtl8710bn-2mb-788k/README.md deleted file mode 100644 index d2d7c83..0000000 --- a/boards/generic-rtl8710bn-2mb-788k/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# Generic - RTL8710BN (2M/788k) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bn-2mb-788k/) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-rtl8710bn-2mb-788k` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 17x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n - -## Usage - -**Board code:** `generic-rtl8710bn-2mb-788k` - -In `platformio.ini`: - -```ini -[env:generic-rtl8710bn-2mb-788k] -platform = libretuya -board = generic-rtl8710bn-2mb-788k -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-rtl8710bn-2mb-788k - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA00 | | | | PWM2 | -D1 | PA05 | | | | PWM4 | -D2 | PA06 | | | FCS | | -D3 | PA07 | | | FD1 | | -D4 | PA08 | | | FD2 | | -D5 | PA09 | | | FD0 | | -D6 | PA10 | | | FSCK | | -D7 | PA11 | | | FD3 | | -D8 | PA12 | | | | PWM3 | -D9 | PA14 | | | | PWM0 | SWCLK -D10 | PA15 | | | | PWM1 | SWDIO -D11 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D12 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D13 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D14 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -D15 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D16 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/generic-rtl8710bn-2mb-788k/pins_arduino.h b/boards/generic-rtl8710bn-2mb-788k/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-rtl8710bn-2mb-788k/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-rtl8710bn-2mb-788k/variant.h b/boards/generic-rtl8710bn-2mb-788k/variant.h deleted file mode 100644 index cf285a0..0000000 --- a/boards/generic-rtl8710bn-2mb-788k/variant.h +++ /dev/null @@ -1,95 +0,0 @@ -/* This file was auto-generated from generic-rtl8710bn-2mb-788k.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 18 -#define NUM_DIGITAL_PINS 17 -#define NUM_ANALOG_INPUTS 2 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 12u // PA_19 -#define PIN_A1 17u // AD_2 -#define A0 PIN_A0 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 12u // PA_19 -#define PIN_SPI0_MISO 13u // PA_22 -#define PIN_SPI0_MOSI 14u // PA_23 -#define PIN_SPI0_SCK 11u // PA_18 -#define PIN_SPI1_CS 12u // PA_19 -#define PIN_SPI1_MISO 13u // PA_22 -#define PIN_SPI1_MOSI 14u // PA_23 -#define PIN_SPI1_SCK 11u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 13u // PA_22 -#define PIN_WIRE0_SCL_1 15u // PA_29 -#define PIN_WIRE0_SDA_0 12u // PA_19 -#define PIN_WIRE0_SDA_1 16u // PA_30 -#define PIN_WIRE1_SCL 11u // PA_18 -#define PIN_WIRE1_SDA 14u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 12u // PA_19 -#define PIN_SERIAL0_RTS 13u // PA_22 -#define PIN_SERIAL0_RX 11u // PA_18 -#define PIN_SERIAL0_TX 14u // PA_23 -#define PIN_SERIAL2_RX 15u // PA_29 -#define PIN_SERIAL2_TX 16u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 12u // PA_19 -#define PIN_FUNCTION_ADC2 17u // AD_2 -#define PIN_FUNCTION_CS0 12u // PA_19 -#define PIN_FUNCTION_CS1 12u // PA_19 -#define PIN_FUNCTION_CTS0 12u // PA_19 -#define PIN_FUNCTION_FCS 2u // PA_6 -#define PIN_FUNCTION_FD0 5u // PA_9 -#define PIN_FUNCTION_FD1 3u // PA_7 -#define PIN_FUNCTION_FD2 4u // PA_8 -#define PIN_FUNCTION_FD3 7u // PA_11 -#define PIN_FUNCTION_FSCK 6u // PA_10 -#define PIN_FUNCTION_MISO0 13u // PA_22 -#define PIN_FUNCTION_MISO1 13u // PA_22 -#define PIN_FUNCTION_MOSI0 14u // PA_23 -#define PIN_FUNCTION_MOSI1 14u // PA_23 -#define PIN_FUNCTION_PA00 0u // PA_0 -#define PIN_FUNCTION_PA05 1u // PA_5 -#define PIN_FUNCTION_PA06 2u // PA_6 -#define PIN_FUNCTION_PA07 3u // PA_7 -#define PIN_FUNCTION_PA08 4u // PA_8 -#define PIN_FUNCTION_PA09 5u // PA_9 -#define PIN_FUNCTION_PA10 6u // PA_10 -#define PIN_FUNCTION_PA11 7u // PA_11 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 9u // PA_14 -#define PIN_FUNCTION_PA15 10u // PA_15 -#define PIN_FUNCTION_PA18 11u // PA_18 -#define PIN_FUNCTION_PA19 12u // PA_19 -#define PIN_FUNCTION_PA22 13u // PA_22 -#define PIN_FUNCTION_PA23 14u // PA_23 -#define PIN_FUNCTION_PA29 15u // PA_29 -#define PIN_FUNCTION_PA30 16u // PA_30 -#define PIN_FUNCTION_RTS0 13u // PA_22 -#define PIN_FUNCTION_RX0 11u // PA_18 -#define PIN_FUNCTION_RX2 15u // PA_29 -#define PIN_FUNCTION_SCK0 11u // PA_18 -#define PIN_FUNCTION_SCK1 11u // PA_18 -#define PIN_FUNCTION_TX0 14u // PA_23 -#define PIN_FUNCTION_TX2 16u // PA_30 diff --git a/boards/generic-rtl8710bx-4mb-980k.json b/boards/generic-rtl8710bx-4mb-980k.json index 5f40241..4168c7e 100644 --- a/boards/generic-rtl8710bx-4mb-980k.json +++ b/boards/generic-rtl8710bx-4mb-980k.json @@ -12,13 +12,13 @@ }, "name": "Generic - RTL8710BX (4M/980k)", "symbol": "RTL8710BX (4M/980k)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bx-4mb-980k/", + "url": "https://docs.libretiny.eu/boards/generic-rtl8710bx-4mb-980k/", "vendor": "Generic", "doc": { "extra": [ "## Information", "This is a generic board definition for RTL8710BX with 4 MiB of flash. It has a bigger application partition size (980 KiB). The used bootloader is also different from the standard Tuya one.", - "It can be found in [Ezviz T31 smart plug](https://www.ezviz.com/product/T31/2021) - bare chip soldered onto the manufacturer-made PCB. The plug is not Tuya/SmartLife-compatible and has a 25Q32CSIG flash chip. Refer to [libretuya#23](https://github.com/kuba2k2/libretuya/issues/23) for photos and more information.", + "It can be found in [Ezviz T31 smart plug](https://www.ezviz.com/product/T31/2021) - bare chip soldered onto the manufacturer-made PCB. The plug is not Tuya/SmartLife-compatible and has a 25Q32CSIG flash chip. Refer to [libretiny#23](https://github.com/kuba2k2/libretiny/issues/23) for photos and more information.", "Note that stock firmware seems to use smaller app images (0x80000 / 512 KiB). After 0x180000 some product-test data and device logs can be found. Because the OTA2 offset is 0x100000, the board definition was configured to use all available space." ] }, diff --git a/boards/generic-rtl8710bx-4mb-980k/README.md b/boards/generic-rtl8710bx-4mb-980k/README.md deleted file mode 100644 index 403467d..0000000 --- a/boards/generic-rtl8710bx-4mb-980k/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# Generic - RTL8710BX (4M/980k) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-rtl8710bx-4mb-980k/) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|---------------------------------- -Board code | `generic-rtl8710bx-4mb-980k` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 4 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 17x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n - -## Usage - -**Board code:** `generic-rtl8710bx-4mb-980k` - -In `platformio.ini`: - -```ini -[env:generic-rtl8710bx-4mb-980k] -platform = libretuya -board = generic-rtl8710bx-4mb-980k -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-rtl8710bx-4mb-980k - framework: - version: dev -``` - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA00 | | | | PWM2 | -D1 | PA05 | | | | PWM4 | -D2 | PA06 | | | FCS | | -D3 | PA07 | | | FD1 | | -D4 | PA08 | | | FD2 | | -D5 | PA09 | | | FD0 | | -D6 | PA10 | | | FSCK | | -D7 | PA11 | | | FD3 | | -D8 | PA12 | | | | PWM3 | -D9 | PA14 | | | | PWM0 | SWCLK -D10 | PA15 | | | | PWM1 | SWDIO -D11 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D12 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D13 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D14 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -D15 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D16 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -A0 | PA19, ADC1 | | | | | - -## Flash memory map - -Flash size: 4 MiB / 4,194,304 B / 0x400000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 980 KiB / 0xF5000 | 0x100000 -OTA2 Image | 0x100000 | 980 KiB / 0xF5000 | 0x1F5000 -Key-Value Store | 0x1F5000 | 32 KiB / 0x8000 | 0x1FD000 -User Data | 0x1FD000 | 2 MiB / 0x202000 | 0x3FF000 -RDP | 0x3FF000 | 4 KiB / 0x1000 | 0x400000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. - -## Information - -This is a generic board definition for RTL8710BX with 4 MiB of flash. It has a bigger application partition size (980 KiB). The used bootloader is also different from the standard Tuya one. - -It can be found in [Ezviz T31 smart plug](https://www.ezviz.com/product/T31/2021) - bare chip soldered onto the manufacturer-made PCB. The plug is not Tuya/SmartLife-compatible and has a 25Q32CSIG flash chip. Refer to [libretuya#23](https://github.com/kuba2k2/libretuya/issues/23) for photos and more information. - -Note that stock firmware seems to use smaller app images (0x80000 / 512 KiB). After 0x180000 some product-test data and device logs can be found. Because the OTA2 offset is 0x100000, the board definition was configured to use all available space. diff --git a/boards/generic-rtl8710bx-4mb-980k/pins_arduino.h b/boards/generic-rtl8710bx-4mb-980k/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-rtl8710bx-4mb-980k/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-rtl8710bx-4mb-980k/variant.h b/boards/generic-rtl8710bx-4mb-980k/variant.h deleted file mode 100644 index dab27a9..0000000 --- a/boards/generic-rtl8710bx-4mb-980k/variant.h +++ /dev/null @@ -1,92 +0,0 @@ -/* This file was auto-generated from generic-rtl8710bx-4mb-980k.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 17 -#define NUM_DIGITAL_PINS 17 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 12u // PA_19 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 12u // PA_19 -#define PIN_SPI0_MISO 13u // PA_22 -#define PIN_SPI0_MOSI 14u // PA_23 -#define PIN_SPI0_SCK 11u // PA_18 -#define PIN_SPI1_CS 12u // PA_19 -#define PIN_SPI1_MISO 13u // PA_22 -#define PIN_SPI1_MOSI 14u // PA_23 -#define PIN_SPI1_SCK 11u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 13u // PA_22 -#define PIN_WIRE0_SCL_1 15u // PA_29 -#define PIN_WIRE0_SDA_0 12u // PA_19 -#define PIN_WIRE0_SDA_1 16u // PA_30 -#define PIN_WIRE1_SCL 11u // PA_18 -#define PIN_WIRE1_SDA 14u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 12u // PA_19 -#define PIN_SERIAL0_RTS 13u // PA_22 -#define PIN_SERIAL0_RX 11u // PA_18 -#define PIN_SERIAL0_TX 14u // PA_23 -#define PIN_SERIAL2_RX 15u // PA_29 -#define PIN_SERIAL2_TX 16u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 12u // PA_19 -#define PIN_FUNCTION_CS0 12u // PA_19 -#define PIN_FUNCTION_CS1 12u // PA_19 -#define PIN_FUNCTION_CTS0 12u // PA_19 -#define PIN_FUNCTION_FCS 2u // PA_6 -#define PIN_FUNCTION_FD0 5u // PA_9 -#define PIN_FUNCTION_FD1 3u // PA_7 -#define PIN_FUNCTION_FD2 4u // PA_8 -#define PIN_FUNCTION_FD3 7u // PA_11 -#define PIN_FUNCTION_FSCK 6u // PA_10 -#define PIN_FUNCTION_MISO0 13u // PA_22 -#define PIN_FUNCTION_MISO1 13u // PA_22 -#define PIN_FUNCTION_MOSI0 14u // PA_23 -#define PIN_FUNCTION_MOSI1 14u // PA_23 -#define PIN_FUNCTION_PA00 0u // PA_0 -#define PIN_FUNCTION_PA05 1u // PA_5 -#define PIN_FUNCTION_PA06 2u // PA_6 -#define PIN_FUNCTION_PA07 3u // PA_7 -#define PIN_FUNCTION_PA08 4u // PA_8 -#define PIN_FUNCTION_PA09 5u // PA_9 -#define PIN_FUNCTION_PA10 6u // PA_10 -#define PIN_FUNCTION_PA11 7u // PA_11 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 9u // PA_14 -#define PIN_FUNCTION_PA15 10u // PA_15 -#define PIN_FUNCTION_PA18 11u // PA_18 -#define PIN_FUNCTION_PA19 12u // PA_19 -#define PIN_FUNCTION_PA22 13u // PA_22 -#define PIN_FUNCTION_PA23 14u // PA_23 -#define PIN_FUNCTION_PA29 15u // PA_29 -#define PIN_FUNCTION_PA30 16u // PA_30 -#define PIN_FUNCTION_RTS0 13u // PA_22 -#define PIN_FUNCTION_RX0 11u // PA_18 -#define PIN_FUNCTION_RX2 15u // PA_29 -#define PIN_FUNCTION_SCK0 11u // PA_18 -#define PIN_FUNCTION_SCK1 11u // PA_18 -#define PIN_FUNCTION_TX0 14u // PA_23 -#define PIN_FUNCTION_TX2 16u // PA_30 diff --git a/boards/generic-rtl8720cf-2mb-992k.json b/boards/generic-rtl8720cf-2mb-992k.json index c1f79ef..c187d41 100644 --- a/boards/generic-rtl8720cf-2mb-992k.json +++ b/boards/generic-rtl8720cf-2mb-992k.json @@ -12,7 +12,7 @@ }, "name": "Generic - RTL8720CF (2M/992k)", "symbol": "RTL8720CF (2M/992k)", - "url": "https://kuba2k2.github.io/libretuya/boards/generic-rtl8720cf-2mb-992k/", + "url": "https://docs.libretiny.eu/boards/generic-rtl8720cf-2mb-992k/", "vendor": "Generic", "pcb": { "pinout": { diff --git a/boards/generic-rtl8720cf-2mb-992k/README.md b/boards/generic-rtl8720cf-2mb-992k/README.md deleted file mode 100644 index bab705c..0000000 --- a/boards/generic-rtl8720cf-2mb-992k/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Generic - RTL8720CF (2M/992k) - -*by Generic* - -[Product page](https://kuba2k2.github.io/libretuya/boards/generic-rtl8720cf-2mb-992k/) - -- [General info](../../docs/platform/realtek-amb/README.md) - -Parameter | Value --------------|----------------------------- -Board code | `generic-rtl8720cf-2mb-992k` -MCU | RTL8720CF -Manufacturer | Realtek -Series | AmebaZ2 -Frequency | 100 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 20x GPIO, 8x PWM, 3x UART -Wi-Fi | 802.11 b/g/n -BLE | v4.2 - -## Usage - -**Board code:** `generic-rtl8720cf-2mb-992k` - -In `platformio.ini`: - -```ini -[env:generic-rtl8720cf-2mb-992k] -platform = libretuya -board = generic-rtl8720cf-2mb-992k -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: generic-rtl8720cf-2mb-992k - framework: - version: dev -``` - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Partition Table | 0x000000 | 4 KiB / 0x1000 | 0x001000 -System Data | 0x001000 | 4 KiB / 0x1000 | 0x002000 -Calibration | 0x002000 | 4 KiB / 0x1000 | 0x003000 -(reserved) | 0x003000 | 4 KiB / 0x1000 | 0x004000 -Boot Image | 0x004000 | 32 KiB / 0x8000 | 0x00C000 -OTA1 Image | 0x00C000 | 992 KiB / 0xF8000 | 0x104000 -OTA2 Image | 0x104000 | 992 KiB / 0xF8000 | 0x1FC000 -Key-Value Store | 0x1FC000 | 8 KiB / 0x2000 | 0x1FE000 -User Data | 0x1FE000 | 8 KiB / 0x2000 | 0x200000 diff --git a/boards/generic-rtl8720cf-2mb-992k/pins_arduino.h b/boards/generic-rtl8720cf-2mb-992k/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/generic-rtl8720cf-2mb-992k/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/generic-rtl8720cf-2mb-992k/variant.h b/boards/generic-rtl8720cf-2mb-992k/variant.h deleted file mode 100644 index 9cd90ec..0000000 --- a/boards/generic-rtl8720cf-2mb-992k/variant.h +++ /dev/null @@ -1,7 +0,0 @@ -/* This file was auto-generated from generic-rtl8720cf-2mb-992k.json using boardgen */ - -#pragma once - -#include - -// clang-format off diff --git a/boards/lsc-lma35-t/README.md b/boards/lsc-lma35-t/README.md deleted file mode 100644 index df042fc..0000000 --- a/boards/lsc-lma35-t/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# LSC LMA35 BK7231T - -*by Unknown* - -[Product page](https://www.action.com/de-at/p/lsc-smart-connect-outdoor-led-streifen/) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|---------------------------------- -Board code | `lsc-lma35-t` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 15x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 - -## Usage - -**Board code:** `lsc-lma35-t` - -In `platformio.ini`: - -```ini -[env:lsc-lma35-t] -platform = libretuya -board = lsc-lma35-t -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: lsc-lma35-t - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_lsc-lma35-t.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P26 | | | | PWM5 | -D1 | P14 | | | SCK | | -D2 | P16 | | | MOSI | | -D3 | P24 | | | | PWM4 | -D4 | P22 | | | | | TDI -D5 | P0 | UART2_TX | I2C2_SCL | | | -D6 | P23 | | | | | TDO -D7 | P8 | | | | PWM2 | -D8 | P9 | | | | PWM3 | -D9 | P21 | | I2C1_SDA | | | TMS -D10 | P6 | | | | PWM0 | -D11 | P7 | | | | PWM1 | -D12 | P10 | UART1_RX | | | | -D13 | P11 | UART1_TX | | | | -D14 | P1 | UART2_RX | I2C2_SDA | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. - -## Information - -This board has no marking on the front side, only something that looks like PCB manufacturing info on the back; thus it was named based on these symbols. - -It can be found in 'LSC Smart Connect Outdoor LED Strip', and is likely custom-made for this product. - -The pinout was established by writing to and probing consecutive GPIOs, using the generic board definition. - -Pins marked with '?' are currently unknown, with a possibility of being CEN. Pin 22 (P1/D14) is also not confirmed. diff --git a/boards/lsc-lma35-t/pinout_lsc-lma35-t.svg b/boards/lsc-lma35-t/pinout_lsc-lma35-t.svg deleted file mode 100644 index 3d02d8c..0000000 --- a/boards/lsc-lma35-t/pinout_lsc-lma35-t.svg +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - P26 - - - - D0 - - - - IRDA - - - - PWM5 - - - - - P14 - - - - D1 - - - - - P16 - - - - D2 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - GND - - - - - P22 - - - - D4 - - - - - P0 - - - - D5 - - - - TX2 - - - - SCL2 - - - - - P23 - - - - ADC3 - - - - D6 - - - - A0 - - - - - ? - - - - - GND - - - - - P8 - - - - D7 - - - - PWM2 - - - - - P9 - - - - D8 - - - - PWM3 - - - - - GND - - - - - P21 - - - - D9 - - - - - P6 - - - - D10 - - - - PWM0 - - - - - P7 - - - - D11 - - - - PWM1 - - - - - P10 - - - - D12 - - - - RX1 - - - - - GND - - - - - P11 - - - - D13 - - - - TX1 - - - - - ? - - - - - P1 - - - - D14 - - - - RX2 - - - - SDA2 - diff --git a/boards/lsc-lma35-t/pins_arduino.h b/boards/lsc-lma35-t/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/lsc-lma35-t/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/lsc-lma35-t/variant.h b/boards/lsc-lma35-t/variant.h deleted file mode 100644 index 7fff860..0000000 --- a/boards/lsc-lma35-t/variant.h +++ /dev/null @@ -1,71 +0,0 @@ -/* This file was auto-generated from lsc-lma35-t.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 15 -#define NUM_DIGITAL_PINS 15 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 6u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE2_SCL 5u // GPIO0 -#define PIN_WIRE2_SDA 14u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 12u // GPIO10 -#define PIN_SERIAL1_TX 13u // GPIO11 -#define PIN_SERIAL2_RX 14u // GPIO1 -#define PIN_SERIAL2_TX 5u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 6u // GPIO23 -#define PIN_FUNCTION_MOSI 2u // GPIO16 -#define PIN_FUNCTION_P0 5u // GPIO0 -#define PIN_FUNCTION_P1 14u // GPIO1 -#define PIN_FUNCTION_P6 10u // GPIO6 -#define PIN_FUNCTION_P7 11u // GPIO7 -#define PIN_FUNCTION_P8 7u // GPIO8 -#define PIN_FUNCTION_P9 8u // GPIO9 -#define PIN_FUNCTION_P10 12u // GPIO10 -#define PIN_FUNCTION_P11 13u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P16 2u // GPIO16 -#define PIN_FUNCTION_P21 9u // GPIO21 -#define PIN_FUNCTION_P22 4u // GPIO22 -#define PIN_FUNCTION_P23 6u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 0u // GPIO26 -#define PIN_FUNCTION_PWM0 10u // GPIO6 -#define PIN_FUNCTION_PWM1 11u // GPIO7 -#define PIN_FUNCTION_PWM2 7u // GPIO8 -#define PIN_FUNCTION_PWM3 8u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 0u // GPIO26 -#define PIN_FUNCTION_RX1 12u // GPIO10 -#define PIN_FUNCTION_RX2 14u // GPIO1 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL2 5u // GPIO0 -#define PIN_FUNCTION_SDA1 9u // GPIO21 -#define PIN_FUNCTION_SDA2 14u // GPIO1 -#define PIN_FUNCTION_TX1 13u // GPIO11 -#define PIN_FUNCTION_TX2 5u // GPIO0 diff --git a/boards/lsc-lma35/README.md b/boards/lsc-lma35/README.md deleted file mode 100644 index 9065734..0000000 --- a/boards/lsc-lma35/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# LSC LMA35 - -*by Unknown* - -[Product page](https://www.action.com/de-at/p/lsc-smart-connect-outdoor-led-streifen/) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|---------------------------------- -Board code | `lsc-lma35` -MCU | BK7231N -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 15x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v5.1 - -## Usage - -**Board code:** `lsc-lma35` - -In `platformio.ini`: - -```ini -[env:lsc-lma35] -platform = libretuya -board = lsc-lma35 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: lsc-lma35 - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_lsc-lma35.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P26 | | | | PWM5 | -D1 | P14 | | | SCK | | -D2 | P16 | | | MOSI | | -D3 | P24 | | | | PWM4 | -D4 | P22 | | | | | TDI -D5 | P0 | UART2_TX | I2C2_SCL | | | -D6 | P23 | | | | | TDO -D7 | P8 | | | | PWM2 | -D8 | P9 | | | | PWM3 | -D9 | P21 | | I2C1_SDA | | | TMS -D10 | P6 | | | | PWM0 | -D11 | P7 | | | | PWM1 | -D12 | P10 | UART1_RX | | | | -D13 | P11 | UART1_TX | | | | -D14 | P1 | UART2_RX | I2C2_SDA | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x119000 | 0x12A000 -OTA Image | 0x12A000 | 664 KiB / 0xA6000 | 0x1D0000 -Calibration | 0x1D0000 | 4 KiB / 0x1000 | 0x1D1000 -Network Data | 0x1D1000 | 4 KiB / 0x1000 | 0x1D2000 -TLV Store | 0x1D2000 | 4 KiB / 0x1000 | 0x1D3000 -Key-Value Store | 0x1D3000 | 32 KiB / 0x8000 | 0x1DB000 -User Data | 0x1DB000 | 148 KiB / 0x25000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. - -## Information - -This board has no marking on the front side, only something that looks like PCB manufacturing info on the back; thus it was named based on these symbols. - -It can be found in 'LSC Smart Connect Outdoor LED Strip', and is likely custom-made for this product. - -The pinout was established by writing to and probing consecutive GPIOs, using the generic board definition. - -Pins marked with '?' are currently unknown, with a possibility of being CEN. Pin 22 (P1/D14) is also not confirmed. diff --git a/boards/lsc-lma35/pinout_lsc-lma35.svg b/boards/lsc-lma35/pinout_lsc-lma35.svg deleted file mode 100644 index 3d02d8c..0000000 --- a/boards/lsc-lma35/pinout_lsc-lma35.svg +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - P26 - - - - D0 - - - - IRDA - - - - PWM5 - - - - - P14 - - - - D1 - - - - - P16 - - - - D2 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - GND - - - - - P22 - - - - D4 - - - - - P0 - - - - D5 - - - - TX2 - - - - SCL2 - - - - - P23 - - - - ADC3 - - - - D6 - - - - A0 - - - - - ? - - - - - GND - - - - - P8 - - - - D7 - - - - PWM2 - - - - - P9 - - - - D8 - - - - PWM3 - - - - - GND - - - - - P21 - - - - D9 - - - - - P6 - - - - D10 - - - - PWM0 - - - - - P7 - - - - D11 - - - - PWM1 - - - - - P10 - - - - D12 - - - - RX1 - - - - - GND - - - - - P11 - - - - D13 - - - - TX1 - - - - - ? - - - - - P1 - - - - D14 - - - - RX2 - - - - SDA2 - diff --git a/boards/lsc-lma35/pins_arduino.h b/boards/lsc-lma35/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/lsc-lma35/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/lsc-lma35/variant.h b/boards/lsc-lma35/variant.h deleted file mode 100644 index 0fb2fa1..0000000 --- a/boards/lsc-lma35/variant.h +++ /dev/null @@ -1,71 +0,0 @@ -/* This file was auto-generated from lsc-lma35.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 15 -#define NUM_DIGITAL_PINS 15 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 6u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE2_SCL 5u // GPIO0 -#define PIN_WIRE2_SDA 14u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 12u // GPIO10 -#define PIN_SERIAL1_TX 13u // GPIO11 -#define PIN_SERIAL2_RX 14u // GPIO1 -#define PIN_SERIAL2_TX 5u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 6u // GPIO23 -#define PIN_FUNCTION_MOSI 2u // GPIO16 -#define PIN_FUNCTION_P0 5u // GPIO0 -#define PIN_FUNCTION_P1 14u // GPIO1 -#define PIN_FUNCTION_P6 10u // GPIO6 -#define PIN_FUNCTION_P7 11u // GPIO7 -#define PIN_FUNCTION_P8 7u // GPIO8 -#define PIN_FUNCTION_P9 8u // GPIO9 -#define PIN_FUNCTION_P10 12u // GPIO10 -#define PIN_FUNCTION_P11 13u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P16 2u // GPIO16 -#define PIN_FUNCTION_P21 9u // GPIO21 -#define PIN_FUNCTION_P22 4u // GPIO22 -#define PIN_FUNCTION_P23 6u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 0u // GPIO26 -#define PIN_FUNCTION_PWM0 10u // GPIO6 -#define PIN_FUNCTION_PWM1 11u // GPIO7 -#define PIN_FUNCTION_PWM2 7u // GPIO8 -#define PIN_FUNCTION_PWM3 8u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 0u // GPIO26 -#define PIN_FUNCTION_RX1 12u // GPIO10 -#define PIN_FUNCTION_RX2 14u // GPIO1 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL2 5u // GPIO0 -#define PIN_FUNCTION_SDA1 9u // GPIO21 -#define PIN_FUNCTION_SDA2 14u // GPIO1 -#define PIN_FUNCTION_TX1 13u // GPIO11 -#define PIN_FUNCTION_TX2 5u // GPIO0 diff --git a/boards/bw12/variant.cpp b/boards/variants/bw12.c similarity index 69% rename from boards/bw12/variant.cpp rename to boards/variants/bw12.c index 035bb33..8b631e6 100644 --- a/boards/bw12/variant.cpp +++ b/boards/variants/bw12.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA05, PWM4, WAKE1 {PA_5, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA29, UART2_RX, I2C0_SCL, PWM4 @@ -29,6 +31,18 @@ PinInfo pinTable[PINS_COUNT] = { // D10: PA23, UART0_TX, SPI0_MOSI, SPI1_MOSI, I2C1_SDA, SD_D1, PWM0, WAKE3 {PA_23, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[2]), // PA_0 (D2) + [5] = &(lt_arduino_pin_info_list[0]), // PA_5 (D0) + [12] = &(lt_arduino_pin_info_list[7]), // PA_12 (D7) + [14] = &(lt_arduino_pin_info_list[6]), // PA_14 (D6) + [15] = &(lt_arduino_pin_info_list[8]), // PA_15 (D8) + [18] = &(lt_arduino_pin_info_list[9]), // PA_18 (D9) + [19] = &(lt_arduino_pin_info_list[3]), // PA_19 (D3) + [22] = &(lt_arduino_pin_info_list[4]), // PA_22 (D4) + [23] = &(lt_arduino_pin_info_list[10]), // PA_23 (D10) + [29] = &(lt_arduino_pin_info_list[1]), // PA_29 (D1) + [30] = &(lt_arduino_pin_info_list[5]), // PA_30 (D5) +}; +// clang-format on diff --git a/boards/variants/bw12.h b/boards/variants/bw12.h new file mode 100644 index 0000000..130f383 --- /dev/null +++ b/boards/variants/bw12.h @@ -0,0 +1,123 @@ +/* This file was auto-generated from bw12.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 11 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 30 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 29u // PA_29 +#define PIN_WIRE0_SCL_1 22u // PA_22 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 30u // PA_30 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 22u // PA_22 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 5u // PA_5 +#define PIN_D1 29u // PA_29 +#define PIN_D2 0u // PA_0 +#define PIN_D3 19u // PA_19 +#define PIN_D4 22u // PA_22 +#define PIN_D5 30u // PA_30 +#define PIN_D6 14u // PA_14 +#define PIN_D7 12u // PA_12 +#define PIN_D8 15u // PA_15 +#define PIN_D9 18u // PA_18 +#define PIN_D10 23u // PA_23 +#define PIN_A0 19u // PA_19 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/variants/bw15.c b/boards/variants/bw15.c new file mode 100644 index 0000000..a769d26 --- /dev/null +++ b/boards/variants/bw15.c @@ -0,0 +1,54 @@ +/* This file was auto-generated from bw15.json using boardgen */ + +#include + +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif + +// clang-format off +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { + // D0: PA17, SD_CMD, PWM5 + {PIN_A17, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, + // D1: PA18, SD_CLK, PWM6 + {PIN_A18, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, + // D2: PA02, TDO, UART1_RX, SPI0_CS, I2C0_SCL, PWM2 + {PIN_A2, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D3: PA15, SD_D2, SPI0_CS, UART2_RX, I2C0_SCL, PWM3 + {PIN_A15, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D4: PA04, tRST, UART1_CTS, SPI0_MOSI, PWM4 + {PIN_A4, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D5: PA19, SD_D0, SPI0_MOSI, UART2_CTS, I2C0_SCL, PWM7 + {PIN_A19, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D6: PA20, SD_D1, SPI0_MISO, UART2_RTS, I2C0_SDA, PWM0 + {PIN_A20, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D7: PA16, SD_D3, SPI0_SCK, UART2_TX, I2C0_SDA, PWM4 + {PIN_A16, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D8: PA00, TCK, UART1_RX, PWM0, SWCLK + {PIN_A0, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SWD | PIN_UART, PIN_NONE, 0}, + // D9: PA03, TDI, UART1_TX, SPI0_SCK, I2C0_SDA, PWM3 + {PIN_A3, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D10: PA01, TMS, UART1_TX, PWM1, SWDIO + {PIN_A1, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SWD | PIN_UART, PIN_NONE, 0}, + // D11: PA13, UART0_RX, PWM7 + {PIN_A13, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_UART, PIN_NONE, 0}, + // D12: PA14, SD_INT, UART0_TX, PWM2 + {PIN_A14, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_UART, PIN_NONE, 0}, +}; + +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[8]), // PIN_A0 (D8) + [1] = &(lt_arduino_pin_info_list[10]), // PIN_A1 (D10) + [2] = &(lt_arduino_pin_info_list[2]), // PIN_A2 (D2) + [3] = &(lt_arduino_pin_info_list[9]), // PIN_A3 (D9) + [4] = &(lt_arduino_pin_info_list[4]), // PIN_A4 (D4) + [13] = &(lt_arduino_pin_info_list[11]), // PIN_A13 (D11) + [14] = &(lt_arduino_pin_info_list[12]), // PIN_A14 (D12) + [15] = &(lt_arduino_pin_info_list[3]), // PIN_A15 (D3) + [16] = &(lt_arduino_pin_info_list[7]), // PIN_A16 (D7) + [17] = &(lt_arduino_pin_info_list[0]), // PIN_A17 (D0) + [18] = &(lt_arduino_pin_info_list[1]), // PIN_A18 (D1) + [19] = &(lt_arduino_pin_info_list[5]), // PIN_A19 (D5) + [20] = &(lt_arduino_pin_info_list[6]), // PIN_A20 (D6) +}; +// clang-format on diff --git a/boards/variants/bw15.h b/boards/variants/bw15.h new file mode 100644 index 0000000..eb1f647 --- /dev/null +++ b/boards/variants/bw15.h @@ -0,0 +1,128 @@ +/* This file was auto-generated from bw15.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 13 // Total GPIO count +#define NUM_DIGITAL_PINS 13 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 0 // ADC inputs +#define NUM_ANALOG_OUTPUTS 13 // PWM & DAC outputs +#define PINS_GPIO_MAX 20 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS_0 2u // PIN_A2 +#define PIN_SPI0_CS_1 15u // PIN_A15 +#define PIN_SPI0_MISO 20u // PIN_A20 +#define PIN_SPI0_MOSI_0 4u // PIN_A4 +#define PIN_SPI0_MOSI_1 19u // PIN_A19 +#define PIN_SPI0_SCK_0 16u // PIN_A16 +#define PIN_SPI0_SCK_1 3u // PIN_A3 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 2u // PIN_A2 +#define PIN_WIRE0_SCL_1 15u // PIN_A15 +#define PIN_WIRE0_SCL_2 19u // PIN_A19 +#define PIN_WIRE0_SDA_0 20u // PIN_A20 +#define PIN_WIRE0_SDA_1 16u // PIN_A16 +#define PIN_WIRE0_SDA_2 3u // PIN_A3 + +// Serial ports +// ------------ +#define PIN_SERIAL0_RX 13u // PIN_A13 +#define PIN_SERIAL0_TX 14u // PIN_A14 +#define PIN_SERIAL1_CTS 4u // PIN_A4 +#define PIN_SERIAL1_RX_0 2u // PIN_A2 +#define PIN_SERIAL1_RX_1 0u // PIN_A0 +#define PIN_SERIAL1_TX_0 3u // PIN_A3 +#define PIN_SERIAL1_TX_1 1u // PIN_A1 +#define PIN_SERIAL2_CTS 19u // PIN_A19 +#define PIN_SERIAL2_RTS 20u // PIN_A20 +#define PIN_SERIAL2_RX 15u // PIN_A15 +#define PIN_SERIAL2_TX 16u // PIN_A16 + +// Pin function macros +// ------------------- +#define PIN_CS0 15u // PIN_A15 +#define PIN_CTS1 4u // PIN_A4 +#define PIN_CTS2 19u // PIN_A19 +#define PIN_MISO0 20u // PIN_A20 +#define PIN_MOSI0 19u // PIN_A19 +#define PIN_PA00 0u // PIN_A0 +#define PIN_PA01 1u // PIN_A1 +#define PIN_PA02 2u // PIN_A2 +#define PIN_PA03 3u // PIN_A3 +#define PIN_PA04 4u // PIN_A4 +#define PIN_PA13 13u // PIN_A13 +#define PIN_PA14 14u // PIN_A14 +#define PIN_PA15 15u // PIN_A15 +#define PIN_PA16 16u // PIN_A16 +#define PIN_PA17 17u // PIN_A17 +#define PIN_PA18 18u // PIN_A18 +#define PIN_PA19 19u // PIN_A19 +#define PIN_PA20 20u // PIN_A20 +#define PIN_PWM0 0u // PIN_A0 +#define PIN_PWM1 1u // PIN_A1 +#define PIN_PWM2 14u // PIN_A14 +#define PIN_PWM3 3u // PIN_A3 +#define PIN_PWM4 16u // PIN_A16 +#define PIN_PWM5 17u // PIN_A17 +#define PIN_PWM6 18u // PIN_A18 +#define PIN_PWM7 13u // PIN_A13 +#define PIN_RTS2 20u // PIN_A20 +#define PIN_RX0 13u // PIN_A13 +#define PIN_RX1 0u // PIN_A0 +#define PIN_RX2 15u // PIN_A15 +#define PIN_SCK0 3u // PIN_A3 +#define PIN_SCL0 19u // PIN_A19 +#define PIN_SDA0 3u // PIN_A3 +#define PIN_TX0 14u // PIN_A14 +#define PIN_TX1 1u // PIN_A1 +#define PIN_TX2 16u // PIN_A16 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_WIRE0 1 +#define SERIAL_INTERFACES_COUNT 3 +#define SPI_INTERFACES_COUNT 1 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 17u // PIN_A17 +#define PIN_D1 18u // PIN_A18 +#define PIN_D2 2u // PIN_A2 +#define PIN_D3 15u // PIN_A15 +#define PIN_D4 4u // PIN_A4 +#define PIN_D5 19u // PIN_A19 +#define PIN_D6 20u // PIN_A20 +#define PIN_D7 16u // PIN_A16 +#define PIN_D8 0u // PIN_A0 +#define PIN_D9 3u // PIN_A3 +#define PIN_D10 1u // PIN_A1 +#define PIN_D11 13u // PIN_A13 +#define PIN_D12 14u // PIN_A14 + +// Static pin names +// ---------------- +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; diff --git a/boards/cb2l/variant.cpp b/boards/variants/cb2l.c similarity index 61% rename from boards/cb2l/variant.cpp rename to boards/variants/cb2l.c index d67162b..a613471 100644 --- a/boards/cb2l/variant.cpp +++ b/boards/variants/cb2l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P8, PWM2 {GPIO8, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P7, PWM1 @@ -25,6 +27,16 @@ PinInfo pinTable[PINS_COUNT] = { // D8: P21, I2C1_SDA, TMS, MCLK, ^FCS {GPIO21, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_I2S | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [6] = &(lt_arduino_pin_info_list[2]), // GPIO6 (D2) + [7] = &(lt_arduino_pin_info_list[1]), // GPIO7 (D1) + [8] = &(lt_arduino_pin_info_list[0]), // GPIO8 (D0) + [10] = &(lt_arduino_pin_info_list[5]), // GPIO10 (D5) + [11] = &(lt_arduino_pin_info_list[7]), // GPIO11 (D7) + [21] = &(lt_arduino_pin_info_list[8]), // GPIO21 (D8) + [24] = &(lt_arduino_pin_info_list[4]), // GPIO24 (D4) + [26] = &(lt_arduino_pin_info_list[3]), // GPIO26 (D3) +}; +// clang-format on diff --git a/boards/variants/cb2l.h b/boards/variants/cb2l.h new file mode 100644 index 0000000..ccbc8d1 --- /dev/null +++ b/boards/variants/cb2l.h @@ -0,0 +1,71 @@ +/* This file was auto-generated from cb2l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 9 // Total GPIO count +#define NUM_DIGITAL_PINS 9 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 0 // ADC inputs +#define NUM_ANALOG_OUTPUTS 5 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_P0 0u // GPIO0 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P21 21u // GPIO21 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define SERIAL_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 8u // GPIO8 +#define PIN_D1 7u // GPIO7 +#define PIN_D2 6u // GPIO6 +#define PIN_D3 26u // GPIO26 +#define PIN_D4 24u // GPIO24 +#define PIN_D5 10u // GPIO10 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 11u // GPIO11 +#define PIN_D8 21u // GPIO21 + +// Static pin names +// ---------------- +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; diff --git a/boards/cb2s/variant.cpp b/boards/variants/cb2s.c similarity index 61% rename from boards/cb2s/variant.cpp rename to boards/variants/cb2s.c index 505e4e1..8ab2a42 100644 --- a/boards/cb2s/variant.cpp +++ b/boards/variants/cb2s.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P6, PWM0 {GPIO6, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P7, PWM1 @@ -29,6 +31,18 @@ PinInfo pinTable[PINS_COUNT] = { // D10: P21, I2C1_SDA, TMS, MCLK, ^FCS {GPIO21, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_I2S | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[8]), // GPIO0 (D8) + [1] = &(lt_arduino_pin_info_list[9]), // GPIO1 (D9) + [6] = &(lt_arduino_pin_info_list[0]), // GPIO6 (D0) + [7] = &(lt_arduino_pin_info_list[1]), // GPIO7 (D1) + [8] = &(lt_arduino_pin_info_list[2]), // GPIO8 (D2) + [10] = &(lt_arduino_pin_info_list[4]), // GPIO10 (D4) + [11] = &(lt_arduino_pin_info_list[5]), // GPIO11 (D5) + [21] = &(lt_arduino_pin_info_list[10]), // GPIO21 (D10) + [23] = &(lt_arduino_pin_info_list[3]), // GPIO23 (D3) + [24] = &(lt_arduino_pin_info_list[6]), // GPIO24 (D6) + [26] = &(lt_arduino_pin_info_list[7]), // GPIO26 (D7) +}; +// clang-format on diff --git a/boards/variants/cb2s.h b/boards/variants/cb2s.h new file mode 100644 index 0000000..a90ec1c --- /dev/null +++ b/boards/variants/cb2s.h @@ -0,0 +1,90 @@ +/* This file was auto-generated from cb2s.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 11 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 5 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P21 21u // GPIO21 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 6u // GPIO6 +#define PIN_D1 7u // GPIO7 +#define PIN_D2 8u // GPIO8 +#define PIN_D3 23u // GPIO23 +#define PIN_D4 10u // GPIO10 +#define PIN_D5 11u // GPIO11 +#define PIN_D6 24u // GPIO24 +#define PIN_D7 26u // GPIO26 +#define PIN_D8 0u // GPIO0 +#define PIN_D9 1u // GPIO1 +#define PIN_D10 21u // GPIO21 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/cb3l/variant.cpp b/boards/variants/cb3l.c similarity index 61% rename from boards/cb3l/variant.cpp rename to boards/variants/cb3l.c index df4de7d..6d592ce 100644 --- a/boards/cb3l/variant.cpp +++ b/boards/variants/cb3l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P23, ADC3, TDO, FSO {GPIO23, PIN_GPIO | PIN_IRQ | PIN_ADC | PIN_JTAG, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -31,6 +33,19 @@ PinInfo pinTable[PINS_COUNT] = { // D11: P11, UART1_TX {GPIO11, PIN_GPIO | PIN_IRQ | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [6] = &(lt_arduino_pin_info_list[4]), // GPIO6 (D4) + [7] = &(lt_arduino_pin_info_list[9]), // GPIO7 (D9) + [8] = &(lt_arduino_pin_info_list[8]), // GPIO8 (D8) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[10]), // GPIO10 (D10) + [11] = &(lt_arduino_pin_info_list[11]), // GPIO11 (D11) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [21] = &(lt_arduino_pin_info_list[7]), // GPIO21 (D7) + [23] = &(lt_arduino_pin_info_list[0]), // GPIO23 (D0) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[2]), // GPIO26 (D2) +}; +// clang-format on diff --git a/boards/variants/cb3l.h b/boards/variants/cb3l.h new file mode 100644 index 0000000..cd31a53 --- /dev/null +++ b/boards/variants/cb3l.h @@ -0,0 +1,85 @@ +/* This file was auto-generated from cb3l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 12 // Total GPIO count +#define NUM_DIGITAL_PINS 12 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P21 21u // GPIO21 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define SERIAL_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 23u // GPIO23 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 26u // GPIO26 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 6u // GPIO6 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 21u // GPIO21 +#define PIN_D8 8u // GPIO8 +#define PIN_D9 7u // GPIO7 +#define PIN_D10 10u // GPIO10 +#define PIN_D11 11u // GPIO11 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; diff --git a/boards/cb3s/variant.cpp b/boards/variants/cb3s.c similarity index 61% rename from boards/cb3s/variant.cpp rename to boards/variants/cb3s.c index eb8b2d7..049d819 100644 --- a/boards/cb3s/variant.cpp +++ b/boards/variants/cb3s.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P23, ADC3, TDO, FSO {GPIO23, PIN_GPIO | PIN_IRQ | PIN_ADC | PIN_JTAG, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -35,6 +37,21 @@ PinInfo pinTable[PINS_COUNT] = { // D13: P20, I2C1_SCL, TCK, FSCK {GPIO20, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [6] = &(lt_arduino_pin_info_list[4]), // GPIO6 (D4) + [7] = &(lt_arduino_pin_info_list[9]), // GPIO7 (D9) + [8] = &(lt_arduino_pin_info_list[8]), // GPIO8 (D8) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[10]), // GPIO10 (D10) + [11] = &(lt_arduino_pin_info_list[11]), // GPIO11 (D11) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [20] = &(lt_arduino_pin_info_list[13]), // GPIO20 (D13) + [21] = &(lt_arduino_pin_info_list[7]), // GPIO21 (D7) + [22] = &(lt_arduino_pin_info_list[12]), // GPIO22 (D12) + [23] = &(lt_arduino_pin_info_list[0]), // GPIO23 (D0) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[2]), // GPIO26 (D2) +}; +// clang-format on diff --git a/boards/variants/cb3s.h b/boards/variants/cb3s.h new file mode 100644 index 0000000..711d8b1 --- /dev/null +++ b/boards/variants/cb3s.h @@ -0,0 +1,100 @@ +/* This file was auto-generated from cb3s.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 14 // Total GPIO count +#define NUM_DIGITAL_PINS 14 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA_0 21u // GPIO21 +#define PIN_WIRE1_SDA_1 21u // GPIO21 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 23u // GPIO23 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 26u // GPIO26 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 6u // GPIO6 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 21u // GPIO21 +#define PIN_D8 8u // GPIO8 +#define PIN_D9 7u // GPIO7 +#define PIN_D10 10u // GPIO10 +#define PIN_D11 11u // GPIO11 +#define PIN_D12 22u // GPIO22 +#define PIN_D13 20u // GPIO20 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; diff --git a/boards/cb3se/variant.cpp b/boards/variants/cb3se.c similarity index 59% rename from boards/cb3se/variant.cpp rename to boards/variants/cb3se.c index 55d77a9..7cd476d 100644 --- a/boards/cb3se/variant.cpp +++ b/boards/variants/cb3se.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P23, ADC3, TDO, FSO {GPIO23, PIN_GPIO | PIN_IRQ | PIN_ADC | PIN_JTAG, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -41,6 +43,24 @@ PinInfo pinTable[PINS_COUNT] = { // D16: P16, SD_D0, MOSI {GPIO16, PIN_GPIO | PIN_IRQ | PIN_SPI, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [1] = &(lt_arduino_pin_info_list[7]), // GPIO1 (D7) + [6] = &(lt_arduino_pin_info_list[4]), // GPIO6 (D4) + [7] = &(lt_arduino_pin_info_list[9]), // GPIO7 (D9) + [8] = &(lt_arduino_pin_info_list[8]), // GPIO8 (D8) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[10]), // GPIO10 (D10) + [11] = &(lt_arduino_pin_info_list[11]), // GPIO11 (D11) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [15] = &(lt_arduino_pin_info_list[12]), // GPIO15 (D12) + [16] = &(lt_arduino_pin_info_list[16]), // GPIO16 (D16) + [17] = &(lt_arduino_pin_info_list[15]), // GPIO17 (D15) + [20] = &(lt_arduino_pin_info_list[14]), // GPIO20 (D14) + [22] = &(lt_arduino_pin_info_list[13]), // GPIO22 (D13) + [23] = &(lt_arduino_pin_info_list[0]), // GPIO23 (D0) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[2]), // GPIO26 (D2) +}; +// clang-format on diff --git a/boards/variants/cb3se.h b/boards/variants/cb3se.h new file mode 100644 index 0000000..95d3f98 --- /dev/null +++ b/boards/variants/cb3se.h @@ -0,0 +1,113 @@ +/* This file was auto-generated from cb3se.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 17 // Total GPIO count +#define NUM_DIGITAL_PINS 17 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_CS 15u // GPIO15 +#define PIN_MISO 17u // GPIO17 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P15 15u // GPIO15 +#define PIN_P16 16u // GPIO16 +#define PIN_P17 17u // GPIO17 +#define PIN_P20 20u // GPIO20 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 23u // GPIO23 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 26u // GPIO26 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 6u // GPIO6 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 1u // GPIO1 +#define PIN_D8 8u // GPIO8 +#define PIN_D9 7u // GPIO7 +#define PIN_D10 10u // GPIO10 +#define PIN_D11 11u // GPIO11 +#define PIN_D12 15u // GPIO15 +#define PIN_D13 22u // GPIO22 +#define PIN_D14 20u // GPIO20 +#define PIN_D15 17u // GPIO17 +#define PIN_D16 16u // GPIO16 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; diff --git a/boards/generic-bk7231n-qfn32-tuya/variant.cpp b/boards/variants/generic-bk7231n-qfn32-tuya.c similarity index 62% rename from boards/generic-bk7231n-qfn32-tuya/variant.cpp rename to boards/variants/generic-bk7231n-qfn32-tuya.c index fb33d95..64a732a 100644 --- a/boards/generic-bk7231n-qfn32-tuya/variant.cpp +++ b/boards/variants/generic-bk7231n-qfn32-tuya.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P0, UART2_TX, I2C2_SCL {GPIO0, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: P1, UART2_RX, I2C2_SDA @@ -45,6 +47,26 @@ PinInfo pinTable[PINS_COUNT] = { // D18: P28, DN {GPIO28, PIN_GPIO | PIN_IRQ, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // GPIO0 (D0) + [1] = &(lt_arduino_pin_info_list[1]), // GPIO1 (D1) + [6] = &(lt_arduino_pin_info_list[2]), // GPIO6 (D2) + [7] = &(lt_arduino_pin_info_list[3]), // GPIO7 (D3) + [8] = &(lt_arduino_pin_info_list[4]), // GPIO8 (D4) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[6]), // GPIO10 (D6) + [11] = &(lt_arduino_pin_info_list[7]), // GPIO11 (D7) + [14] = &(lt_arduino_pin_info_list[8]), // GPIO14 (D8) + [15] = &(lt_arduino_pin_info_list[9]), // GPIO15 (D9) + [16] = &(lt_arduino_pin_info_list[10]), // GPIO16 (D10) + [17] = &(lt_arduino_pin_info_list[11]), // GPIO17 (D11) + [20] = &(lt_arduino_pin_info_list[12]), // GPIO20 (D12) + [21] = &(lt_arduino_pin_info_list[13]), // GPIO21 (D13) + [22] = &(lt_arduino_pin_info_list[14]), // GPIO22 (D14) + [23] = &(lt_arduino_pin_info_list[15]), // GPIO23 (D15) + [24] = &(lt_arduino_pin_info_list[16]), // GPIO24 (D16) + [26] = &(lt_arduino_pin_info_list[17]), // GPIO26 (D17) + [28] = &(lt_arduino_pin_info_list[18]), // GPIO28 (D18) +}; +// clang-format on diff --git a/boards/variants/generic-bk7231n-qfn32-tuya.h b/boards/variants/generic-bk7231n-qfn32-tuya.h new file mode 100644 index 0000000..73d8a9c --- /dev/null +++ b/boards/variants/generic-bk7231n-qfn32-tuya.h @@ -0,0 +1,123 @@ +/* This file was auto-generated from generic-bk7231n-qfn32-tuya.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 19 // Total GPIO count +#define NUM_DIGITAL_PINS 19 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 28 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_CS 15u // GPIO15 +#define PIN_MISO 17u // GPIO17 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P15 15u // GPIO15 +#define PIN_P16 16u // GPIO16 +#define PIN_P17 17u // GPIO17 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_P28 28u // GPIO28 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // GPIO0 +#define PIN_D1 1u // GPIO1 +#define PIN_D2 6u // GPIO6 +#define PIN_D3 7u // GPIO7 +#define PIN_D4 8u // GPIO8 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 10u // GPIO10 +#define PIN_D7 11u // GPIO11 +#define PIN_D8 14u // GPIO14 +#define PIN_D9 15u // GPIO15 +#define PIN_D10 16u // GPIO16 +#define PIN_D11 17u // GPIO17 +#define PIN_D12 20u // GPIO20 +#define PIN_D13 21u // GPIO21 +#define PIN_D14 22u // GPIO22 +#define PIN_D15 23u // GPIO23 +#define PIN_D16 24u // GPIO24 +#define PIN_D17 26u // GPIO26 +#define PIN_D18 28u // GPIO28 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; +static const unsigned char D17 = PIN_D17; +static const unsigned char D18 = PIN_D18; diff --git a/boards/generic-bk7231t-qfn32-tuya/variant.cpp b/boards/variants/generic-bk7231t-qfn32-tuya.c similarity index 62% rename from boards/generic-bk7231t-qfn32-tuya/variant.cpp rename to boards/variants/generic-bk7231t-qfn32-tuya.c index c358dee..539e8ba 100644 --- a/boards/generic-bk7231t-qfn32-tuya/variant.cpp +++ b/boards/variants/generic-bk7231t-qfn32-tuya.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P0, UART2_TX, I2C2_SCL {GPIO0, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: P1, UART2_RX, I2C2_SDA @@ -45,6 +47,26 @@ PinInfo pinTable[PINS_COUNT] = { // D18: P28, DN {GPIO28, PIN_GPIO | PIN_IRQ, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // GPIO0 (D0) + [1] = &(lt_arduino_pin_info_list[1]), // GPIO1 (D1) + [6] = &(lt_arduino_pin_info_list[2]), // GPIO6 (D2) + [7] = &(lt_arduino_pin_info_list[3]), // GPIO7 (D3) + [8] = &(lt_arduino_pin_info_list[4]), // GPIO8 (D4) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[6]), // GPIO10 (D6) + [11] = &(lt_arduino_pin_info_list[7]), // GPIO11 (D7) + [14] = &(lt_arduino_pin_info_list[8]), // GPIO14 (D8) + [15] = &(lt_arduino_pin_info_list[9]), // GPIO15 (D9) + [16] = &(lt_arduino_pin_info_list[10]), // GPIO16 (D10) + [17] = &(lt_arduino_pin_info_list[11]), // GPIO17 (D11) + [20] = &(lt_arduino_pin_info_list[12]), // GPIO20 (D12) + [21] = &(lt_arduino_pin_info_list[13]), // GPIO21 (D13) + [22] = &(lt_arduino_pin_info_list[14]), // GPIO22 (D14) + [23] = &(lt_arduino_pin_info_list[15]), // GPIO23 (D15) + [24] = &(lt_arduino_pin_info_list[16]), // GPIO24 (D16) + [26] = &(lt_arduino_pin_info_list[17]), // GPIO26 (D17) + [28] = &(lt_arduino_pin_info_list[18]), // GPIO28 (D18) +}; +// clang-format on diff --git a/boards/variants/generic-bk7231t-qfn32-tuya.h b/boards/variants/generic-bk7231t-qfn32-tuya.h new file mode 100644 index 0000000..dd9b587 --- /dev/null +++ b/boards/variants/generic-bk7231t-qfn32-tuya.h @@ -0,0 +1,123 @@ +/* This file was auto-generated from generic-bk7231t-qfn32-tuya.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 19 // Total GPIO count +#define NUM_DIGITAL_PINS 19 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 28 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_CS 15u // GPIO15 +#define PIN_MISO 17u // GPIO17 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P15 15u // GPIO15 +#define PIN_P16 16u // GPIO16 +#define PIN_P17 17u // GPIO17 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_P28 28u // GPIO28 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // GPIO0 +#define PIN_D1 1u // GPIO1 +#define PIN_D2 6u // GPIO6 +#define PIN_D3 7u // GPIO7 +#define PIN_D4 8u // GPIO8 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 10u // GPIO10 +#define PIN_D7 11u // GPIO11 +#define PIN_D8 14u // GPIO14 +#define PIN_D9 15u // GPIO15 +#define PIN_D10 16u // GPIO16 +#define PIN_D11 17u // GPIO17 +#define PIN_D12 20u // GPIO20 +#define PIN_D13 21u // GPIO21 +#define PIN_D14 22u // GPIO22 +#define PIN_D15 23u // GPIO23 +#define PIN_D16 24u // GPIO24 +#define PIN_D17 26u // GPIO26 +#define PIN_D18 28u // GPIO28 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; +static const unsigned char D17 = PIN_D17; +static const unsigned char D18 = PIN_D18; diff --git a/boards/generic-bk7252/variant.cpp b/boards/variants/generic-bk7252.c similarity index 62% rename from boards/generic-bk7252/variant.cpp rename to boards/variants/generic-bk7252.c index 74c7841..b7287a6 100644 --- a/boards/generic-bk7252/variant.cpp +++ b/boards/variants/generic-bk7252.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P0, UART2_TX, I2C2_SCL {GPIO0, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: P1, UART2_RX, I2C2_SDA @@ -83,6 +85,45 @@ PinInfo pinTable[PINS_COUNT] = { // D37: P39, DVP_PD7 {GPIO39, PIN_GPIO | PIN_IRQ, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // GPIO0 (D0) + [1] = &(lt_arduino_pin_info_list[1]), // GPIO1 (D1) + [2] = &(lt_arduino_pin_info_list[2]), // GPIO2 (D2) + [3] = &(lt_arduino_pin_info_list[3]), // GPIO3 (D3) + [4] = &(lt_arduino_pin_info_list[4]), // GPIO4 (D4) + [5] = &(lt_arduino_pin_info_list[5]), // GPIO5 (D5) + [6] = &(lt_arduino_pin_info_list[6]), // GPIO6 (D6) + [7] = &(lt_arduino_pin_info_list[7]), // GPIO7 (D7) + [10] = &(lt_arduino_pin_info_list[8]), // GPIO10 (D8) + [11] = &(lt_arduino_pin_info_list[9]), // GPIO11 (D9) + [12] = &(lt_arduino_pin_info_list[10]), // GPIO12 (D10) + [13] = &(lt_arduino_pin_info_list[11]), // GPIO13 (D11) + [14] = &(lt_arduino_pin_info_list[12]), // GPIO14 (D12) + [15] = &(lt_arduino_pin_info_list[13]), // GPIO15 (D13) + [16] = &(lt_arduino_pin_info_list[14]), // GPIO16 (D14) + [17] = &(lt_arduino_pin_info_list[15]), // GPIO17 (D15) + [18] = &(lt_arduino_pin_info_list[16]), // GPIO18 (D16) + [19] = &(lt_arduino_pin_info_list[17]), // GPIO19 (D17) + [20] = &(lt_arduino_pin_info_list[18]), // GPIO20 (D18) + [21] = &(lt_arduino_pin_info_list[19]), // GPIO21 (D19) + [22] = &(lt_arduino_pin_info_list[20]), // GPIO22 (D20) + [23] = &(lt_arduino_pin_info_list[21]), // GPIO23 (D21) + [24] = &(lt_arduino_pin_info_list[22]), // GPIO24 (D22) + [25] = &(lt_arduino_pin_info_list[23]), // GPIO25 (D23) + [26] = &(lt_arduino_pin_info_list[24]), // GPIO26 (D24) + [27] = &(lt_arduino_pin_info_list[25]), // GPIO27 (D25) + [28] = &(lt_arduino_pin_info_list[26]), // GPIO28 (D26) + [29] = &(lt_arduino_pin_info_list[27]), // GPIO29 (D27) + [30] = &(lt_arduino_pin_info_list[28]), // GPIO30 (D28) + [31] = &(lt_arduino_pin_info_list[29]), // GPIO31 (D29) + [32] = &(lt_arduino_pin_info_list[30]), // GPIO32 (D30) + [33] = &(lt_arduino_pin_info_list[31]), // GPIO33 (D31) + [34] = &(lt_arduino_pin_info_list[32]), // GPIO34 (D32) + [35] = &(lt_arduino_pin_info_list[33]), // GPIO35 (D33) + [36] = &(lt_arduino_pin_info_list[34]), // GPIO36 (D34) + [37] = &(lt_arduino_pin_info_list[35]), // GPIO37 (D35) + [38] = &(lt_arduino_pin_info_list[36]), // GPIO38 (D36) + [39] = &(lt_arduino_pin_info_list[37]), // GPIO39 (D37) +}; +// clang-format on diff --git a/boards/variants/generic-bk7252.h b/boards/variants/generic-bk7252.h new file mode 100644 index 0000000..98a7ac7 --- /dev/null +++ b/boards/variants/generic-bk7252.h @@ -0,0 +1,200 @@ +/* This file was auto-generated from generic-bk7252.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 38 // Total GPIO count +#define NUM_DIGITAL_PINS 38 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 7 // ADC inputs +#define NUM_ANALOG_OUTPUTS 4 // PWM & DAC outputs +#define PINS_GPIO_MAX 39 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_CTS 12u // GPIO12 +#define PIN_SERIAL1_RTS 13u // GPIO13 +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC1 4u // GPIO4 +#define PIN_ADC2 5u // GPIO5 +#define PIN_ADC3 23u // GPIO23 +#define PIN_ADC4 2u // GPIO2 +#define PIN_ADC5 3u // GPIO3 +#define PIN_ADC6 12u // GPIO12 +#define PIN_ADC7 13u // GPIO13 +#define PIN_CS 15u // GPIO15 +#define PIN_CTS1 12u // GPIO12 +#define PIN_MISO 17u // GPIO17 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P2 2u // GPIO2 +#define PIN_P3 3u // GPIO3 +#define PIN_P4 4u // GPIO4 +#define PIN_P5 5u // GPIO5 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P12 12u // GPIO12 +#define PIN_P13 13u // GPIO13 +#define PIN_P14 14u // GPIO14 +#define PIN_P15 15u // GPIO15 +#define PIN_P16 16u // GPIO16 +#define PIN_P17 17u // GPIO17 +#define PIN_P18 18u // GPIO18 +#define PIN_P19 19u // GPIO19 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P25 25u // GPIO25 +#define PIN_P26 26u // GPIO26 +#define PIN_P27 27u // GPIO27 +#define PIN_P28 28u // GPIO28 +#define PIN_P29 29u // GPIO29 +#define PIN_P30 30u // GPIO30 +#define PIN_P31 31u // GPIO31 +#define PIN_P32 32u // GPIO32 +#define PIN_P33 33u // GPIO33 +#define PIN_P34 34u // GPIO34 +#define PIN_P35 35u // GPIO35 +#define PIN_P36 36u // GPIO36 +#define PIN_P37 37u // GPIO37 +#define PIN_P38 38u // GPIO38 +#define PIN_P39 39u // GPIO39 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RTS1 13u // GPIO13 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // GPIO0 +#define PIN_D1 1u // GPIO1 +#define PIN_D2 2u // GPIO2 +#define PIN_D3 3u // GPIO3 +#define PIN_D4 4u // GPIO4 +#define PIN_D5 5u // GPIO5 +#define PIN_D6 6u // GPIO6 +#define PIN_D7 7u // GPIO7 +#define PIN_D8 10u // GPIO10 +#define PIN_D9 11u // GPIO11 +#define PIN_D10 12u // GPIO12 +#define PIN_D11 13u // GPIO13 +#define PIN_D12 14u // GPIO14 +#define PIN_D13 15u // GPIO15 +#define PIN_D14 16u // GPIO16 +#define PIN_D15 17u // GPIO17 +#define PIN_D16 18u // GPIO18 +#define PIN_D17 19u // GPIO19 +#define PIN_D18 20u // GPIO20 +#define PIN_D19 21u // GPIO21 +#define PIN_D20 22u // GPIO22 +#define PIN_D21 23u // GPIO23 +#define PIN_D22 24u // GPIO24 +#define PIN_D23 25u // GPIO25 +#define PIN_D24 26u // GPIO26 +#define PIN_D25 27u // GPIO27 +#define PIN_D26 28u // GPIO28 +#define PIN_D27 29u // GPIO29 +#define PIN_D28 30u // GPIO30 +#define PIN_D29 31u // GPIO31 +#define PIN_D30 32u // GPIO32 +#define PIN_D31 33u // GPIO33 +#define PIN_D32 34u // GPIO34 +#define PIN_D33 35u // GPIO35 +#define PIN_D34 36u // GPIO36 +#define PIN_D35 37u // GPIO37 +#define PIN_D36 38u // GPIO38 +#define PIN_D37 39u // GPIO39 +#define PIN_A1 4u // GPIO4 +#define PIN_A2 5u // GPIO5 +#define PIN_A3 23u // GPIO23 +#define PIN_A4 3u // GPIO3 +#define PIN_A5 2u // GPIO2 +#define PIN_A6 12u // GPIO12 +#define PIN_A7 13u // GPIO13 + +// Static pin names +// ---------------- +static const unsigned char A1 = PIN_A1; +static const unsigned char A2 = PIN_A2; +static const unsigned char A3 = PIN_A3; +static const unsigned char A4 = PIN_A4; +static const unsigned char A5 = PIN_A5; +static const unsigned char A6 = PIN_A6; +static const unsigned char A7 = PIN_A7; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; +static const unsigned char D17 = PIN_D17; +static const unsigned char D18 = PIN_D18; +static const unsigned char D19 = PIN_D19; +static const unsigned char D20 = PIN_D20; +static const unsigned char D21 = PIN_D21; +static const unsigned char D22 = PIN_D22; +static const unsigned char D23 = PIN_D23; +static const unsigned char D24 = PIN_D24; +static const unsigned char D25 = PIN_D25; +static const unsigned char D26 = PIN_D26; +static const unsigned char D27 = PIN_D27; +static const unsigned char D28 = PIN_D28; +static const unsigned char D29 = PIN_D29; +static const unsigned char D30 = PIN_D30; +static const unsigned char D31 = PIN_D31; +static const unsigned char D32 = PIN_D32; +static const unsigned char D33 = PIN_D33; +static const unsigned char D34 = PIN_D34; +static const unsigned char D35 = PIN_D35; +static const unsigned char D36 = PIN_D36; +static const unsigned char D37 = PIN_D37; diff --git a/boards/generic-rtl8710bn-2mb-468k/variant.cpp b/boards/variants/generic-rtl8710bn-2mb-468k.c similarity index 69% rename from boards/generic-rtl8710bn-2mb-468k/variant.cpp rename to boards/variants/generic-rtl8710bn-2mb-468k.c index 227abbe..10a9b98 100644 --- a/boards/generic-rtl8710bn-2mb-468k/variant.cpp +++ b/boards/variants/generic-rtl8710bn-2mb-468k.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA00, PWM2 {PA_0, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA05, PWM4, WAKE1 @@ -43,6 +45,25 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // PA_0 (D0) + [5] = &(lt_arduino_pin_info_list[1]), // PA_5 (D1) + [6] = &(lt_arduino_pin_info_list[2]), // PA_6 (D2) + [7] = &(lt_arduino_pin_info_list[3]), // PA_7 (D3) + [8] = &(lt_arduino_pin_info_list[4]), // PA_8 (D4) + [9] = &(lt_arduino_pin_info_list[5]), // PA_9 (D5) + [10] = &(lt_arduino_pin_info_list[6]), // PA_10 (D6) + [11] = &(lt_arduino_pin_info_list[7]), // PA_11 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[9]), // PA_14 (D9) + [15] = &(lt_arduino_pin_info_list[10]), // PA_15 (D10) + [18] = &(lt_arduino_pin_info_list[11]), // PA_18 (D11) + [19] = &(lt_arduino_pin_info_list[12]), // PA_19 (D12) + [22] = &(lt_arduino_pin_info_list[13]), // PA_22 (D13) + [23] = &(lt_arduino_pin_info_list[14]), // PA_23 (D14) + [29] = &(lt_arduino_pin_info_list[15]), // PA_29 (D15) + [30] = &(lt_arduino_pin_info_list[16]), // PA_30 (D16) + [41] = &(lt_arduino_pin_info_list[17]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/generic-rtl8710bn-2mb-468k.h b/boards/variants/generic-rtl8710bn-2mb-468k.h new file mode 100644 index 0000000..e61f834 --- /dev/null +++ b/boards/variants/generic-rtl8710bn-2mb-468k.h @@ -0,0 +1,150 @@ +/* This file was auto-generated from generic-rtl8710bn-2mb-468k.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 18 // Total GPIO count +#define NUM_DIGITAL_PINS 17 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 22u // PA_22 +#define PIN_WIRE0_SCL_1 29u // PA_29 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_FCS 6u // PA_6 +#define PIN_FD0 9u // PA_9 +#define PIN_FD1 7u // PA_7 +#define PIN_FD2 8u // PA_8 +#define PIN_FD3 11u // PA_11 +#define PIN_FSCK 10u // PA_10 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA06 6u // PA_6 +#define PIN_PA07 7u // PA_7 +#define PIN_PA08 8u // PA_8 +#define PIN_PA09 9u // PA_9 +#define PIN_PA10 10u // PA_10 +#define PIN_PA11 11u // PA_11 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 30u // PA_30 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // PA_0 +#define PIN_D1 5u // PA_5 +#define PIN_D2 6u // PA_6 +#define PIN_D3 7u // PA_7 +#define PIN_D4 8u // PA_8 +#define PIN_D5 9u // PA_9 +#define PIN_D6 10u // PA_10 +#define PIN_D7 11u // PA_11 +#define PIN_D8 12u // PA_12 +#define PIN_D9 14u // PA_14 +#define PIN_D10 15u // PA_15 +#define PIN_D11 18u // PA_18 +#define PIN_D12 19u // PA_19 +#define PIN_D13 22u // PA_22 +#define PIN_D14 23u // PA_23 +#define PIN_D15 29u // PA_29 +#define PIN_D16 30u // PA_30 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; diff --git a/boards/generic-rtl8710bn-2mb-788k/variant.cpp b/boards/variants/generic-rtl8710bn-2mb-788k.c similarity index 69% rename from boards/generic-rtl8710bn-2mb-788k/variant.cpp rename to boards/variants/generic-rtl8710bn-2mb-788k.c index 41602e5..a19fd6c 100644 --- a/boards/generic-rtl8710bn-2mb-788k/variant.cpp +++ b/boards/variants/generic-rtl8710bn-2mb-788k.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA00, PWM2 {PA_0, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA05, PWM4, WAKE1 @@ -43,6 +45,25 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // PA_0 (D0) + [5] = &(lt_arduino_pin_info_list[1]), // PA_5 (D1) + [6] = &(lt_arduino_pin_info_list[2]), // PA_6 (D2) + [7] = &(lt_arduino_pin_info_list[3]), // PA_7 (D3) + [8] = &(lt_arduino_pin_info_list[4]), // PA_8 (D4) + [9] = &(lt_arduino_pin_info_list[5]), // PA_9 (D5) + [10] = &(lt_arduino_pin_info_list[6]), // PA_10 (D6) + [11] = &(lt_arduino_pin_info_list[7]), // PA_11 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[9]), // PA_14 (D9) + [15] = &(lt_arduino_pin_info_list[10]), // PA_15 (D10) + [18] = &(lt_arduino_pin_info_list[11]), // PA_18 (D11) + [19] = &(lt_arduino_pin_info_list[12]), // PA_19 (D12) + [22] = &(lt_arduino_pin_info_list[13]), // PA_22 (D13) + [23] = &(lt_arduino_pin_info_list[14]), // PA_23 (D14) + [29] = &(lt_arduino_pin_info_list[15]), // PA_29 (D15) + [30] = &(lt_arduino_pin_info_list[16]), // PA_30 (D16) + [41] = &(lt_arduino_pin_info_list[17]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/generic-rtl8710bn-2mb-788k.h b/boards/variants/generic-rtl8710bn-2mb-788k.h new file mode 100644 index 0000000..3174473 --- /dev/null +++ b/boards/variants/generic-rtl8710bn-2mb-788k.h @@ -0,0 +1,150 @@ +/* This file was auto-generated from generic-rtl8710bn-2mb-788k.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 18 // Total GPIO count +#define NUM_DIGITAL_PINS 17 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 22u // PA_22 +#define PIN_WIRE0_SCL_1 29u // PA_29 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_FCS 6u // PA_6 +#define PIN_FD0 9u // PA_9 +#define PIN_FD1 7u // PA_7 +#define PIN_FD2 8u // PA_8 +#define PIN_FD3 11u // PA_11 +#define PIN_FSCK 10u // PA_10 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA06 6u // PA_6 +#define PIN_PA07 7u // PA_7 +#define PIN_PA08 8u // PA_8 +#define PIN_PA09 9u // PA_9 +#define PIN_PA10 10u // PA_10 +#define PIN_PA11 11u // PA_11 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 30u // PA_30 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // PA_0 +#define PIN_D1 5u // PA_5 +#define PIN_D2 6u // PA_6 +#define PIN_D3 7u // PA_7 +#define PIN_D4 8u // PA_8 +#define PIN_D5 9u // PA_9 +#define PIN_D6 10u // PA_10 +#define PIN_D7 11u // PA_11 +#define PIN_D8 12u // PA_12 +#define PIN_D9 14u // PA_14 +#define PIN_D10 15u // PA_15 +#define PIN_D11 18u // PA_18 +#define PIN_D12 19u // PA_19 +#define PIN_D13 22u // PA_22 +#define PIN_D14 23u // PA_23 +#define PIN_D15 29u // PA_29 +#define PIN_D16 30u // PA_30 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; diff --git a/boards/generic-rtl8710bx-4mb-980k/variant.cpp b/boards/variants/generic-rtl8710bx-4mb-980k.c similarity index 69% rename from boards/generic-rtl8710bx-4mb-980k/variant.cpp rename to boards/variants/generic-rtl8710bx-4mb-980k.c index dc55d0a..b2f0fce 100644 --- a/boards/generic-rtl8710bx-4mb-980k/variant.cpp +++ b/boards/variants/generic-rtl8710bx-4mb-980k.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA00, PWM2 {PA_0, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA05, PWM4, WAKE1 @@ -41,6 +43,24 @@ PinInfo pinTable[PINS_COUNT] = { // D16: PA30, UART2_TX, I2C0_SDA, PWM4 {PA_30, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // PA_0 (D0) + [5] = &(lt_arduino_pin_info_list[1]), // PA_5 (D1) + [6] = &(lt_arduino_pin_info_list[2]), // PA_6 (D2) + [7] = &(lt_arduino_pin_info_list[3]), // PA_7 (D3) + [8] = &(lt_arduino_pin_info_list[4]), // PA_8 (D4) + [9] = &(lt_arduino_pin_info_list[5]), // PA_9 (D5) + [10] = &(lt_arduino_pin_info_list[6]), // PA_10 (D6) + [11] = &(lt_arduino_pin_info_list[7]), // PA_11 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[9]), // PA_14 (D9) + [15] = &(lt_arduino_pin_info_list[10]), // PA_15 (D10) + [18] = &(lt_arduino_pin_info_list[11]), // PA_18 (D11) + [19] = &(lt_arduino_pin_info_list[12]), // PA_19 (D12) + [22] = &(lt_arduino_pin_info_list[13]), // PA_22 (D13) + [23] = &(lt_arduino_pin_info_list[14]), // PA_23 (D14) + [29] = &(lt_arduino_pin_info_list[15]), // PA_29 (D15) + [30] = &(lt_arduino_pin_info_list[16]), // PA_30 (D16) +}; +// clang-format on diff --git a/boards/variants/generic-rtl8710bx-4mb-980k.h b/boards/variants/generic-rtl8710bx-4mb-980k.h new file mode 100644 index 0000000..272ffca --- /dev/null +++ b/boards/variants/generic-rtl8710bx-4mb-980k.h @@ -0,0 +1,147 @@ +/* This file was auto-generated from generic-rtl8710bx-4mb-980k.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 17 // Total GPIO count +#define NUM_DIGITAL_PINS 17 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 30 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 22u // PA_22 +#define PIN_WIRE0_SCL_1 29u // PA_29 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_FCS 6u // PA_6 +#define PIN_FD0 9u // PA_9 +#define PIN_FD1 7u // PA_7 +#define PIN_FD2 8u // PA_8 +#define PIN_FD3 11u // PA_11 +#define PIN_FSCK 10u // PA_10 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA06 6u // PA_6 +#define PIN_PA07 7u // PA_7 +#define PIN_PA08 8u // PA_8 +#define PIN_PA09 9u // PA_9 +#define PIN_PA10 10u // PA_10 +#define PIN_PA11 11u // PA_11 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 30u // PA_30 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // PA_0 +#define PIN_D1 5u // PA_5 +#define PIN_D2 6u // PA_6 +#define PIN_D3 7u // PA_7 +#define PIN_D4 8u // PA_8 +#define PIN_D5 9u // PA_9 +#define PIN_D6 10u // PA_10 +#define PIN_D7 11u // PA_11 +#define PIN_D8 12u // PA_12 +#define PIN_D9 14u // PA_14 +#define PIN_D10 15u // PA_15 +#define PIN_D11 18u // PA_18 +#define PIN_D12 19u // PA_19 +#define PIN_D13 22u // PA_22 +#define PIN_D14 23u // PA_23 +#define PIN_D15 29u // PA_29 +#define PIN_D16 30u // PA_30 +#define PIN_A0 19u // PA_19 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; diff --git a/boards/variants/generic-rtl8720cf-2mb-992k.c b/boards/variants/generic-rtl8720cf-2mb-992k.c new file mode 100644 index 0000000..26deb19 --- /dev/null +++ b/boards/variants/generic-rtl8720cf-2mb-992k.c @@ -0,0 +1,75 @@ +/* This file was auto-generated from generic-rtl8720cf-2mb-992k.json using boardgen */ + +#include + +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif + +// clang-format off +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { + // D0: PA00, TCK, UART1_RX, PWM0, SWCLK + {PIN_A0, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SWD | PIN_UART, PIN_NONE, 0}, + // D1: PA01, TMS, UART1_TX, PWM1, SWDIO + {PIN_A1, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SWD | PIN_UART, PIN_NONE, 0}, + // D2: PA02, TDO, UART1_RX, SPI0_CS, I2C0_SCL, PWM2 + {PIN_A2, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D3: PA03, TDI, UART1_TX, SPI0_SCK, I2C0_SDA, PWM3 + {PIN_A3, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D4: PA04, tRST, UART1_CTS, SPI0_MOSI, PWM4 + {PIN_A4, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_JTAG | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D5: PA07, ^FCS, SPI0_CS + {PIN_A7, PIN_GPIO | PIN_IRQ | PIN_SPI, PIN_NONE, 0}, + // D6: PA08, FSCK, SPI0_SCK + {PIN_A8, PIN_GPIO | PIN_IRQ | PIN_SPI, PIN_NONE, 0}, + // D7: PA09, FD2, SPI0_MOSI, UART0_RTS + {PIN_A9, PIN_GPIO | PIN_IRQ | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D8: PA10, FD1, SPI0_MISO, UART0_CTS + {PIN_A10, PIN_GPIO | PIN_IRQ | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D9: PA11, FD0, UART0_TX, I2C0_SCL, PWM0 + {PIN_A11, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, + // D10: PA12, FD3, UART0_RX, I2C0_SDA, PWM1 + {PIN_A12, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, + // D11: PA13, UART0_RX, PWM7 + {PIN_A13, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_UART, PIN_NONE, 0}, + // D12: PA14, SD_INT, UART0_TX, PWM2 + {PIN_A14, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_UART, PIN_NONE, 0}, + // D13: PA15, SD_D2, SPI0_CS, UART2_RX, I2C0_SCL, PWM3 + {PIN_A15, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D14: PA16, SD_D3, SPI0_SCK, UART2_TX, I2C0_SDA, PWM4 + {PIN_A16, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D15: PA17, SD_CMD, PWM5 + {PIN_A17, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, + // D16: PA18, SD_CLK, PWM6 + {PIN_A18, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, + // D17: PA19, SD_D0, SPI0_MOSI, UART2_CTS, I2C0_SCL, PWM7 + {PIN_A19, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D18: PA20, SD_D1, SPI0_MISO, UART2_RTS, I2C0_SDA, PWM0 + {PIN_A20, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_SPI | PIN_UART, PIN_NONE, 0}, + // D19: PA23, PWM7 + {PIN_A23, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, +}; + +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[0]), // PIN_A0 (D0) + [1] = &(lt_arduino_pin_info_list[1]), // PIN_A1 (D1) + [2] = &(lt_arduino_pin_info_list[2]), // PIN_A2 (D2) + [3] = &(lt_arduino_pin_info_list[3]), // PIN_A3 (D3) + [4] = &(lt_arduino_pin_info_list[4]), // PIN_A4 (D4) + [7] = &(lt_arduino_pin_info_list[5]), // PIN_A7 (D5) + [8] = &(lt_arduino_pin_info_list[6]), // PIN_A8 (D6) + [9] = &(lt_arduino_pin_info_list[7]), // PIN_A9 (D7) + [10] = &(lt_arduino_pin_info_list[8]), // PIN_A10 (D8) + [11] = &(lt_arduino_pin_info_list[9]), // PIN_A11 (D9) + [12] = &(lt_arduino_pin_info_list[10]), // PIN_A12 (D10) + [13] = &(lt_arduino_pin_info_list[11]), // PIN_A13 (D11) + [14] = &(lt_arduino_pin_info_list[12]), // PIN_A14 (D12) + [15] = &(lt_arduino_pin_info_list[13]), // PIN_A15 (D13) + [16] = &(lt_arduino_pin_info_list[14]), // PIN_A16 (D14) + [17] = &(lt_arduino_pin_info_list[15]), // PIN_A17 (D15) + [18] = &(lt_arduino_pin_info_list[16]), // PIN_A18 (D16) + [19] = &(lt_arduino_pin_info_list[17]), // PIN_A19 (D17) + [20] = &(lt_arduino_pin_info_list[18]), // PIN_A20 (D18) + [23] = &(lt_arduino_pin_info_list[19]), // PIN_A23 (D19) +}; +// clang-format on diff --git a/boards/variants/generic-rtl8720cf-2mb-992k.h b/boards/variants/generic-rtl8720cf-2mb-992k.h new file mode 100644 index 0000000..fddd627 --- /dev/null +++ b/boards/variants/generic-rtl8720cf-2mb-992k.h @@ -0,0 +1,161 @@ +/* This file was auto-generated from generic-rtl8720cf-2mb-992k.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 20 // Total GPIO count +#define NUM_DIGITAL_PINS 20 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 0 // ADC inputs +#define NUM_ANALOG_OUTPUTS 16 // PWM & DAC outputs +#define PINS_GPIO_MAX 23 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS_0 2u // PIN_A2 +#define PIN_SPI0_CS_1 7u // PIN_A7 +#define PIN_SPI0_CS_2 15u // PIN_A15 +#define PIN_SPI0_MISO_0 10u // PIN_A10 +#define PIN_SPI0_MISO_1 20u // PIN_A20 +#define PIN_SPI0_MOSI_0 4u // PIN_A4 +#define PIN_SPI0_MOSI_1 9u // PIN_A9 +#define PIN_SPI0_MOSI_2 19u // PIN_A19 +#define PIN_SPI0_SCK_0 3u // PIN_A3 +#define PIN_SPI0_SCK_1 8u // PIN_A8 +#define PIN_SPI0_SCK_2 16u // PIN_A16 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 2u // PIN_A2 +#define PIN_WIRE0_SCL_1 11u // PIN_A11 +#define PIN_WIRE0_SCL_2 15u // PIN_A15 +#define PIN_WIRE0_SCL_3 19u // PIN_A19 +#define PIN_WIRE0_SDA_0 3u // PIN_A3 +#define PIN_WIRE0_SDA_1 12u // PIN_A12 +#define PIN_WIRE0_SDA_2 16u // PIN_A16 +#define PIN_WIRE0_SDA_3 20u // PIN_A20 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 10u // PIN_A10 +#define PIN_SERIAL0_RTS 9u // PIN_A9 +#define PIN_SERIAL0_RX_0 12u // PIN_A12 +#define PIN_SERIAL0_RX_1 13u // PIN_A13 +#define PIN_SERIAL0_TX_0 11u // PIN_A11 +#define PIN_SERIAL0_TX_1 14u // PIN_A14 +#define PIN_SERIAL1_CTS 4u // PIN_A4 +#define PIN_SERIAL1_RX_0 0u // PIN_A0 +#define PIN_SERIAL1_RX_1 2u // PIN_A2 +#define PIN_SERIAL1_TX_0 1u // PIN_A1 +#define PIN_SERIAL1_TX_1 3u // PIN_A3 +#define PIN_SERIAL2_CTS 19u // PIN_A19 +#define PIN_SERIAL2_RTS 20u // PIN_A20 +#define PIN_SERIAL2_RX 15u // PIN_A15 +#define PIN_SERIAL2_TX 16u // PIN_A16 + +// Pin function macros +// ------------------- +#define PIN_CS0 15u // PIN_A15 +#define PIN_CTS0 10u // PIN_A10 +#define PIN_CTS1 4u // PIN_A4 +#define PIN_CTS2 19u // PIN_A19 +#define PIN_MISO0 20u // PIN_A20 +#define PIN_MOSI0 19u // PIN_A19 +#define PIN_PA00 0u // PIN_A0 +#define PIN_PA01 1u // PIN_A1 +#define PIN_PA02 2u // PIN_A2 +#define PIN_PA03 3u // PIN_A3 +#define PIN_PA04 4u // PIN_A4 +#define PIN_PA07 7u // PIN_A7 +#define PIN_PA08 8u // PIN_A8 +#define PIN_PA09 9u // PIN_A9 +#define PIN_PA10 10u // PIN_A10 +#define PIN_PA11 11u // PIN_A11 +#define PIN_PA12 12u // PIN_A12 +#define PIN_PA13 13u // PIN_A13 +#define PIN_PA14 14u // PIN_A14 +#define PIN_PA15 15u // PIN_A15 +#define PIN_PA16 16u // PIN_A16 +#define PIN_PA17 17u // PIN_A17 +#define PIN_PA18 18u // PIN_A18 +#define PIN_PA19 19u // PIN_A19 +#define PIN_PA20 20u // PIN_A20 +#define PIN_PA23 23u // PIN_A23 +#define PIN_PWM0 20u // PIN_A20 +#define PIN_PWM1 12u // PIN_A12 +#define PIN_PWM2 14u // PIN_A14 +#define PIN_PWM3 15u // PIN_A15 +#define PIN_PWM4 16u // PIN_A16 +#define PIN_PWM5 17u // PIN_A17 +#define PIN_PWM6 18u // PIN_A18 +#define PIN_PWM7 23u // PIN_A23 +#define PIN_RTS0 9u // PIN_A9 +#define PIN_RTS2 20u // PIN_A20 +#define PIN_RX0 13u // PIN_A13 +#define PIN_RX1 2u // PIN_A2 +#define PIN_RX2 15u // PIN_A15 +#define PIN_SCK0 16u // PIN_A16 +#define PIN_SCL0 19u // PIN_A19 +#define PIN_SDA0 20u // PIN_A20 +#define PIN_TX0 14u // PIN_A14 +#define PIN_TX1 3u // PIN_A3 +#define PIN_TX2 16u // PIN_A16 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_WIRE0 1 +#define SERIAL_INTERFACES_COUNT 3 +#define SPI_INTERFACES_COUNT 1 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 0u // PIN_A0 +#define PIN_D1 1u // PIN_A1 +#define PIN_D2 2u // PIN_A2 +#define PIN_D3 3u // PIN_A3 +#define PIN_D4 4u // PIN_A4 +#define PIN_D5 7u // PIN_A7 +#define PIN_D6 8u // PIN_A8 +#define PIN_D7 9u // PIN_A9 +#define PIN_D8 10u // PIN_A10 +#define PIN_D9 11u // PIN_A11 +#define PIN_D10 12u // PIN_A12 +#define PIN_D11 13u // PIN_A13 +#define PIN_D12 14u // PIN_A14 +#define PIN_D13 15u // PIN_A15 +#define PIN_D14 16u // PIN_A16 +#define PIN_D15 17u // PIN_A17 +#define PIN_D16 18u // PIN_A18 +#define PIN_D17 19u // PIN_A19 +#define PIN_D18 20u // PIN_A20 +#define PIN_D19 23u // PIN_A23 + +// Static pin names +// ---------------- +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; +static const unsigned char D16 = PIN_D16; +static const unsigned char D17 = PIN_D17; +static const unsigned char D18 = PIN_D18; +static const unsigned char D19 = PIN_D19; diff --git a/boards/lsc-lma35-t/variant.cpp b/boards/variants/lsc-lma35-t.c similarity index 62% rename from boards/lsc-lma35-t/variant.cpp rename to boards/variants/lsc-lma35-t.c index 19882ab..2ac070c 100644 --- a/boards/lsc-lma35-t/variant.cpp +++ b/boards/variants/lsc-lma35-t.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P26, PWM5, IRDA {GPIO26, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -37,6 +39,22 @@ PinInfo pinTable[PINS_COUNT] = { // D14: P1, UART2_RX, I2C2_SDA {GPIO1, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[5]), // GPIO0 (D5) + [1] = &(lt_arduino_pin_info_list[14]), // GPIO1 (D14) + [6] = &(lt_arduino_pin_info_list[10]), // GPIO6 (D10) + [7] = &(lt_arduino_pin_info_list[11]), // GPIO7 (D11) + [8] = &(lt_arduino_pin_info_list[7]), // GPIO8 (D7) + [9] = &(lt_arduino_pin_info_list[8]), // GPIO9 (D8) + [10] = &(lt_arduino_pin_info_list[12]), // GPIO10 (D12) + [11] = &(lt_arduino_pin_info_list[13]), // GPIO11 (D13) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [16] = &(lt_arduino_pin_info_list[2]), // GPIO16 (D2) + [21] = &(lt_arduino_pin_info_list[9]), // GPIO21 (D9) + [22] = &(lt_arduino_pin_info_list[4]), // GPIO22 (D4) + [23] = &(lt_arduino_pin_info_list[6]), // GPIO23 (D6) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[0]), // GPIO26 (D0) +}; +// clang-format on diff --git a/boards/variants/lsc-lma35-t.h b/boards/variants/lsc-lma35-t.h new file mode 100644 index 0000000..695df45 --- /dev/null +++ b/boards/variants/lsc-lma35-t.h @@ -0,0 +1,105 @@ +/* This file was auto-generated from lsc-lma35-t.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 15 // Total GPIO count +#define NUM_DIGITAL_PINS 15 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P16 16u // GPIO16 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 26u // GPIO26 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 16u // GPIO16 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 22u // GPIO22 +#define PIN_D5 0u // GPIO0 +#define PIN_D6 23u // GPIO23 +#define PIN_D7 8u // GPIO8 +#define PIN_D8 9u // GPIO9 +#define PIN_D9 21u // GPIO21 +#define PIN_D10 6u // GPIO6 +#define PIN_D11 7u // GPIO7 +#define PIN_D12 10u // GPIO10 +#define PIN_D13 11u // GPIO11 +#define PIN_D14 1u // GPIO1 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; diff --git a/boards/lsc-lma35/variant.cpp b/boards/variants/lsc-lma35.c similarity index 62% rename from boards/lsc-lma35/variant.cpp rename to boards/variants/lsc-lma35.c index e07b81f..c04545b 100644 --- a/boards/lsc-lma35/variant.cpp +++ b/boards/variants/lsc-lma35.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P26, PWM5, IRDA {GPIO26, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -37,6 +39,22 @@ PinInfo pinTable[PINS_COUNT] = { // D14: P1, UART2_RX, I2C2_SDA {GPIO1, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[5]), // GPIO0 (D5) + [1] = &(lt_arduino_pin_info_list[14]), // GPIO1 (D14) + [6] = &(lt_arduino_pin_info_list[10]), // GPIO6 (D10) + [7] = &(lt_arduino_pin_info_list[11]), // GPIO7 (D11) + [8] = &(lt_arduino_pin_info_list[7]), // GPIO8 (D7) + [9] = &(lt_arduino_pin_info_list[8]), // GPIO9 (D8) + [10] = &(lt_arduino_pin_info_list[12]), // GPIO10 (D12) + [11] = &(lt_arduino_pin_info_list[13]), // GPIO11 (D13) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [16] = &(lt_arduino_pin_info_list[2]), // GPIO16 (D2) + [21] = &(lt_arduino_pin_info_list[9]), // GPIO21 (D9) + [22] = &(lt_arduino_pin_info_list[4]), // GPIO22 (D4) + [23] = &(lt_arduino_pin_info_list[6]), // GPIO23 (D6) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[0]), // GPIO26 (D0) +}; +// clang-format on diff --git a/boards/variants/lsc-lma35.h b/boards/variants/lsc-lma35.h new file mode 100644 index 0000000..4a0d153 --- /dev/null +++ b/boards/variants/lsc-lma35.h @@ -0,0 +1,105 @@ +/* This file was auto-generated from lsc-lma35.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 15 // Total GPIO count +#define NUM_DIGITAL_PINS 15 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P16 16u // GPIO16 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 26u // GPIO26 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 16u // GPIO16 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 22u // GPIO22 +#define PIN_D5 0u // GPIO0 +#define PIN_D6 23u // GPIO23 +#define PIN_D7 8u // GPIO8 +#define PIN_D8 9u // GPIO9 +#define PIN_D9 21u // GPIO21 +#define PIN_D10 6u // GPIO6 +#define PIN_D11 7u // GPIO7 +#define PIN_D12 10u // GPIO10 +#define PIN_D13 11u // GPIO11 +#define PIN_D14 1u // GPIO1 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; diff --git a/boards/wb2l/variant.cpp b/boards/variants/wb2l.c similarity index 61% rename from boards/wb2l/variant.cpp rename to boards/variants/wb2l.c index 534343b..6501454 100644 --- a/boards/wb2l/variant.cpp +++ b/boards/variants/wb2l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P8, PWM2 {GPIO8, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P7, PWM1 @@ -33,6 +35,20 @@ PinInfo pinTable[PINS_COUNT] = { // D12: P22, TDI, FSI {GPIO22, PIN_GPIO | PIN_IRQ | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[8]), // GPIO0 (D8) + [1] = &(lt_arduino_pin_info_list[7]), // GPIO1 (D7) + [6] = &(lt_arduino_pin_info_list[2]), // GPIO6 (D2) + [7] = &(lt_arduino_pin_info_list[1]), // GPIO7 (D1) + [8] = &(lt_arduino_pin_info_list[0]), // GPIO8 (D0) + [10] = &(lt_arduino_pin_info_list[5]), // GPIO10 (D5) + [11] = &(lt_arduino_pin_info_list[6]), // GPIO11 (D6) + [20] = &(lt_arduino_pin_info_list[9]), // GPIO20 (D9) + [21] = &(lt_arduino_pin_info_list[10]), // GPIO21 (D10) + [22] = &(lt_arduino_pin_info_list[12]), // GPIO22 (D12) + [23] = &(lt_arduino_pin_info_list[11]), // GPIO23 (D11) + [24] = &(lt_arduino_pin_info_list[4]), // GPIO24 (D4) + [26] = &(lt_arduino_pin_info_list[3]), // GPIO26 (D3) +}; +// clang-format on diff --git a/boards/variants/wb2l.h b/boards/variants/wb2l.h new file mode 100644 index 0000000..55a5d1b --- /dev/null +++ b/boards/variants/wb2l.h @@ -0,0 +1,100 @@ +/* This file was auto-generated from wb2l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 13 // Total GPIO count +#define NUM_DIGITAL_PINS 13 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 5 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 8u // GPIO8 +#define PIN_D1 7u // GPIO7 +#define PIN_D2 6u // GPIO6 +#define PIN_D3 26u // GPIO26 +#define PIN_D4 24u // GPIO24 +#define PIN_D5 10u // GPIO10 +#define PIN_D6 11u // GPIO11 +#define PIN_D7 1u // GPIO1 +#define PIN_D8 0u // GPIO0 +#define PIN_D9 20u // GPIO20 +#define PIN_D10 21u // GPIO21 +#define PIN_D11 23u // GPIO23 +#define PIN_D12 22u // GPIO22 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; diff --git a/boards/wb2s/variant.cpp b/boards/variants/wb2s.c similarity index 62% rename from boards/wb2s/variant.cpp rename to boards/variants/wb2s.c index d0d6bc3..b08506c 100644 --- a/boards/wb2s/variant.cpp +++ b/boards/variants/wb2s.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P8, PWM2 {GPIO8, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: P7, PWM1 @@ -35,6 +37,21 @@ PinInfo pinTable[PINS_COUNT] = { // D13: P22, TDI, FSI {GPIO22, PIN_GPIO | PIN_IRQ | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[11]), // GPIO0 (D11) + [1] = &(lt_arduino_pin_info_list[10]), // GPIO1 (D10) + [6] = &(lt_arduino_pin_info_list[2]), // GPIO6 (D2) + [7] = &(lt_arduino_pin_info_list[1]), // GPIO7 (D1) + [8] = &(lt_arduino_pin_info_list[0]), // GPIO8 (D0) + [9] = &(lt_arduino_pin_info_list[9]), // GPIO9 (D9) + [10] = &(lt_arduino_pin_info_list[4]), // GPIO10 (D4) + [11] = &(lt_arduino_pin_info_list[5]), // GPIO11 (D5) + [20] = &(lt_arduino_pin_info_list[8]), // GPIO20 (D8) + [21] = &(lt_arduino_pin_info_list[12]), // GPIO21 (D12) + [22] = &(lt_arduino_pin_info_list[13]), // GPIO22 (D13) + [23] = &(lt_arduino_pin_info_list[3]), // GPIO23 (D3) + [24] = &(lt_arduino_pin_info_list[6]), // GPIO24 (D6) + [26] = &(lt_arduino_pin_info_list[7]), // GPIO26 (D7) +}; +// clang-format on diff --git a/boards/variants/wb2s.h b/boards/variants/wb2s.h new file mode 100644 index 0000000..b7b5102 --- /dev/null +++ b/boards/variants/wb2s.h @@ -0,0 +1,104 @@ +/* This file was auto-generated from wb2s.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 14 // Total GPIO count +#define NUM_DIGITAL_PINS 14 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 8u // GPIO8 +#define PIN_D1 7u // GPIO7 +#define PIN_D2 6u // GPIO6 +#define PIN_D3 23u // GPIO23 +#define PIN_D4 10u // GPIO10 +#define PIN_D5 11u // GPIO11 +#define PIN_D6 24u // GPIO24 +#define PIN_D7 26u // GPIO26 +#define PIN_D8 20u // GPIO20 +#define PIN_D9 9u // GPIO9 +#define PIN_D10 1u // GPIO1 +#define PIN_D11 0u // GPIO0 +#define PIN_D12 21u // GPIO21 +#define PIN_D13 22u // GPIO22 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; diff --git a/boards/wb3l/variant.cpp b/boards/variants/wb3l.c similarity index 62% rename from boards/wb3l/variant.cpp rename to boards/variants/wb3l.c index 41ddfce..aad420e 100644 --- a/boards/wb3l/variant.cpp +++ b/boards/variants/wb3l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P23, ADC3, TDO, FSO {GPIO23, PIN_GPIO | PIN_IRQ | PIN_ADC | PIN_JTAG, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -39,6 +41,23 @@ PinInfo pinTable[PINS_COUNT] = { // D15: P1, UART2_RX, I2C2_SDA {GPIO1, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_UART, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [1] = &(lt_arduino_pin_info_list[15]), // GPIO1 (D15) + [6] = &(lt_arduino_pin_info_list[4]), // GPIO6 (D4) + [7] = &(lt_arduino_pin_info_list[9]), // GPIO7 (D9) + [8] = &(lt_arduino_pin_info_list[8]), // GPIO8 (D8) + [9] = &(lt_arduino_pin_info_list[5]), // GPIO9 (D5) + [10] = &(lt_arduino_pin_info_list[10]), // GPIO10 (D10) + [11] = &(lt_arduino_pin_info_list[11]), // GPIO11 (D11) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [16] = &(lt_arduino_pin_info_list[7]), // GPIO16 (D7) + [20] = &(lt_arduino_pin_info_list[14]), // GPIO20 (D14) + [21] = &(lt_arduino_pin_info_list[13]), // GPIO21 (D13) + [22] = &(lt_arduino_pin_info_list[12]), // GPIO22 (D12) + [23] = &(lt_arduino_pin_info_list[0]), // GPIO23 (D0) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[2]), // GPIO26 (D2) +}; +// clang-format on diff --git a/boards/variants/wb3l.h b/boards/variants/wb3l.h new file mode 100644 index 0000000..77e07bc --- /dev/null +++ b/boards/variants/wb3l.h @@ -0,0 +1,112 @@ +/* This file was auto-generated from wb3l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 16 // Total GPIO count +#define NUM_DIGITAL_PINS 16 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_MOSI 16u // GPIO16 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P16 16u // GPIO16 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 23u // GPIO23 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 26u // GPIO26 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 6u // GPIO6 +#define PIN_D5 9u // GPIO9 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 16u // GPIO16 +#define PIN_D8 8u // GPIO8 +#define PIN_D9 7u // GPIO7 +#define PIN_D10 10u // GPIO10 +#define PIN_D11 11u // GPIO11 +#define PIN_D12 22u // GPIO22 +#define PIN_D13 21u // GPIO21 +#define PIN_D14 20u // GPIO20 +#define PIN_D15 1u // GPIO1 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; +static const unsigned char D15 = PIN_D15; diff --git a/boards/wb3s/variant.cpp b/boards/variants/wb3s.c similarity index 62% rename from boards/wb3s/variant.cpp rename to boards/variants/wb3s.c index 3b4e22b..9866697 100644 --- a/boards/wb3s/variant.cpp +++ b/boards/variants/wb3s.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: P23, ADC3, TDO, FSO {GPIO23, PIN_GPIO | PIN_IRQ | PIN_ADC | PIN_JTAG, PIN_NONE, 0}, // D1: P14, SD_CLK, SCK @@ -37,6 +39,22 @@ PinInfo pinTable[PINS_COUNT] = { // D14: P20, I2C1_SCL, TCK, FSCK {GPIO20, PIN_GPIO | PIN_IRQ | PIN_I2C | PIN_JTAG, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[6]), // GPIO0 (D6) + [1] = &(lt_arduino_pin_info_list[7]), // GPIO1 (D7) + [6] = &(lt_arduino_pin_info_list[4]), // GPIO6 (D4) + [7] = &(lt_arduino_pin_info_list[5]), // GPIO7 (D5) + [8] = &(lt_arduino_pin_info_list[9]), // GPIO8 (D9) + [9] = &(lt_arduino_pin_info_list[8]), // GPIO9 (D8) + [10] = &(lt_arduino_pin_info_list[10]), // GPIO10 (D10) + [11] = &(lt_arduino_pin_info_list[11]), // GPIO11 (D11) + [14] = &(lt_arduino_pin_info_list[1]), // GPIO14 (D1) + [20] = &(lt_arduino_pin_info_list[14]), // GPIO20 (D14) + [21] = &(lt_arduino_pin_info_list[13]), // GPIO21 (D13) + [22] = &(lt_arduino_pin_info_list[12]), // GPIO22 (D12) + [23] = &(lt_arduino_pin_info_list[0]), // GPIO23 (D0) + [24] = &(lt_arduino_pin_info_list[3]), // GPIO24 (D3) + [26] = &(lt_arduino_pin_info_list[2]), // GPIO26 (D2) +}; +// clang-format on diff --git a/boards/variants/wb3s.h b/boards/variants/wb3s.h new file mode 100644 index 0000000..f875fe8 --- /dev/null +++ b/boards/variants/wb3s.h @@ -0,0 +1,108 @@ +/* This file was auto-generated from wb3s.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 15 // Total GPIO count +#define NUM_DIGITAL_PINS 15 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 26 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 20u // GPIO20 +#define PIN_WIRE1_SDA 21u // GPIO21 +#define PIN_WIRE2_SCL 0u // GPIO0 +#define PIN_WIRE2_SDA 1u // GPIO1 + +// Serial ports +// ------------ +#define PIN_SERIAL1_RX 10u // GPIO10 +#define PIN_SERIAL1_TX 11u // GPIO11 +#define PIN_SERIAL2_RX 1u // GPIO1 +#define PIN_SERIAL2_TX 0u // GPIO0 + +// Pin function macros +// ------------------- +#define PIN_ADC3 23u // GPIO23 +#define PIN_P0 0u // GPIO0 +#define PIN_P1 1u // GPIO1 +#define PIN_P6 6u // GPIO6 +#define PIN_P7 7u // GPIO7 +#define PIN_P8 8u // GPIO8 +#define PIN_P9 9u // GPIO9 +#define PIN_P10 10u // GPIO10 +#define PIN_P11 11u // GPIO11 +#define PIN_P14 14u // GPIO14 +#define PIN_P20 20u // GPIO20 +#define PIN_P21 21u // GPIO21 +#define PIN_P22 22u // GPIO22 +#define PIN_P23 23u // GPIO23 +#define PIN_P24 24u // GPIO24 +#define PIN_P26 26u // GPIO26 +#define PIN_PWM0 6u // GPIO6 +#define PIN_PWM1 7u // GPIO7 +#define PIN_PWM2 8u // GPIO8 +#define PIN_PWM3 9u // GPIO9 +#define PIN_PWM4 24u // GPIO24 +#define PIN_PWM5 26u // GPIO26 +#define PIN_RX1 10u // GPIO10 +#define PIN_RX2 1u // GPIO1 +#define PIN_SCK 14u // GPIO14 +#define PIN_SCL1 20u // GPIO20 +#define PIN_SCL2 0u // GPIO0 +#define PIN_SDA1 21u // GPIO21 +#define PIN_SDA2 1u // GPIO1 +#define PIN_TX1 11u // GPIO11 +#define PIN_TX2 0u // GPIO0 + +// Port availability +// ----------------- +#define HAS_SERIAL1 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE1 1 +#define HAS_WIRE2 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 23u // GPIO23 +#define PIN_D1 14u // GPIO14 +#define PIN_D2 26u // GPIO26 +#define PIN_D3 24u // GPIO24 +#define PIN_D4 6u // GPIO6 +#define PIN_D5 7u // GPIO7 +#define PIN_D6 0u // GPIO0 +#define PIN_D7 1u // GPIO1 +#define PIN_D8 9u // GPIO9 +#define PIN_D9 8u // GPIO8 +#define PIN_D10 10u // GPIO10 +#define PIN_D11 11u // GPIO11 +#define PIN_D12 22u // GPIO22 +#define PIN_D13 21u // GPIO21 +#define PIN_D14 20u // GPIO20 +#define PIN_A0 23u // GPIO23 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; +static const unsigned char D11 = PIN_D11; +static const unsigned char D12 = PIN_D12; +static const unsigned char D13 = PIN_D13; +static const unsigned char D14 = PIN_D14; diff --git a/boards/wr2/variant.cpp b/boards/variants/wr2.c similarity index 65% rename from boards/wr2/variant.cpp rename to boards/variants/wr2.c index 7c5f0fa..7dcdcdc 100644 --- a/boards/wr2/variant.cpp +++ b/boards/variants/wr2.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA12, PWM3 {PA_12, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA00, PWM2 @@ -23,6 +25,15 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[1]), // PA_0 (D1) + [5] = &(lt_arduino_pin_info_list[2]), // PA_5 (D2) + [12] = &(lt_arduino_pin_info_list[0]), // PA_12 (D0) + [14] = &(lt_arduino_pin_info_list[5]), // PA_14 (D6) + [15] = &(lt_arduino_pin_info_list[6]), // PA_15 (D7) + [18] = &(lt_arduino_pin_info_list[3]), // PA_18 (D4) + [23] = &(lt_arduino_pin_info_list[4]), // PA_23 (D5) + [41] = &(lt_arduino_pin_info_list[7]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr2.h b/boards/variants/wr2.h new file mode 100644 index 0000000..0c9909d --- /dev/null +++ b/boards/variants/wr2.h @@ -0,0 +1,76 @@ +/* This file was auto-generated from wr2.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 8 // Total GPIO count +#define NUM_DIGITAL_PINS 7 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 6 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 + +// Pin function macros +// ------------------- +#define PIN_ADC2 41u // AD_2 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA23 23u // PA_23 +#define PIN_PWM0 14u // PA_14 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_RX0 18u // PA_18 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 1 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 12u // PA_12 +#define PIN_D1 0u // PA_0 +#define PIN_D2 5u // PA_5 +#define PIN_D4 18u // PA_18 +#define PIN_D5 23u // PA_23 +#define PIN_D6 14u // PA_14 +#define PIN_D7 15u // PA_15 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; diff --git a/boards/wr2e/variant.cpp b/boards/variants/wr2e.c similarity index 68% rename from boards/wr2e/variant.cpp rename to boards/variants/wr2e.c index 3175921..ab08bfb 100644 --- a/boards/wr2e/variant.cpp +++ b/boards/variants/wr2e.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA12, PWM3 {PA_12, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, // D1: PA19, ADC1, UART0_CTS, SPI0_CS, SPI1_CS, I2C0_SDA, SD_D3, TMR5_TRIG, I2S0_TX @@ -23,6 +25,15 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [5] = &(lt_arduino_pin_info_list[2]), // PA_5 (D2) + [12] = &(lt_arduino_pin_info_list[0]), // PA_12 (D0) + [14] = &(lt_arduino_pin_info_list[5]), // PA_14 (D5) + [15] = &(lt_arduino_pin_info_list[6]), // PA_15 (D6) + [18] = &(lt_arduino_pin_info_list[3]), // PA_18 (D3) + [19] = &(lt_arduino_pin_info_list[1]), // PA_19 (D1) + [23] = &(lt_arduino_pin_info_list[4]), // PA_23 (D4) + [41] = &(lt_arduino_pin_info_list[7]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr2e.h b/boards/variants/wr2e.h new file mode 100644 index 0000000..279dbaf --- /dev/null +++ b/boards/variants/wr2e.h @@ -0,0 +1,83 @@ +/* This file was auto-generated from wr2e.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 8 // Total GPIO count +#define NUM_DIGITAL_PINS 7 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 5 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA23 23u // PA_23 +#define PIN_PWM0 14u // PA_14 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_RX0 18u // PA_18 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 19u // PA_19 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 1 +#define WIRE_INTERFACES_COUNT 1 + +// Arduino pin names +// ----------------- +#define PIN_D0 12u // PA_12 +#define PIN_D1 19u // PA_19 +#define PIN_D2 5u // PA_5 +#define PIN_D3 18u // PA_18 +#define PIN_D4 23u // PA_23 +#define PIN_D5 14u // PA_14 +#define PIN_D6 15u // PA_15 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; diff --git a/boards/wr2l/variant.cpp b/boards/variants/wr2l.c similarity index 65% rename from boards/wr2l/variant.cpp rename to boards/variants/wr2l.c index 525dcf2..250ab34 100644 --- a/boards/wr2l/variant.cpp +++ b/boards/variants/wr2l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA15, PWM1, SWDIO {PA_15, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_SWD, PIN_NONE, 0}, // D1: PA14, PWM0, SWCLK @@ -17,6 +19,12 @@ PinInfo pinTable[PINS_COUNT] = { // D4: PA12, PWM3 {PA_12, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [5] = &(lt_arduino_pin_info_list[2]), // PA_5 (D2) + [12] = &(lt_arduino_pin_info_list[4]), // PA_12 (D4) + [14] = &(lt_arduino_pin_info_list[1]), // PA_14 (D1) + [15] = &(lt_arduino_pin_info_list[0]), // PA_15 (D0) + [19] = &(lt_arduino_pin_info_list[3]), // PA_19 (D3) +}; +// clang-format on diff --git a/boards/variants/wr2l.h b/boards/variants/wr2l.h new file mode 100644 index 0000000..70feccd --- /dev/null +++ b/boards/variants/wr2l.h @@ -0,0 +1,48 @@ +/* This file was auto-generated from wr2l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 5 // Total GPIO count +#define NUM_DIGITAL_PINS 5 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 4 // PWM & DAC outputs +#define PINS_GPIO_MAX 19 // Last usable GPIO number + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA19 19u // PA_19 +#define PIN_PWM0 14u // PA_14 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_SDA0 19u // PA_19 + +// Arduino pin names +// ----------------- +#define PIN_D0 15u // PA_15 +#define PIN_D1 14u // PA_14 +#define PIN_D2 5u // PA_5 +#define PIN_D3 19u // PA_19 +#define PIN_D4 12u // PA_12 +#define PIN_A0 19u // PA_19 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; diff --git a/boards/wr2le/variant.cpp b/boards/variants/wr2le.c similarity index 65% rename from boards/wr2le/variant.cpp rename to boards/variants/wr2le.c index 677ebf2..00570cf 100644 --- a/boards/wr2le/variant.cpp +++ b/boards/variants/wr2le.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA15, PWM1, SWDIO {PA_15, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_SWD, PIN_NONE, 0}, // D1: PA14, PWM0, SWCLK @@ -17,6 +19,12 @@ PinInfo pinTable[PINS_COUNT] = { // D4: PA12, PWM3 {PA_12, PIN_GPIO | PIN_IRQ | PIN_PWM, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [5] = &(lt_arduino_pin_info_list[2]), // PA_5 (D2) + [12] = &(lt_arduino_pin_info_list[4]), // PA_12 (D4) + [14] = &(lt_arduino_pin_info_list[1]), // PA_14 (D1) + [15] = &(lt_arduino_pin_info_list[0]), // PA_15 (D0) + [22] = &(lt_arduino_pin_info_list[3]), // PA_22 (D3) +}; +// clang-format on diff --git a/boards/variants/wr2le.h b/boards/variants/wr2le.h new file mode 100644 index 0000000..5ac549c --- /dev/null +++ b/boards/variants/wr2le.h @@ -0,0 +1,46 @@ +/* This file was auto-generated from wr2le.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 5 // Total GPIO count +#define NUM_DIGITAL_PINS 5 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 0 // ADC inputs +#define NUM_ANALOG_OUTPUTS 5 // PWM & DAC outputs +#define PINS_GPIO_MAX 22 // Last usable GPIO number + +// Pin function macros +// ------------------- +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA22 22u // PA_22 +#define PIN_PWM0 14u // PA_14 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_SCL0 22u // PA_22 + +// Arduino pin names +// ----------------- +#define PIN_D0 15u // PA_15 +#define PIN_D1 14u // PA_14 +#define PIN_D2 5u // PA_5 +#define PIN_D3 22u // PA_22 +#define PIN_D4 12u // PA_12 + +// Static pin names +// ---------------- +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; diff --git a/boards/wr3/variant.cpp b/boards/variants/wr3.c similarity index 68% rename from boards/wr3/variant.cpp rename to boards/variants/wr3.c index 43aaa4b..abdd128 100644 --- a/boards/wr3/variant.cpp +++ b/boards/variants/wr3.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA22, UART0_RTS, SPI0_MISO, SPI1_MISO, I2C0_SCL, SD_D0, PWM5, I2S0_WS, WAKE2 {PA_22, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_I2S | PIN_SPI | PIN_UART, PIN_NONE, 0}, // D1: PA19, ADC1, UART0_CTS, SPI0_CS, SPI1_CS, I2C0_SDA, SD_D3, TMR5_TRIG, I2S0_TX @@ -31,6 +33,19 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[4]), // PA_0 (D4) + [5] = &(lt_arduino_pin_info_list[7]), // PA_5 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[2]), // PA_14 (D2) + [15] = &(lt_arduino_pin_info_list[3]), // PA_15 (D3) + [18] = &(lt_arduino_pin_info_list[9]), // PA_18 (D9) + [19] = &(lt_arduino_pin_info_list[1]), // PA_19 (D1) + [22] = &(lt_arduino_pin_info_list[0]), // PA_22 (D0) + [23] = &(lt_arduino_pin_info_list[10]), // PA_23 (D10) + [29] = &(lt_arduino_pin_info_list[5]), // PA_29 (D5) + [30] = &(lt_arduino_pin_info_list[6]), // PA_30 (D6) + [41] = &(lt_arduino_pin_info_list[11]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr3.h b/boards/variants/wr3.h new file mode 100644 index 0000000..e479168 --- /dev/null +++ b/boards/variants/wr3.h @@ -0,0 +1,126 @@ +/* This file was auto-generated from wr3.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 12 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 22u // PA_22 +#define PIN_WIRE0_SCL_1 29u // PA_29 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 22u // PA_22 +#define PIN_D1 19u // PA_19 +#define PIN_D2 14u // PA_14 +#define PIN_D3 15u // PA_15 +#define PIN_D4 0u // PA_0 +#define PIN_D5 29u // PA_29 +#define PIN_D6 30u // PA_30 +#define PIN_D7 5u // PA_5 +#define PIN_D8 12u // PA_12 +#define PIN_D9 18u // PA_18 +#define PIN_D10 23u // PA_23 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/wr3e/variant.cpp b/boards/variants/wr3e.c similarity index 68% rename from boards/wr3e/variant.cpp rename to boards/variants/wr3e.c index 0739909..e47c10c 100644 --- a/boards/wr3e/variant.cpp +++ b/boards/variants/wr3e.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA29, UART2_RX, I2C0_SCL, PWM4 {PA_29, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: PA14, PWM0, SWCLK @@ -31,6 +33,19 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[4]), // PA_0 (D4) + [5] = &(lt_arduino_pin_info_list[7]), // PA_5 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[1]), // PA_14 (D1) + [15] = &(lt_arduino_pin_info_list[2]), // PA_15 (D2) + [18] = &(lt_arduino_pin_info_list[9]), // PA_18 (D9) + [19] = &(lt_arduino_pin_info_list[6]), // PA_19 (D6) + [22] = &(lt_arduino_pin_info_list[3]), // PA_22 (D3) + [23] = &(lt_arduino_pin_info_list[10]), // PA_23 (D10) + [29] = &(lt_arduino_pin_info_list[0]), // PA_29 (D0) + [30] = &(lt_arduino_pin_info_list[5]), // PA_30 (D5) + [41] = &(lt_arduino_pin_info_list[11]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr3e.h b/boards/variants/wr3e.h new file mode 100644 index 0000000..4a4c942 --- /dev/null +++ b/boards/variants/wr3e.h @@ -0,0 +1,126 @@ +/* This file was auto-generated from wr3e.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 12 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 29u // PA_29 +#define PIN_WIRE0_SCL_1 22u // PA_22 +#define PIN_WIRE0_SDA_0 30u // PA_30 +#define PIN_WIRE0_SDA_1 19u // PA_19 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 22u // PA_22 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 19u // PA_19 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 29u // PA_29 +#define PIN_D1 14u // PA_14 +#define PIN_D2 15u // PA_15 +#define PIN_D3 22u // PA_22 +#define PIN_D4 0u // PA_0 +#define PIN_D5 30u // PA_30 +#define PIN_D6 19u // PA_19 +#define PIN_D7 5u // PA_5 +#define PIN_D8 12u // PA_12 +#define PIN_D9 18u // PA_18 +#define PIN_D10 23u // PA_23 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/wr3l/variant.cpp b/boards/variants/wr3l.c similarity index 68% rename from boards/wr3l/variant.cpp rename to boards/variants/wr3l.c index 977b8ef..8261af7 100644 --- a/boards/wr3l/variant.cpp +++ b/boards/variants/wr3l.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA22, UART0_RTS, SPI0_MISO, SPI1_MISO, I2C0_SCL, SD_D0, PWM5, I2S0_WS, WAKE2 {PA_22, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_I2S | PIN_SPI | PIN_UART, PIN_NONE, 0}, // D1: PA19, ADC1, UART0_CTS, SPI0_CS, SPI1_CS, I2C0_SDA, SD_D3, TMR5_TRIG, I2S0_TX @@ -31,6 +33,19 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[4]), // PA_0 (D4) + [5] = &(lt_arduino_pin_info_list[7]), // PA_5 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[2]), // PA_14 (D2) + [15] = &(lt_arduino_pin_info_list[3]), // PA_15 (D3) + [18] = &(lt_arduino_pin_info_list[9]), // PA_18 (D9) + [19] = &(lt_arduino_pin_info_list[1]), // PA_19 (D1) + [22] = &(lt_arduino_pin_info_list[0]), // PA_22 (D0) + [23] = &(lt_arduino_pin_info_list[10]), // PA_23 (D10) + [29] = &(lt_arduino_pin_info_list[5]), // PA_29 (D5) + [30] = &(lt_arduino_pin_info_list[6]), // PA_30 (D6) + [41] = &(lt_arduino_pin_info_list[11]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr3l.h b/boards/variants/wr3l.h new file mode 100644 index 0000000..5a692a6 --- /dev/null +++ b/boards/variants/wr3l.h @@ -0,0 +1,126 @@ +/* This file was auto-generated from wr3l.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 12 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 22u // PA_22 +#define PIN_WIRE0_SCL_1 29u // PA_29 +#define PIN_WIRE0_SDA_0 19u // PA_19 +#define PIN_WIRE0_SDA_1 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 22u // PA_22 +#define PIN_D1 19u // PA_19 +#define PIN_D2 14u // PA_14 +#define PIN_D3 15u // PA_15 +#define PIN_D4 0u // PA_0 +#define PIN_D5 29u // PA_29 +#define PIN_D6 30u // PA_30 +#define PIN_D7 5u // PA_5 +#define PIN_D8 12u // PA_12 +#define PIN_D9 18u // PA_18 +#define PIN_D10 23u // PA_23 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/wr3le/variant.cpp b/boards/variants/wr3le.c similarity index 68% rename from boards/wr3le/variant.cpp rename to boards/variants/wr3le.c index 4fac504..b96370f 100644 --- a/boards/wr3le/variant.cpp +++ b/boards/variants/wr3le.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA29, UART2_RX, I2C0_SCL, PWM4 {PA_29, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: PA14, PWM0, SWCLK @@ -31,6 +33,19 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[4]), // PA_0 (D4) + [5] = &(lt_arduino_pin_info_list[7]), // PA_5 (D7) + [12] = &(lt_arduino_pin_info_list[8]), // PA_12 (D8) + [14] = &(lt_arduino_pin_info_list[1]), // PA_14 (D1) + [15] = &(lt_arduino_pin_info_list[2]), // PA_15 (D2) + [18] = &(lt_arduino_pin_info_list[9]), // PA_18 (D9) + [19] = &(lt_arduino_pin_info_list[6]), // PA_19 (D6) + [22] = &(lt_arduino_pin_info_list[3]), // PA_22 (D3) + [23] = &(lt_arduino_pin_info_list[10]), // PA_23 (D10) + [29] = &(lt_arduino_pin_info_list[0]), // PA_29 (D0) + [30] = &(lt_arduino_pin_info_list[5]), // PA_30 (D5) + [41] = &(lt_arduino_pin_info_list[11]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr3le.h b/boards/variants/wr3le.h new file mode 100644 index 0000000..8063f1b --- /dev/null +++ b/boards/variants/wr3le.h @@ -0,0 +1,126 @@ +/* This file was auto-generated from wr3le.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 12 // Total GPIO count +#define NUM_DIGITAL_PINS 11 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 2 // ADC inputs +#define NUM_ANALOG_OUTPUTS 9 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// SPI Interfaces +// -------------- +#define PIN_SPI0_CS 19u // PA_19 +#define PIN_SPI0_MISO 22u // PA_22 +#define PIN_SPI0_MOSI 23u // PA_23 +#define PIN_SPI0_SCK 18u // PA_18 +#define PIN_SPI1_CS 19u // PA_19 +#define PIN_SPI1_MISO 22u // PA_22 +#define PIN_SPI1_MOSI 23u // PA_23 +#define PIN_SPI1_SCK 18u // PA_18 + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL_0 29u // PA_29 +#define PIN_WIRE0_SCL_1 22u // PA_22 +#define PIN_WIRE0_SDA_0 30u // PA_30 +#define PIN_WIRE0_SDA_1 19u // PA_19 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_CTS 19u // PA_19 +#define PIN_SERIAL0_RTS 22u // PA_22 +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC1 19u // PA_19 +#define PIN_ADC2 41u // AD_2 +#define PIN_CS0 19u // PA_19 +#define PIN_CS1 19u // PA_19 +#define PIN_CTS0 19u // PA_19 +#define PIN_MISO0 22u // PA_22 +#define PIN_MISO1 22u // PA_22 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA19 19u // PA_19 +#define PIN_PA22 22u // PA_22 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_PWM5 22u // PA_22 +#define PIN_RTS0 22u // PA_22 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 22u // PA_22 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 19u // PA_19 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_SPI0 1 +#define HAS_SPI1 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 29u // PA_29 +#define PIN_D1 14u // PA_14 +#define PIN_D2 15u // PA_15 +#define PIN_D3 22u // PA_22 +#define PIN_D4 0u // PA_0 +#define PIN_D5 30u // PA_30 +#define PIN_D6 19u // PA_19 +#define PIN_D7 5u // PA_5 +#define PIN_D8 12u // PA_12 +#define PIN_D9 18u // PA_18 +#define PIN_D10 23u // PA_23 +#define PIN_A0 19u // PA_19 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A0 = PIN_A0; +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; +static const unsigned char D9 = PIN_D9; +static const unsigned char D10 = PIN_D10; diff --git a/boards/wr3n/variant.cpp b/boards/variants/wr3n.c similarity index 66% rename from boards/wr3n/variant.cpp rename to boards/variants/wr3n.c index 955c0a4..5af75b6 100644 --- a/boards/wr3n/variant.cpp +++ b/boards/variants/wr3n.c @@ -2,10 +2,12 @@ #include -extern "C" { +#ifdef LT_VARIANT_INCLUDE +#include LT_VARIANT_INCLUDE +#endif // clang-format off -PinInfo pinTable[PINS_COUNT] = { +PinInfo lt_arduino_pin_info_list[PINS_COUNT] = { // D0: PA29, UART2_RX, I2C0_SCL, PWM4 {PA_29, PIN_GPIO | PIN_IRQ | PIN_PWM | PIN_I2C | PIN_UART, PIN_NONE, 0}, // D1: PA14, PWM0, SWCLK @@ -27,6 +29,17 @@ PinInfo pinTable[PINS_COUNT] = { // A1: ADC2 {AD_2, PIN_ADC, PIN_NONE, 0}, }; -// clang-format on -} // extern "C" +PinInfo *lt_arduino_pin_gpio_map[] = { + [0] = &(lt_arduino_pin_info_list[3]), // PA_0 (D3) + [5] = &(lt_arduino_pin_info_list[5]), // PA_5 (D5) + [12] = &(lt_arduino_pin_info_list[6]), // PA_12 (D6) + [14] = &(lt_arduino_pin_info_list[1]), // PA_14 (D1) + [15] = &(lt_arduino_pin_info_list[2]), // PA_15 (D2) + [18] = &(lt_arduino_pin_info_list[7]), // PA_18 (D7) + [23] = &(lt_arduino_pin_info_list[8]), // PA_23 (D8) + [29] = &(lt_arduino_pin_info_list[0]), // PA_29 (D0) + [30] = &(lt_arduino_pin_info_list[4]), // PA_30 (D4) + [41] = &(lt_arduino_pin_info_list[9]), // AD_2 (A1) +}; +// clang-format on diff --git a/boards/variants/wr3n.h b/boards/variants/wr3n.h new file mode 100644 index 0000000..0c44afa --- /dev/null +++ b/boards/variants/wr3n.h @@ -0,0 +1,92 @@ +/* This file was auto-generated from wr3n.json using boardgen */ + +#pragma once + +// clang-format off + +// Pins +// ---- +#define PINS_COUNT 10 // Total GPIO count +#define NUM_DIGITAL_PINS 9 // Digital inputs/outputs +#define NUM_ANALOG_INPUTS 1 // ADC inputs +#define NUM_ANALOG_OUTPUTS 8 // PWM & DAC outputs +#define PINS_GPIO_MAX 41 // Last usable GPIO number + +// Wire Interfaces +// --------------- +#define PIN_WIRE0_SCL 29u // PA_29 +#define PIN_WIRE0_SDA 30u // PA_30 +#define PIN_WIRE1_SCL 18u // PA_18 +#define PIN_WIRE1_SDA 23u // PA_23 + +// Serial ports +// ------------ +#define PIN_SERIAL0_RX 18u // PA_18 +#define PIN_SERIAL0_TX 23u // PA_23 +#define PIN_SERIAL2_RX 29u // PA_29 +#define PIN_SERIAL2_TX 30u // PA_30 + +// Pin function macros +// ------------------- +#define PIN_ADC2 41u // AD_2 +#define PIN_MOSI0 23u // PA_23 +#define PIN_MOSI1 23u // PA_23 +#define PIN_PA00 0u // PA_0 +#define PIN_PA05 5u // PA_5 +#define PIN_PA12 12u // PA_12 +#define PIN_PA14 14u // PA_14 +#define PIN_PA15 15u // PA_15 +#define PIN_PA18 18u // PA_18 +#define PIN_PA23 23u // PA_23 +#define PIN_PA29 29u // PA_29 +#define PIN_PA30 30u // PA_30 +#define PIN_PWM0 23u // PA_23 +#define PIN_PWM1 15u // PA_15 +#define PIN_PWM2 0u // PA_0 +#define PIN_PWM3 12u // PA_12 +#define PIN_PWM4 5u // PA_5 +#define PIN_RX0 18u // PA_18 +#define PIN_RX2 29u // PA_29 +#define PIN_SCK0 18u // PA_18 +#define PIN_SCK1 18u // PA_18 +#define PIN_SCL0 29u // PA_29 +#define PIN_SCL1 18u // PA_18 +#define PIN_SDA0 30u // PA_30 +#define PIN_SDA1 23u // PA_23 +#define PIN_TX0 23u // PA_23 +#define PIN_TX2 30u // PA_30 + +// Port availability +// ----------------- +#define HAS_SERIAL0 1 +#define HAS_SERIAL2 1 +#define HAS_WIRE0 1 +#define HAS_WIRE1 1 +#define SERIAL_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 2 + +// Arduino pin names +// ----------------- +#define PIN_D0 29u // PA_29 +#define PIN_D1 14u // PA_14 +#define PIN_D2 15u // PA_15 +#define PIN_D3 0u // PA_0 +#define PIN_D4 30u // PA_30 +#define PIN_D5 5u // PA_5 +#define PIN_D6 12u // PA_12 +#define PIN_D7 18u // PA_18 +#define PIN_D8 23u // PA_23 +#define PIN_A1 41u // AD_2 + +// Static pin names +// ---------------- +static const unsigned char A1 = PIN_A1; +static const unsigned char D0 = PIN_D0; +static const unsigned char D1 = PIN_D1; +static const unsigned char D2 = PIN_D2; +static const unsigned char D3 = PIN_D3; +static const unsigned char D4 = PIN_D4; +static const unsigned char D5 = PIN_D5; +static const unsigned char D6 = PIN_D6; +static const unsigned char D7 = PIN_D7; +static const unsigned char D8 = PIN_D8; diff --git a/boards/wb2l/README.md b/boards/wb2l/README.md deleted file mode 100644 index 698083f..0000000 --- a/boards/wb2l/README.md +++ /dev/null @@ -1,87 +0,0 @@ -# WB2L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wb2l-datasheet?id=K9duegc9bualu) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wb2l` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 13x GPIO, 5x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 -FCC ID | [2ANDL-WB2L](https://fccid.io/2ANDL-WB2L) - -## Usage - -**Board code:** `wb2l` - -In `platformio.ini`: - -```ini -[env:wb2l] -platform = libretuya -board = wb2l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wb2l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wb2l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P8 | | | | PWM2 | -D1 | P7 | | | | PWM1 | -D2 | P6 | | | | PWM0 | -D3 | P26 | | | | PWM5 | -D4 | P24 | | | | PWM4 | -D5 | P10 | UART1_RX | | | | -D6 | P11 | UART1_TX | | | | -D7 | P1 | UART2_RX | I2C2_SDA | | | -D8 | P0 | UART2_TX | I2C2_SCL | | | -D9 | P20 | | I2C1_SCL | | | TCK -D10 | P21 | | I2C1_SDA | | | TMS -D11 | P23 | | | | | TDO -D12 | P22 | | | | | TDI -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/wb2l/pinout_wb2l.svg b/boards/wb2l/pinout_wb2l.svg deleted file mode 100644 index c47c44e..0000000 --- a/boards/wb2l/pinout_wb2l.svg +++ /dev/null @@ -1,372 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WB2L - - - - - - - - - - - - - - - - - - - - - - P8 - - - - D0 - - - - PWM2 - - - - - P7 - - - - D1 - - - - PWM1 - - - - - P6 - - - - D2 - - - - PWM0 - - - - - P26 - - - - D3 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D4 - - - - PWM4 - - - - - GND - - - - - 3V3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GND - - - - - ___ - RST - - - - - P10 - - - - D5 - - - - RX1 - - - - - P11 - - - - D6 - - - - TX1 - - - - - P1 - - - - D7 - - - - RX2 - - - - SDA2 - - - - - P0 - - - - D8 - - - - TX2 - - - - SCL2 - - - - - P20 - - - - D9 - - - - SCL1 - - - - TCK - - - - FSCK - - - - - P21 - - - - D10 - - - - SDA1 - - - - TMS - - - - ___ - FCS - - - - - P23 - - - - ADC3 - - - - D11 - - - - A0 - - - - TDO - - - - FSO - - - - - P22 - - - - D12 - - - - TDI - - - - FSI - diff --git a/boards/wb2l/pins_arduino.h b/boards/wb2l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wb2l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wb2l/variant.h b/boards/wb2l/variant.h deleted file mode 100644 index 3c26b7b..0000000 --- a/boards/wb2l/variant.h +++ /dev/null @@ -1,69 +0,0 @@ -/* This file was auto-generated from wb2l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 13 -#define NUM_DIGITAL_PINS 13 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 11u // GPIO23 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 9u // GPIO20 -#define PIN_WIRE1_SDA 10u // GPIO21 -#define PIN_WIRE2_SCL 8u // GPIO0 -#define PIN_WIRE2_SDA 7u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 5u // GPIO10 -#define PIN_SERIAL1_TX 6u // GPIO11 -#define PIN_SERIAL2_RX 7u // GPIO1 -#define PIN_SERIAL2_TX 8u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 11u // GPIO23 -#define PIN_FUNCTION_P0 8u // GPIO0 -#define PIN_FUNCTION_P1 7u // GPIO1 -#define PIN_FUNCTION_P6 2u // GPIO6 -#define PIN_FUNCTION_P7 1u // GPIO7 -#define PIN_FUNCTION_P8 0u // GPIO8 -#define PIN_FUNCTION_P10 5u // GPIO10 -#define PIN_FUNCTION_P11 6u // GPIO11 -#define PIN_FUNCTION_P20 9u // GPIO20 -#define PIN_FUNCTION_P21 10u // GPIO21 -#define PIN_FUNCTION_P22 12u // GPIO22 -#define PIN_FUNCTION_P23 11u // GPIO23 -#define PIN_FUNCTION_P24 4u // GPIO24 -#define PIN_FUNCTION_P26 3u // GPIO26 -#define PIN_FUNCTION_PWM0 2u // GPIO6 -#define PIN_FUNCTION_PWM1 1u // GPIO7 -#define PIN_FUNCTION_PWM2 0u // GPIO8 -#define PIN_FUNCTION_PWM4 4u // GPIO24 -#define PIN_FUNCTION_PWM5 3u // GPIO26 -#define PIN_FUNCTION_RX1 5u // GPIO10 -#define PIN_FUNCTION_RX2 7u // GPIO1 -#define PIN_FUNCTION_SCL1 9u // GPIO20 -#define PIN_FUNCTION_SCL2 8u // GPIO0 -#define PIN_FUNCTION_SDA1 10u // GPIO21 -#define PIN_FUNCTION_SDA2 7u // GPIO1 -#define PIN_FUNCTION_TX1 6u // GPIO11 -#define PIN_FUNCTION_TX2 8u // GPIO0 diff --git a/boards/wb2s/README.md b/boards/wb2s/README.md deleted file mode 100644 index cf44ee6..0000000 --- a/boards/wb2s/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# WB2S Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wb2s-module-datasheet?id=K9ghecl7kc479) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wb2s` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 14x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 -FCC ID | [2ANDL-WB2S](https://fccid.io/2ANDL-WB2S) - -## Usage - -**Board code:** `wb2s` - -In `platformio.ini`: - -```ini -[env:wb2s] -platform = libretuya -board = wb2s -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wb2s - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wb2s.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P8 | | | | PWM2 | -D1 | P7 | | | | PWM1 | -D2 | P6 | | | | PWM0 | -D3 | P23 | | | | | TDO -D4 | P10 | UART1_RX | | | | -D5 | P11 | UART1_TX | | | | -D6 | P24 | | | | PWM4 | -D7 | P26 | | | | PWM5 | -D8 | P20 | | I2C1_SCL | | | TCK -D9 | P9 | | | | PWM3 | -D10 | P1 | UART2_RX | I2C2_SDA | | | -D11 | P0 | UART2_TX | I2C2_SCL | | | -D12 | P21 | | I2C1_SDA | | | TMS -D13 | P22 | | | | | TDI -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/wb2s/pinout_wb2s.svg b/boards/wb2s/pinout_wb2s.svg deleted file mode 100644 index 5ecf3d1..0000000 --- a/boards/wb2s/pinout_wb2s.svg +++ /dev/null @@ -1,391 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WB2S - - - - - - - - - - - - - - - - - - - - - - P8 - - - - D0 - - - - PWM2 - - - - - P7 - - - - D1 - - - - PWM1 - - - - - P6 - - - - D2 - - - - PWM0 - - - - - P23 - - - - ADC3 - - - - D3 - - - - A0 - - - - TDO - - - - - CEN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - GND - - - - - P10 - - - - D4 - - - - RX1 - - - - - P11 - - - - D5 - - - - TX1 - - - - - P24 - - - - D6 - - - - PWM4 - - - - - P26 - - - - D7 - - - - IRDA - - - - PWM5 - - - - - P20 - - - - D8 - - - - SCL1 - - - - TCK - - - - - P9 - - - - D9 - - - - PWM3 - - - - - P1 - - - - D10 - - - - RX2 - - - - SDA2 - - - - - P0 - - - - D11 - - - - TX2 - - - - SCL2 - - - - - P21 - - - - D12 - - - - SDA1 - - - - TMS - - - - - P22 - - - - D13 - - - - TDI - - - - - P23 - - - - ADC3 - - - - D3 - - - - A0 - - - - TDO - - - - - ___ - RST - - - - - 3V3 - - - - - GND - diff --git a/boards/wb2s/pins_arduino.h b/boards/wb2s/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wb2s/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wb2s/variant.h b/boards/wb2s/variant.h deleted file mode 100644 index a2b9c4b..0000000 --- a/boards/wb2s/variant.h +++ /dev/null @@ -1,73 +0,0 @@ -/* This file was auto-generated from wb2s.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 14 -#define NUM_DIGITAL_PINS 14 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 3u // GPIO23 -#define PIN_A0 3u // GPIO23 -#define A0 PIN_A0 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 8u // GPIO20 -#define PIN_WIRE1_SDA 12u // GPIO21 -#define PIN_WIRE2_SCL 11u // GPIO0 -#define PIN_WIRE2_SDA 10u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 4u // GPIO10 -#define PIN_SERIAL1_TX 5u // GPIO11 -#define PIN_SERIAL2_RX 10u // GPIO1 -#define PIN_SERIAL2_TX 11u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 3u // GPIO23 -#define PIN_FUNCTION_P0 11u // GPIO0 -#define PIN_FUNCTION_P1 10u // GPIO1 -#define PIN_FUNCTION_P6 2u // GPIO6 -#define PIN_FUNCTION_P7 1u // GPIO7 -#define PIN_FUNCTION_P8 0u // GPIO8 -#define PIN_FUNCTION_P9 9u // GPIO9 -#define PIN_FUNCTION_P10 4u // GPIO10 -#define PIN_FUNCTION_P11 5u // GPIO11 -#define PIN_FUNCTION_P20 8u // GPIO20 -#define PIN_FUNCTION_P21 12u // GPIO21 -#define PIN_FUNCTION_P22 13u // GPIO22 -#define PIN_FUNCTION_P23 3u // GPIO23 -#define PIN_FUNCTION_P24 6u // GPIO24 -#define PIN_FUNCTION_P26 7u // GPIO26 -#define PIN_FUNCTION_PWM0 2u // GPIO6 -#define PIN_FUNCTION_PWM1 1u // GPIO7 -#define PIN_FUNCTION_PWM2 0u // GPIO8 -#define PIN_FUNCTION_PWM3 9u // GPIO9 -#define PIN_FUNCTION_PWM4 6u // GPIO24 -#define PIN_FUNCTION_PWM5 7u // GPIO26 -#define PIN_FUNCTION_RX1 4u // GPIO10 -#define PIN_FUNCTION_RX2 10u // GPIO1 -#define PIN_FUNCTION_SCL1 8u // GPIO20 -#define PIN_FUNCTION_SCL2 11u // GPIO0 -#define PIN_FUNCTION_SDA1 12u // GPIO21 -#define PIN_FUNCTION_SDA2 10u // GPIO1 -#define PIN_FUNCTION_TX1 5u // GPIO11 -#define PIN_FUNCTION_TX2 11u // GPIO0 diff --git a/boards/wb3l/README.md b/boards/wb3l/README.md deleted file mode 100644 index 4baf8e4..0000000 --- a/boards/wb3l/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# WB3L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wb3l-module-datasheet?id=K9duiggw2v8sp) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wb3l` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 16x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 -FCC ID | [2ANDL-WB3L](https://fccid.io/2ANDL-WB3L) - -## Usage - -**Board code:** `wb3l` - -In `platformio.ini`: - -```ini -[env:wb3l] -platform = libretuya -board = wb3l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wb3l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wb3l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|------|------|------ -D0 | P23 | | | | | TDO -D1 | P14 | | | SCK | | -D2 | P26 | | | | PWM5 | -D3 | P24 | | | | PWM4 | -D4 | P6 | | | | PWM0 | -D5 | P9 | | | | PWM3 | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P16 | | | MOSI | | -D8 | P8 | | | | PWM2 | -D9 | P7 | | | | PWM1 | -D10 | P10 | UART1_RX | | | | -D11 | P11 | UART1_TX | | | | -D12 | P22 | | | | | TDI -D13 | P21 | | I2C1_SDA | | | TMS -D14 | P20 | | I2C1_SCL | | | TCK -D15 | P1 | UART2_RX | I2C2_SDA | | | -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/wb3l/pinout_wb3l.svg b/boards/wb3l/pinout_wb3l.svg deleted file mode 100644 index 26cd9a6..0000000 --- a/boards/wb3l/pinout_wb3l.svg +++ /dev/null @@ -1,372 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WB3L - - - - - - - - - - - - - - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - CEN - - - - - P14 - - - - D1 - - - - - P26 - - - - D2 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - P6 - - - - D4 - - - - PWM0 - - - - - 3V3 - - - - - GND - - - - - P9 - - - - D5 - - - - PWM3 - - - - - P0 - - - - D6 - - - - TX2 - - - - SCL2 - - - - - P16 - - - - D7 - - - - - P8 - - - - D8 - - - - PWM2 - - - - - P7 - - - - D9 - - - - PWM1 - - - - - P10 - - - - D10 - - - - RX1 - - - - - P11 - - - - D11 - - - - TX1 - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - P22 - - - - D12 - - - - TDI - - - - FSI - - - - - P21 - - - - D13 - - - - SDA1 - - - - TMS - - - - ___ - FCS - - - - - P20 - - - - D14 - - - - SCL1 - - - - TCK - - - - FSCK - - - - - P1 - - - - D15 - - - - RX2 - - - - SDA2 - diff --git a/boards/wb3l/pins_arduino.h b/boards/wb3l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wb3l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wb3l/variant.h b/boards/wb3l/variant.h deleted file mode 100644 index da5196a..0000000 --- a/boards/wb3l/variant.h +++ /dev/null @@ -1,77 +0,0 @@ -/* This file was auto-generated from wb3l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 16 -#define NUM_DIGITAL_PINS 16 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 0u // GPIO23 -#define PIN_A0 0u // GPIO23 -#define A0 PIN_A0 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 14u // GPIO20 -#define PIN_WIRE1_SDA 13u // GPIO21 -#define PIN_WIRE2_SCL 6u // GPIO0 -#define PIN_WIRE2_SDA 15u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 10u // GPIO10 -#define PIN_SERIAL1_TX 11u // GPIO11 -#define PIN_SERIAL2_RX 15u // GPIO1 -#define PIN_SERIAL2_TX 6u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 0u // GPIO23 -#define PIN_FUNCTION_MOSI 7u // GPIO16 -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P1 15u // GPIO1 -#define PIN_FUNCTION_P6 4u // GPIO6 -#define PIN_FUNCTION_P7 9u // GPIO7 -#define PIN_FUNCTION_P8 8u // GPIO8 -#define PIN_FUNCTION_P9 5u // GPIO9 -#define PIN_FUNCTION_P10 10u // GPIO10 -#define PIN_FUNCTION_P11 11u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P16 7u // GPIO16 -#define PIN_FUNCTION_P20 14u // GPIO20 -#define PIN_FUNCTION_P21 13u // GPIO21 -#define PIN_FUNCTION_P22 12u // GPIO22 -#define PIN_FUNCTION_P23 0u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 2u // GPIO26 -#define PIN_FUNCTION_PWM0 4u // GPIO6 -#define PIN_FUNCTION_PWM1 9u // GPIO7 -#define PIN_FUNCTION_PWM2 8u // GPIO8 -#define PIN_FUNCTION_PWM3 5u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 2u // GPIO26 -#define PIN_FUNCTION_RX1 10u // GPIO10 -#define PIN_FUNCTION_RX2 15u // GPIO1 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL1 14u // GPIO20 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA1 13u // GPIO21 -#define PIN_FUNCTION_SDA2 15u // GPIO1 -#define PIN_FUNCTION_TX1 11u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/wb3s/README.md b/boards/wb3s/README.md deleted file mode 100644 index de30353..0000000 --- a/boards/wb3s/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# WB3S Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wb3s-module-datasheet?id=K9dx20n6hz5n4) - -- [General info](../../docs/platform/beken-72xx/README.md) -- [Flashing guide](../../docs/platform/beken-72xx/flashing.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wb3s` -MCU | BK7231T -Manufacturer | Beken -Series | BK72XX -Frequency | 120 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 15x GPIO, 6x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -Bluetooth | BLE v4.2 -FCC ID | [2ANDL-WB3S](https://fccid.io/2ANDL-WB3S) - -## Usage - -**Board code:** `wb3s` - -In `platformio.ini`: - -```ini -[env:wb3s] -platform = libretuya -board = wb3s -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wb3s - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wb3s.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|-----------|----------|----------|-----|------|------ -D0 | P23 | | | | | TDO -D1 | P14 | | | SCK | | -D2 | P26 | | | | PWM5 | -D3 | P24 | | | | PWM4 | -D4 | P6 | | | | PWM0 | -D5 | P7 | | | | PWM1 | -D6 | P0 | UART2_TX | I2C2_SCL | | | -D7 | P1 | UART2_RX | I2C2_SDA | | | -D8 | P9 | | | | PWM3 | -D9 | P8 | | | | PWM2 | -D10 | P10 | UART1_RX | | | | -D11 | P11 | UART1_TX | | | | -D12 | P22 | | | | | TDI -D13 | P21 | | I2C1_SDA | | | TMS -D14 | P20 | | I2C1_SCL | | | TCK -A0 | P23, ADC3 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|--------------------|--------- -Bootloader | 0x000000 | 68 KiB / 0x11000 | 0x011000 -App Image | 0x011000 | 1.1 MiB / 0x121000 | 0x132000 -OTA Image | 0x132000 | 664 KiB / 0xA6000 | 0x1D8000 -Key-Value Store | 0x1D8000 | 32 KiB / 0x8000 | 0x1E0000 -Calibration | 0x1E0000 | 4 KiB / 0x1000 | 0x1E1000 -TLV Store | 0x1E1000 | 4 KiB / 0x1000 | 0x1E2000 -Network Data | 0x1E2000 | 4 KiB / 0x1000 | 0x1E3000 -User Data | 0x1E3000 | 116 KiB / 0x1D000 | 0x200000 - -Bootloader and app partitions contain CRC16 sums every 32 bytes. That results in the actual flash offsets/sizes not aligned to sector boundaries. To simplify calculations, the values shown in the table (extracted from bootloader's partition table) were aligned to 4096 bytes. diff --git a/boards/wb3s/pinout_wb3s.svg b/boards/wb3s/pinout_wb3s.svg deleted file mode 100644 index 9533b88..0000000 --- a/boards/wb3s/pinout_wb3s.svg +++ /dev/null @@ -1,370 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WB3S - - - - - - - - - - - - - - - - - CEN - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - - P14 - - - - D1 - - - - - P26 - - - - D2 - - - - IRDA - - - - PWM5 - - - - - P24 - - - - D3 - - - - PWM4 - - - - - P6 - - - - D4 - - - - PWM0 - - - - - 3V3 - - - - - GND - - - - - P7 - - - - D5 - - - - PWM1 - - - - - P0 - - - - D6 - - - - TX2 - - - - SCL2 - - - - - P1 - - - - D7 - - - - RX2 - - - - SDA2 - - - - - P9 - - - - D8 - - - - PWM3 - - - - - P8 - - - - D9 - - - - PWM2 - - - - - P10 - - - - D10 - - - - RX1 - - - - - P11 - - - - D11 - - - - TX1 - - - - - P23 - - - - ADC3 - - - - D0 - - - - A0 - - - - TDO - - - - FSO - - - - - P22 - - - - D12 - - - - TDI - - - - FSI - - - - - P21 - - - - D13 - - - - SDA1 - - - - TMS - - - - ___ - FCS - - - - - P20 - - - - D14 - - - - SCL1 - - - - TCK - - - - FSCK - - - diff --git a/boards/wb3s/pins_arduino.h b/boards/wb3s/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wb3s/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wb3s/variant.h b/boards/wb3s/variant.h deleted file mode 100644 index 2c1fb78..0000000 --- a/boards/wb3s/variant.h +++ /dev/null @@ -1,75 +0,0 @@ -/* This file was auto-generated from wb3s.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 15 -#define NUM_DIGITAL_PINS 15 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 0u // GPIO23 -#define PIN_A0 0u // GPIO23 -#define A0 PIN_A0 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE1_SCL 14u // GPIO20 -#define PIN_WIRE1_SDA 13u // GPIO21 -#define PIN_WIRE2_SCL 6u // GPIO0 -#define PIN_WIRE2_SDA 7u // GPIO1 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL1_RX 10u // GPIO10 -#define PIN_SERIAL1_TX 11u // GPIO11 -#define PIN_SERIAL2_RX 7u // GPIO1 -#define PIN_SERIAL2_TX 6u // GPIO0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC3 0u // GPIO23 -#define PIN_FUNCTION_P0 6u // GPIO0 -#define PIN_FUNCTION_P1 7u // GPIO1 -#define PIN_FUNCTION_P6 4u // GPIO6 -#define PIN_FUNCTION_P7 5u // GPIO7 -#define PIN_FUNCTION_P8 9u // GPIO8 -#define PIN_FUNCTION_P9 8u // GPIO9 -#define PIN_FUNCTION_P10 10u // GPIO10 -#define PIN_FUNCTION_P11 11u // GPIO11 -#define PIN_FUNCTION_P14 1u // GPIO14 -#define PIN_FUNCTION_P20 14u // GPIO20 -#define PIN_FUNCTION_P21 13u // GPIO21 -#define PIN_FUNCTION_P22 12u // GPIO22 -#define PIN_FUNCTION_P23 0u // GPIO23 -#define PIN_FUNCTION_P24 3u // GPIO24 -#define PIN_FUNCTION_P26 2u // GPIO26 -#define PIN_FUNCTION_PWM0 4u // GPIO6 -#define PIN_FUNCTION_PWM1 5u // GPIO7 -#define PIN_FUNCTION_PWM2 9u // GPIO8 -#define PIN_FUNCTION_PWM3 8u // GPIO9 -#define PIN_FUNCTION_PWM4 3u // GPIO24 -#define PIN_FUNCTION_PWM5 2u // GPIO26 -#define PIN_FUNCTION_RX1 10u // GPIO10 -#define PIN_FUNCTION_RX2 7u // GPIO1 -#define PIN_FUNCTION_SCK 1u // GPIO14 -#define PIN_FUNCTION_SCL1 14u // GPIO20 -#define PIN_FUNCTION_SCL2 6u // GPIO0 -#define PIN_FUNCTION_SDA1 13u // GPIO21 -#define PIN_FUNCTION_SDA2 7u // GPIO1 -#define PIN_FUNCTION_TX1 11u // GPIO11 -#define PIN_FUNCTION_TX2 6u // GPIO0 diff --git a/boards/wr2/README.md b/boards/wr2/README.md deleted file mode 100644 index 3fdfc80..0000000 --- a/boards/wr2/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# WR2 Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wifiwr2module?id=K9605tko0juc3) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|---------------------------------------- -Board code | `wr2` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 7x GPIO, 5x PWM, 1x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR2](https://fccid.io/2ANDL-WR2) - -## Usage - -**Board code:** `wr2` - -In `platformio.ini`: - -```ini -[env:wr2] -platform = libretuya -board = wr2 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr2 - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr2.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------|----------|----------|----------------------|------|------ -D0 | PA12 | | | | PWM3 | -D1 | PA00 | | | | PWM2 | -D2 | PA05 | | | | PWM4 | -D4 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D5 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -D6 | PA14 | | | | PWM0 | SWCLK -D7 | PA15 | | | | PWM1 | SWDIO -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr2/pinout_wr2.svg b/boards/wr2/pinout_wr2.svg deleted file mode 100644 index e240c2d..0000000 --- a/boards/wr2/pinout_wr2.svg +++ /dev/null @@ -1,224 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR2 - - - - - - - - - - - - - - - - - - - - - - PA12 - - - - D0 - - - - PWM3 - - - - - PA00 - - - - D1 - - - - PWM2 - - - - - PA05 - - - - D2 - - - - PWM4 - - - - - ADC2 - - - - A1 - - - - - CEN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - GND - - - - - PA18 - - - - D4 - - - - RX0 - - - - SCL1 - - - - - PA23 - - - - D5 - - - - TX0 - - - - SDA1 - - - - PWM0 - - - - - PA14 - - - - D6 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D7 - - - - PWM1 - - - - SWDIO - diff --git a/boards/wr2/pins_arduino.h b/boards/wr2/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr2/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr2/variant.h b/boards/wr2/variant.h deleted file mode 100644 index 3fb6663..0000000 --- a/boards/wr2/variant.h +++ /dev/null @@ -1,54 +0,0 @@ -/* This file was auto-generated from wr2.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 8 -#define NUM_DIGITAL_PINS 7 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A1 7u // AD_2 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE1_SCL 3u // PA_18 -#define PIN_WIRE1_SDA 4u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 1 -#define PIN_SERIAL0_RX 3u // PA_18 -#define PIN_SERIAL0_TX 4u // PA_23 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC2 7u // AD_2 -#define PIN_FUNCTION_MOSI0 4u // PA_23 -#define PIN_FUNCTION_MOSI1 4u // PA_23 -#define PIN_FUNCTION_PA00 1u // PA_0 -#define PIN_FUNCTION_PA05 2u // PA_5 -#define PIN_FUNCTION_PA12 0u // PA_12 -#define PIN_FUNCTION_PA14 5u // PA_14 -#define PIN_FUNCTION_PA15 6u // PA_15 -#define PIN_FUNCTION_PA18 3u // PA_18 -#define PIN_FUNCTION_PA23 4u // PA_23 -#define PIN_FUNCTION_RX0 3u // PA_18 -#define PIN_FUNCTION_SCK0 3u // PA_18 -#define PIN_FUNCTION_SCK1 3u // PA_18 -#define PIN_FUNCTION_SCL1 3u // PA_18 -#define PIN_FUNCTION_SDA1 4u // PA_23 -#define PIN_FUNCTION_TX0 4u // PA_23 diff --git a/boards/wr2e/README.md b/boards/wr2e/README.md deleted file mode 100644 index 2a513f0..0000000 --- a/boards/wr2e/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# WR2E Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr2e?id=K97scnsjhue4h) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wr2e` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 7x GPIO, 4x PWM, 1x UART, 2x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR2E](https://fccid.io/2ANDL-WR2E) - -## Usage - -**Board code:** `wr2e` - -In `platformio.ini`: - -```ini -[env:wr2e] -platform = libretuya -board = wr2e -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr2e - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr2e.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA12 | | | | PWM3 | -D1 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D2 | PA05 | | | | PWM4 | -D3 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D4 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -D5 | PA14 | | | | PWM0 | SWCLK -D6 | PA15 | | | | PWM1 | SWDIO -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr2e/pinout_wr2e.svg b/boards/wr2e/pinout_wr2e.svg deleted file mode 100644 index a0549c7..0000000 --- a/boards/wr2e/pinout_wr2e.svg +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR2E - - - - - - - - - - - - - - - - - - - - - - PA12 - - - - D0 - - - - PWM3 - - - - - PA19 - - - - ADC1 - - - - D1 - - - - A0 - - - - - PA05 - - - - D2 - - - - PWM4 - - - - - ADC2 - - - - A1 - - - - - CEN - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3V3 - - - - - GND - - - - - PA18 - - - - D3 - - - - RX0 - - - - SCL1 - - - - - PA23 - - - - D4 - - - - TX0 - - - - SDA1 - - - - PWM0 - - - - - PA14 - - - - D5 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D6 - - - - PWM1 - - - - SWDIO - diff --git a/boards/wr2e/pins_arduino.h b/boards/wr2e/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr2e/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr2e/variant.h b/boards/wr2e/variant.h deleted file mode 100644 index 290e3be..0000000 --- a/boards/wr2e/variant.h +++ /dev/null @@ -1,62 +0,0 @@ -/* This file was auto-generated from wr2e.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 8 -#define NUM_DIGITAL_PINS 7 -#define NUM_ANALOG_INPUTS 2 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 1u // PA_19 -#define PIN_A1 7u // AD_2 -#define A0 PIN_A0 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 1 -#define PIN_WIRE1_SCL 3u // PA_18 -#define PIN_WIRE1_SDA 4u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 1 -#define PIN_SERIAL0_CTS 1u // PA_19 -#define PIN_SERIAL0_RX 3u // PA_18 -#define PIN_SERIAL0_TX 4u // PA_23 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 1u // PA_19 -#define PIN_FUNCTION_ADC2 7u // AD_2 -#define PIN_FUNCTION_CS0 1u // PA_19 -#define PIN_FUNCTION_CS1 1u // PA_19 -#define PIN_FUNCTION_CTS0 1u // PA_19 -#define PIN_FUNCTION_MOSI0 4u // PA_23 -#define PIN_FUNCTION_MOSI1 4u // PA_23 -#define PIN_FUNCTION_PA05 2u // PA_5 -#define PIN_FUNCTION_PA12 0u // PA_12 -#define PIN_FUNCTION_PA14 5u // PA_14 -#define PIN_FUNCTION_PA15 6u // PA_15 -#define PIN_FUNCTION_PA18 3u // PA_18 -#define PIN_FUNCTION_PA19 1u // PA_19 -#define PIN_FUNCTION_PA23 4u // PA_23 -#define PIN_FUNCTION_RX0 3u // PA_18 -#define PIN_FUNCTION_SCK0 3u // PA_18 -#define PIN_FUNCTION_SCK1 3u // PA_18 -#define PIN_FUNCTION_SCL1 3u // PA_18 -#define PIN_FUNCTION_SDA0 1u // PA_19 -#define PIN_FUNCTION_SDA1 4u // PA_23 -#define PIN_FUNCTION_TX0 4u // PA_23 diff --git a/boards/wr2l/README.md b/boards/wr2l/README.md deleted file mode 100644 index 65e4299..0000000 --- a/boards/wr2l/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# WR2L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wifiwr2lmodule?id=K9605tnbj7gva) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wr2l` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 5x GPIO, 4x PWM, 1x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR2L](https://fccid.io/2ANDL-WR2L) - -## Usage - -**Board code:** `wr2l` - -In `platformio.ini`: - -```ini -[env:wr2l] -platform = libretuya -board = wr2l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr2l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr2l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|------------------|------|------ -D0 | PA15 | | | | PWM1 | SWDIO -D1 | PA14 | | | | PWM0 | SWCLK -D2 | PA05 | | | | PWM4 | -D3 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D4 | PA12 | | | | PWM3 | -A0 | PA19, ADC1 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr2l/pinout_wr2l.svg b/boards/wr2l/pinout_wr2l.svg deleted file mode 100644 index 34f6e6e..0000000 --- a/boards/wr2l/pinout_wr2l.svg +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR2L - - - - - - - - - - - - - - - - - - - - - - PA15 - - - - D0 - - - - PWM1 - - - - SWDIO - - - - - PA14 - - - - D1 - - - - PWM0 - - - - SWCLK - - - - - PA05 - - - - D2 - - - - PWM4 - - - - - PA19 - - - - ADC1 - - - - D3 - - - - A0 - - - - - PA12 - - - - D4 - - - - PWM3 - - - - - GND - - - - - 3V3 - diff --git a/boards/wr2l/pins_arduino.h b/boards/wr2l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr2l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr2l/variant.h b/boards/wr2l/variant.h deleted file mode 100644 index 3e44957..0000000 --- a/boards/wr2l/variant.h +++ /dev/null @@ -1,48 +0,0 @@ -/* This file was auto-generated from wr2l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 5 -#define NUM_DIGITAL_PINS 5 -#define NUM_ANALOG_INPUTS 1 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 3u // PA_19 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 0 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 3u // PA_19 -#define PIN_FUNCTION_CS0 3u // PA_19 -#define PIN_FUNCTION_CS1 3u // PA_19 -#define PIN_FUNCTION_CTS0 3u // PA_19 -#define PIN_FUNCTION_PA05 2u // PA_5 -#define PIN_FUNCTION_PA12 4u // PA_12 -#define PIN_FUNCTION_PA14 1u // PA_14 -#define PIN_FUNCTION_PA15 0u // PA_15 -#define PIN_FUNCTION_PA19 3u // PA_19 -#define PIN_FUNCTION_PWM0 1u // PA_14 -#define PIN_FUNCTION_PWM1 0u // PA_15 -#define PIN_FUNCTION_PWM3 4u // PA_12 -#define PIN_FUNCTION_PWM4 2u // PA_5 -#define PIN_FUNCTION_SDA0 3u // PA_19 diff --git a/boards/wr2le/README.md b/boards/wr2le/README.md deleted file mode 100644 index fb05274..0000000 --- a/boards/wr2le/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# WR2LE Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr2le?id=K9eio9y9e8i8c) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------- -Board code | `wr2le` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 5x GPIO, 5x PWM, 1x UART -Wi-Fi | 802.11 b/g/n - -## Usage - -**Board code:** `wr2le` - -In `platformio.ini`: - -```ini -[env:wr2le] -platform = libretuya -board = wr2le -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr2le - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr2le.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------|-----------|----------|----------------------|------|------ -D0 | PA15 | | | | PWM1 | SWDIO -D1 | PA14 | | | | PWM0 | SWCLK -D2 | PA05 | | | | PWM4 | -D3 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D4 | PA12 | | | | PWM3 | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr2le/pinout_wr2le.svg b/boards/wr2le/pinout_wr2le.svg deleted file mode 100644 index aa10a33..0000000 --- a/boards/wr2le/pinout_wr2le.svg +++ /dev/null @@ -1,153 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR2LE - - - - - - - - - - - - - - - - - - - - - - PA15 - - - - D0 - - - - PWM1 - - - - SWDIO - - - - - PA14 - - - - D1 - - - - PWM0 - - - - SWCLK - - - - - PA05 - - - - D2 - - - - PWM4 - - - - - PA22 - - - - D3 - - - - PWM5 - - - - - PA12 - - - - D4 - - - - PWM3 - - - - - GND - - - - - 3V3 - diff --git a/boards/wr2le/pins_arduino.h b/boards/wr2le/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr2le/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr2le/variant.h b/boards/wr2le/variant.h deleted file mode 100644 index 2d4b8a0..0000000 --- a/boards/wr2le/variant.h +++ /dev/null @@ -1,42 +0,0 @@ -/* This file was auto-generated from wr2le.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 5 -#define NUM_DIGITAL_PINS 5 -#define NUM_ANALOG_OUTPUTS 0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 0 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 0 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_MISO0 3u // PA_22 -#define PIN_FUNCTION_MISO1 3u // PA_22 -#define PIN_FUNCTION_PA05 2u // PA_5 -#define PIN_FUNCTION_PA12 4u // PA_12 -#define PIN_FUNCTION_PA14 1u // PA_14 -#define PIN_FUNCTION_PA15 0u // PA_15 -#define PIN_FUNCTION_PA22 3u // PA_22 -#define PIN_FUNCTION_PWM0 1u // PA_14 -#define PIN_FUNCTION_PWM1 0u // PA_15 -#define PIN_FUNCTION_PWM3 4u // PA_12 -#define PIN_FUNCTION_PWM4 2u // PA_5 -#define PIN_FUNCTION_PWM5 3u // PA_22 -#define PIN_FUNCTION_RTS0 3u // PA_22 -#define PIN_FUNCTION_SCL0 3u // PA_22 diff --git a/boards/wr3/README.md b/boards/wr3/README.md deleted file mode 100644 index cae18a1..0000000 --- a/boards/wr3/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# WR3 Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr3-module-datasheet?id=K9g3ainzbj9z1) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|---------------------------------------- -Board code | `wr3` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR3](https://fccid.io/2ANDL-WR3) - -## Usage - -**Board code:** `wr3` - -In `platformio.ini`: - -```ini -[env:wr3] -platform = libretuya -board = wr3 -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr3 - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr3.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D1 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D2 | PA14 | | | | PWM0 | SWCLK -D3 | PA15 | | | | PWM1 | SWDIO -D4 | PA00 | | | | PWM2 | -D5 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D6 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D7 | PA05 | | | | PWM4 | -D8 | PA12 | | | | PWM3 | -D9 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D10 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr3/pinout_wr3.svg b/boards/wr3/pinout_wr3.svg deleted file mode 100644 index fc5c656..0000000 --- a/boards/wr3/pinout_wr3.svg +++ /dev/null @@ -1,309 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR3 - - - - - - - - - - - - - - - - - - PA22 - - - - D0 - - - - SCL0 - - - - MISO0 - - - - MISO1 - - - - PWM5 - - - - - CEN - - - - - PA19 - - - - ADC1 - - - - D1 - - - - A0 - - - - SDA0 - - - - CS0 - - - - CS1 - - - - - PA14 - - - - D2 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D3 - - - - PWM1 - - - - SWDIO - - - - - PA00 - - - - D4 - - - - PWM2 - - - - - 3V3 - - - - - GND - - - - - ADC2 - - - - A1 - - - - - PA29 - - - - D5 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA30 - - - - D6 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - PA05 - - - - D7 - - - - PWM4 - - - - - PA12 - - - - D8 - - - - PWM3 - - - - - PA18 - - - - D9 - - - - RX0 - - - - SCL1 - - - - SCK0 - - - - SCK1 - - - - - PA23 - - - - D10 - - - - TX0 - - - - SDA1 - - - - MOSI0 - - - - MOSI1 - - - - PWM0 - diff --git a/boards/wr3/pins_arduino.h b/boards/wr3/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr3/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr3/variant.h b/boards/wr3/variant.h deleted file mode 100644 index 89aa47c..0000000 --- a/boards/wr3/variant.h +++ /dev/null @@ -1,83 +0,0 @@ -/* This file was auto-generated from wr3.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 12 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_INPUTS 2 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 1u // PA_19 -#define PIN_A1 11u // AD_2 -#define A0 PIN_A0 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 1u // PA_19 -#define PIN_SPI0_MISO 0u // PA_22 -#define PIN_SPI0_MOSI 10u // PA_23 -#define PIN_SPI0_SCK 9u // PA_18 -#define PIN_SPI1_CS 1u // PA_19 -#define PIN_SPI1_MISO 0u // PA_22 -#define PIN_SPI1_MOSI 10u // PA_23 -#define PIN_SPI1_SCK 9u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 0u // PA_22 -#define PIN_WIRE0_SCL_1 5u // PA_29 -#define PIN_WIRE0_SDA_0 1u // PA_19 -#define PIN_WIRE0_SDA_1 6u // PA_30 -#define PIN_WIRE1_SCL 9u // PA_18 -#define PIN_WIRE1_SDA 10u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 1u // PA_19 -#define PIN_SERIAL0_RTS 0u // PA_22 -#define PIN_SERIAL0_RX 9u // PA_18 -#define PIN_SERIAL0_TX 10u // PA_23 -#define PIN_SERIAL2_RX 5u // PA_29 -#define PIN_SERIAL2_TX 6u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 1u // PA_19 -#define PIN_FUNCTION_ADC2 11u // AD_2 -#define PIN_FUNCTION_CS0 1u // PA_19 -#define PIN_FUNCTION_CS1 1u // PA_19 -#define PIN_FUNCTION_CTS0 1u // PA_19 -#define PIN_FUNCTION_MISO0 0u // PA_22 -#define PIN_FUNCTION_MISO1 0u // PA_22 -#define PIN_FUNCTION_MOSI0 10u // PA_23 -#define PIN_FUNCTION_MOSI1 10u // PA_23 -#define PIN_FUNCTION_PA00 4u // PA_0 -#define PIN_FUNCTION_PA05 7u // PA_5 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 2u // PA_14 -#define PIN_FUNCTION_PA15 3u // PA_15 -#define PIN_FUNCTION_PA18 9u // PA_18 -#define PIN_FUNCTION_PA19 1u // PA_19 -#define PIN_FUNCTION_PA22 0u // PA_22 -#define PIN_FUNCTION_PA23 10u // PA_23 -#define PIN_FUNCTION_PA29 5u // PA_29 -#define PIN_FUNCTION_PA30 6u // PA_30 -#define PIN_FUNCTION_RTS0 0u // PA_22 -#define PIN_FUNCTION_RX0 9u // PA_18 -#define PIN_FUNCTION_RX2 5u // PA_29 -#define PIN_FUNCTION_SCK0 9u // PA_18 -#define PIN_FUNCTION_SCK1 9u // PA_18 -#define PIN_FUNCTION_TX0 10u // PA_23 -#define PIN_FUNCTION_TX2 6u // PA_30 diff --git a/boards/wr3e/README.md b/boards/wr3e/README.md deleted file mode 100644 index d564d2d..0000000 --- a/boards/wr3e/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# WR3E Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr3e-module-datasheet?id=K9elwlqbfosbc) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wr3e` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR3E](https://fccid.io/2ANDL-WR3E) - -## Usage - -**Board code:** `wr3e` - -In `platformio.ini`: - -```ini -[env:wr3e] -platform = libretuya -board = wr3e -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr3e - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr3e.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D1 | PA14 | | | | PWM0 | SWCLK -D2 | PA15 | | | | PWM1 | SWDIO -D3 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D4 | PA00 | | | | PWM2 | -D5 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D6 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D7 | PA05 | | | | PWM4 | -D8 | PA12 | | | | PWM3 | -D9 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D10 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr3e/pinout_wr3e.svg b/boards/wr3e/pinout_wr3e.svg deleted file mode 100644 index f1fc4fd..0000000 --- a/boards/wr3e/pinout_wr3e.svg +++ /dev/null @@ -1,309 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR3E - - - - - - - - - - - - - - - - - - ADC2 - - - - A1 - - - - - CEN - - - - - PA29 - - - - D0 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA14 - - - - D1 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D2 - - - - PWM1 - - - - SWDIO - - - - - PA22 - - - - D3 - - - - SCL0 - - - - MISO0 - - - - MISO1 - - - - PWM5 - - - - - 3V3 - - - - - GND - - - - - PA00 - - - - D4 - - - - PWM2 - - - - - PA30 - - - - D5 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - PA19 - - - - ADC1 - - - - D6 - - - - A0 - - - - SDA0 - - - - CS0 - - - - CS1 - - - - - PA05 - - - - D7 - - - - PWM4 - - - - - PA12 - - - - D8 - - - - PWM3 - - - - - PA18 - - - - D9 - - - - RX0 - - - - SCL1 - - - - SCK0 - - - - SCK1 - - - - - PA23 - - - - D10 - - - - TX0 - - - - SDA1 - - - - MOSI0 - - - - MOSI1 - - - - PWM0 - diff --git a/boards/wr3e/pins_arduino.h b/boards/wr3e/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr3e/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr3e/variant.h b/boards/wr3e/variant.h deleted file mode 100644 index 6ddccc9..0000000 --- a/boards/wr3e/variant.h +++ /dev/null @@ -1,83 +0,0 @@ -/* This file was auto-generated from wr3e.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 12 -#define NUM_ANALOG_INPUTS 2 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A1 11u // AD_2 -#define PIN_A0 6u // PA_19 -#define A1 PIN_A1 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 6u // PA_19 -#define PIN_SPI0_MISO 3u // PA_22 -#define PIN_SPI0_MOSI 10u // PA_23 -#define PIN_SPI0_SCK 9u // PA_18 -#define PIN_SPI1_CS 6u // PA_19 -#define PIN_SPI1_MISO 3u // PA_22 -#define PIN_SPI1_MOSI 10u // PA_23 -#define PIN_SPI1_SCK 9u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 0u // PA_29 -#define PIN_WIRE0_SCL_1 3u // PA_22 -#define PIN_WIRE0_SDA_0 5u // PA_30 -#define PIN_WIRE0_SDA_1 6u // PA_19 -#define PIN_WIRE1_SCL 9u // PA_18 -#define PIN_WIRE1_SDA 10u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 6u // PA_19 -#define PIN_SERIAL0_RTS 3u // PA_22 -#define PIN_SERIAL0_RX 9u // PA_18 -#define PIN_SERIAL0_TX 10u // PA_23 -#define PIN_SERIAL2_RX 0u // PA_29 -#define PIN_SERIAL2_TX 5u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 6u // PA_19 -#define PIN_FUNCTION_ADC2 11u // AD_2 -#define PIN_FUNCTION_CS0 6u // PA_19 -#define PIN_FUNCTION_CS1 6u // PA_19 -#define PIN_FUNCTION_CTS0 6u // PA_19 -#define PIN_FUNCTION_MISO0 3u // PA_22 -#define PIN_FUNCTION_MISO1 3u // PA_22 -#define PIN_FUNCTION_MOSI0 10u // PA_23 -#define PIN_FUNCTION_MOSI1 10u // PA_23 -#define PIN_FUNCTION_PA00 4u // PA_0 -#define PIN_FUNCTION_PA05 7u // PA_5 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 1u // PA_14 -#define PIN_FUNCTION_PA15 2u // PA_15 -#define PIN_FUNCTION_PA18 9u // PA_18 -#define PIN_FUNCTION_PA19 6u // PA_19 -#define PIN_FUNCTION_PA22 3u // PA_22 -#define PIN_FUNCTION_PA23 10u // PA_23 -#define PIN_FUNCTION_PA29 0u // PA_29 -#define PIN_FUNCTION_PA30 5u // PA_30 -#define PIN_FUNCTION_RTS0 3u // PA_22 -#define PIN_FUNCTION_RX0 9u // PA_18 -#define PIN_FUNCTION_RX2 0u // PA_29 -#define PIN_FUNCTION_SCK0 9u // PA_18 -#define PIN_FUNCTION_SCK1 9u // PA_18 -#define PIN_FUNCTION_TX0 10u // PA_23 -#define PIN_FUNCTION_TX2 5u // PA_30 diff --git a/boards/wr3l/README.md b/boards/wr3l/README.md deleted file mode 100644 index e10a350..0000000 --- a/boards/wr3l/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# WR3L Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wifiwr3lmodule?id=K9605tt0kveqm) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wr3l` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR3L](https://fccid.io/2ANDL-WR3L) - -## Usage - -**Board code:** `wr3l` - -In `platformio.ini`: - -```ini -[env:wr3l] -platform = libretuya -board = wr3l -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr3l - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr3l.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D1 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D2 | PA14 | | | | PWM0 | SWCLK -D3 | PA15 | | | | PWM1 | SWDIO -D4 | PA00 | | | | PWM2 | -D5 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D6 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D7 | PA05 | | | | PWM4 | -D8 | PA12 | | | | PWM3 | -D9 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D10 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr3l/pinout_wr3l.svg b/boards/wr3l/pinout_wr3l.svg deleted file mode 100644 index 50a4006..0000000 --- a/boards/wr3l/pinout_wr3l.svg +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR3L - - - - - - - - - - - - - - - - - - PA22 - - - - D0 - - - - SCL0 - - - - MISO0 - - - - MISO1 - - - - PWM5 - - - - - CEN - - - - - PA19 - - - - ADC1 - - - - D1 - - - - A0 - - - - SDA0 - - - - CS0 - - - - CS1 - - - - - PA14 - - - - D2 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D3 - - - - PWM1 - - - - SWDIO - - - - - PA00 - - - - D4 - - - - PWM2 - - - - - 3V3 - - - - - GND - - - - - ADC2 - - - - A1 - - - - - PA29 - - - - D5 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA30 - - - - D6 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - PA05 - - - - D7 - - - - PWM4 - - - - - PA12 - - - - D8 - - - - PWM3 - - - - - PA18 - - - - D9 - - - - RX0 - - - - SCL1 - - - - SCK0 - - - - SCK1 - - - - - PA23 - - - - D10 - - - - TX0 - - - - SDA1 - - - - MOSI0 - - - - MOSI1 - - - - PWM0 - diff --git a/boards/wr3l/pins_arduino.h b/boards/wr3l/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr3l/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr3l/variant.h b/boards/wr3l/variant.h deleted file mode 100644 index ab59b7f..0000000 --- a/boards/wr3l/variant.h +++ /dev/null @@ -1,83 +0,0 @@ -/* This file was auto-generated from wr3l.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 12 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_INPUTS 2 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A0 1u // PA_19 -#define PIN_A1 11u // AD_2 -#define A0 PIN_A0 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 1u // PA_19 -#define PIN_SPI0_MISO 0u // PA_22 -#define PIN_SPI0_MOSI 10u // PA_23 -#define PIN_SPI0_SCK 9u // PA_18 -#define PIN_SPI1_CS 1u // PA_19 -#define PIN_SPI1_MISO 0u // PA_22 -#define PIN_SPI1_MOSI 10u // PA_23 -#define PIN_SPI1_SCK 9u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 0u // PA_22 -#define PIN_WIRE0_SCL_1 5u // PA_29 -#define PIN_WIRE0_SDA_0 1u // PA_19 -#define PIN_WIRE0_SDA_1 6u // PA_30 -#define PIN_WIRE1_SCL 9u // PA_18 -#define PIN_WIRE1_SDA 10u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 1u // PA_19 -#define PIN_SERIAL0_RTS 0u // PA_22 -#define PIN_SERIAL0_RX 9u // PA_18 -#define PIN_SERIAL0_TX 10u // PA_23 -#define PIN_SERIAL2_RX 5u // PA_29 -#define PIN_SERIAL2_TX 6u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 1u // PA_19 -#define PIN_FUNCTION_ADC2 11u // AD_2 -#define PIN_FUNCTION_CS0 1u // PA_19 -#define PIN_FUNCTION_CS1 1u // PA_19 -#define PIN_FUNCTION_CTS0 1u // PA_19 -#define PIN_FUNCTION_MISO0 0u // PA_22 -#define PIN_FUNCTION_MISO1 0u // PA_22 -#define PIN_FUNCTION_MOSI0 10u // PA_23 -#define PIN_FUNCTION_MOSI1 10u // PA_23 -#define PIN_FUNCTION_PA00 4u // PA_0 -#define PIN_FUNCTION_PA05 7u // PA_5 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 2u // PA_14 -#define PIN_FUNCTION_PA15 3u // PA_15 -#define PIN_FUNCTION_PA18 9u // PA_18 -#define PIN_FUNCTION_PA19 1u // PA_19 -#define PIN_FUNCTION_PA22 0u // PA_22 -#define PIN_FUNCTION_PA23 10u // PA_23 -#define PIN_FUNCTION_PA29 5u // PA_29 -#define PIN_FUNCTION_PA30 6u // PA_30 -#define PIN_FUNCTION_RTS0 0u // PA_22 -#define PIN_FUNCTION_RX0 9u // PA_18 -#define PIN_FUNCTION_RX2 5u // PA_29 -#define PIN_FUNCTION_SCK0 9u // PA_18 -#define PIN_FUNCTION_SCK1 9u // PA_18 -#define PIN_FUNCTION_TX0 10u // PA_23 -#define PIN_FUNCTION_TX2 6u // PA_30 diff --git a/boards/wr3le/README.md b/boards/wr3le/README.md deleted file mode 100644 index 6e28e43..0000000 --- a/boards/wr3le/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# WR3LE Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr3le?id=K986l7a1ha8tm) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|-------------------------------------------- -Board code | `wr3le` -MCU | RTL8710BX -Manufacturer | Realtek -Series | AmebaZ -Frequency | 62.5 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 11x GPIO, 6x PWM, 2x UART, 2x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR3LE](https://fccid.io/2ANDL-WR3LE) - -## Usage - -**Board code:** `wr3le` - -In `platformio.ini`: - -```ini -[env:wr3le] -platform = libretuya -board = wr3le -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr3le - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr3le.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------------|-----------|----------|----------------------|------|------ -D0 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D1 | PA14 | | | | PWM0 | SWCLK -D2 | PA15 | | | | PWM1 | SWDIO -D3 | PA22 | UART0_RTS | I2C0_SCL | SPI0_MISO, SPI1_MISO | PWM5 | -D4 | PA00 | | | | PWM2 | -D5 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D6 | PA19 | UART0_CTS | I2C0_SDA | SPI0_CS, SPI1_CS | | -D7 | PA05 | | | | PWM4 | -D8 | PA12 | | | | PWM3 | -D9 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D10 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A0 | PA19, ADC1 | | | | | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr3le/pinout_wr3le.svg b/boards/wr3le/pinout_wr3le.svg deleted file mode 100644 index 2ba22d2..0000000 --- a/boards/wr3le/pinout_wr3le.svg +++ /dev/null @@ -1,325 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR3LE - - - - - - - - - - - - - - - - - - ADC2 - - - - A1 - - - - - CEN - - - - - PA29 - - - - D0 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA14 - - - - D1 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D2 - - - - PWM1 - - - - SWDIO - - - - - PA22 - - - - D3 - - - - SCL0 - - - - MISO0 - - - - MISO1 - - - - PWM5 - - - - - 3V3 - - - - - GND - - - - - PA00 - - - - D4 - - - - PWM2 - - - - - PA30 - - - - D5 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - PA19 - - - - ADC1 - - - - D6 - - - - A0 - - - - SDA0 - - - - CS0 - - - - CS1 - - - - - PA05 - - - - D7 - - - - PWM4 - - - - - PA12 - - - - D8 - - - - PWM3 - - - - - PA18 - - - - D9 - - - - RX0 - - - - SCL1 - - - - SCK0 - - - - SCK1 - - - - - PA23 - - - - D10 - - - - TX0 - - - - SDA1 - - - - MOSI0 - - - - MOSI1 - - - - PWM0 - diff --git a/boards/wr3le/pins_arduino.h b/boards/wr3le/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr3le/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr3le/variant.h b/boards/wr3le/variant.h deleted file mode 100644 index 7e9d8c0..0000000 --- a/boards/wr3le/variant.h +++ /dev/null @@ -1,83 +0,0 @@ -/* This file was auto-generated from wr3le.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 12 -#define NUM_ANALOG_INPUTS 2 -#define NUM_DIGITAL_PINS 11 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A1 11u // AD_2 -#define PIN_A0 6u // PA_19 -#define A1 PIN_A1 -#define A0 PIN_A0 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 2 -#define PIN_SPI0_CS 6u // PA_19 -#define PIN_SPI0_MISO 3u // PA_22 -#define PIN_SPI0_MOSI 10u // PA_23 -#define PIN_SPI0_SCK 9u // PA_18 -#define PIN_SPI1_CS 6u // PA_19 -#define PIN_SPI1_MISO 3u // PA_22 -#define PIN_SPI1_MOSI 10u // PA_23 -#define PIN_SPI1_SCK 9u // PA_18 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL_0 0u // PA_29 -#define PIN_WIRE0_SCL_1 3u // PA_22 -#define PIN_WIRE0_SDA_0 5u // PA_30 -#define PIN_WIRE0_SDA_1 6u // PA_19 -#define PIN_WIRE1_SCL 9u // PA_18 -#define PIN_WIRE1_SDA 10u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_CTS 6u // PA_19 -#define PIN_SERIAL0_RTS 3u // PA_22 -#define PIN_SERIAL0_RX 9u // PA_18 -#define PIN_SERIAL0_TX 10u // PA_23 -#define PIN_SERIAL2_RX 0u // PA_29 -#define PIN_SERIAL2_TX 5u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC1 6u // PA_19 -#define PIN_FUNCTION_ADC2 11u // AD_2 -#define PIN_FUNCTION_CS0 6u // PA_19 -#define PIN_FUNCTION_CS1 6u // PA_19 -#define PIN_FUNCTION_CTS0 6u // PA_19 -#define PIN_FUNCTION_MISO0 3u // PA_22 -#define PIN_FUNCTION_MISO1 3u // PA_22 -#define PIN_FUNCTION_MOSI0 10u // PA_23 -#define PIN_FUNCTION_MOSI1 10u // PA_23 -#define PIN_FUNCTION_PA00 4u // PA_0 -#define PIN_FUNCTION_PA05 7u // PA_5 -#define PIN_FUNCTION_PA12 8u // PA_12 -#define PIN_FUNCTION_PA14 1u // PA_14 -#define PIN_FUNCTION_PA15 2u // PA_15 -#define PIN_FUNCTION_PA18 9u // PA_18 -#define PIN_FUNCTION_PA19 6u // PA_19 -#define PIN_FUNCTION_PA22 3u // PA_22 -#define PIN_FUNCTION_PA23 10u // PA_23 -#define PIN_FUNCTION_PA29 0u // PA_29 -#define PIN_FUNCTION_PA30 5u // PA_30 -#define PIN_FUNCTION_RTS0 3u // PA_22 -#define PIN_FUNCTION_RX0 9u // PA_18 -#define PIN_FUNCTION_RX2 0u // PA_29 -#define PIN_FUNCTION_SCK0 9u // PA_18 -#define PIN_FUNCTION_SCK1 9u // PA_18 -#define PIN_FUNCTION_TX0 10u // PA_23 -#define PIN_FUNCTION_TX2 5u // PA_30 diff --git a/boards/wr3n/README.md b/boards/wr3n/README.md deleted file mode 100644 index 4bfa78e..0000000 --- a/boards/wr3n/README.md +++ /dev/null @@ -1,87 +0,0 @@ -# WR3N Wi-Fi Module - -*by Tuya Inc.* - -[Product page](https://developer.tuya.com/en/docs/iot/wr3n-datasheet?id=K98zdx31ztdge) - -- [General info](../../docs/platform/realtek-amb/README.md) -- [Flashing guide](../../docs/platform/realtek-ambz/flashing.md) -- [Debugging](../../docs/platform/realtek-ambz/debugging.md) - -Parameter | Value --------------|------------------------------------------ -Board code | `wr3n` -MCU | RTL8710BN -Manufacturer | Realtek -Series | AmebaZ -Frequency | 125 MHz -Flash size | 2 MiB -RAM size | 256 KiB -Voltage | 3.0V - 3.6V -I/O | 9x GPIO, 5x PWM, 2x UART, 1x ADC -Wi-Fi | 802.11 b/g/n -FCC ID | [2ANDL-WR3N](https://fccid.io/2ANDL-WR3N) - -## Usage - -**Board code:** `wr3n` - -In `platformio.ini`: - -```ini -[env:wr3n] -platform = libretuya -board = wr3n -framework = arduino -``` - -In ESPHome YAML: - -```yaml -libretuya: - board: wr3n - framework: - version: dev -``` - -## Pinout - -![Pinout](pinout_wr3n.svg) - -## Arduino Core pin mapping - -No. | Pin | UART | IÂČC | SPI | PWM | Other -----|------|----------|----------|----------------------|------|------ -D0 | PA29 | UART2_RX | I2C0_SCL | | PWM4 | -D1 | PA14 | | | | PWM0 | SWCLK -D2 | PA15 | | | | PWM1 | SWDIO -D3 | PA00 | | | | PWM2 | -D4 | PA30 | UART2_TX | I2C0_SDA | | PWM4 | -D5 | PA05 | | | | PWM4 | -D6 | PA12 | | | | PWM3 | -D7 | PA18 | UART0_RX | I2C1_SCL | SPI0_SCK, SPI1_SCK | | -D8 | PA23 | UART0_TX | I2C1_SDA | SPI0_MOSI, SPI1_MOSI | PWM0 | -A1 | ADC2 | | | | | - -## Flash memory map - -Flash size: 2 MiB / 2,097,152 B / 0x200000 - -Hex values are in bytes. - -Name | Start | Length | End -----------------|----------|-------------------|--------- -Boot XIP | 0x000000 | 16 KiB / 0x4000 | 0x004000 -Boot RAM | 0x004000 | 16 KiB / 0x4000 | 0x008000 -(reserved) | 0x008000 | 4 KiB / 0x1000 | 0x009000 -System Data | 0x009000 | 4 KiB / 0x1000 | 0x00A000 -Calibration | 0x00A000 | 4 KiB / 0x1000 | 0x00B000 -OTA1 Image | 0x00B000 | 788 KiB / 0xC5000 | 0x0D0000 -OTA2 Image | 0x0D0000 | 788 KiB / 0xC5000 | 0x195000 -Key-Value Store | 0x195000 | 24 KiB / 0x6000 | 0x19B000 -User Data | 0x19B000 | 400 KiB / 0x64000 | 0x1FF000 -RDP | 0x1FF000 | 4 KiB / 0x1000 | 0x200000 - -RDP is most likely not used in Tuya firmwares, as the System Data partition contains an incorrect offset 0xFF000 for RDP, which is in the middle of OTA2 image. - -Additionally, Tuya firmware uses an encrypted KV or file storage, which resides at the end of flash memory. This seems to overlap system RDP area. diff --git a/boards/wr3n/pinout_wr3n.svg b/boards/wr3n/pinout_wr3n.svg deleted file mode 100644 index 428d398..0000000 --- a/boards/wr3n/pinout_wr3n.svg +++ /dev/null @@ -1,241 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WR3N - - - - - - - - - - - - - - - - - - ADC2 - - - - A1 - - - - - CEN - - - - - PA29 - - - - D0 - - - - RX2 - - - - SCL0 - - - - PWM4 - - - - - PA14 - - - - D1 - - - - PWM0 - - - - SWCLK - - - - - PA15 - - - - D2 - - - - PWM1 - - - - SWDIO - - - - - PA00 - - - - D3 - - - - PWM2 - - - - - 3V3 - - - - - GND - - - - - - PA30 - - - - D4 - - - - TX2 - - - - SDA0 - - - - PWM4 - - - - - - PA05 - - - - D5 - - - - PWM4 - - - - - PA12 - - - - D6 - - - - PWM3 - - - - - PA18 - - - - D7 - - - - RX0 - - - - SCL1 - - - - - PA23 - - - - D8 - - - - TX0 - - - - SDA1 - - - - PWM0 - diff --git a/boards/wr3n/pins_arduino.h b/boards/wr3n/pins_arduino.h deleted file mode 100644 index 1de3ade..0000000 --- a/boards/wr3n/pins_arduino.h +++ /dev/null @@ -1 +0,0 @@ -#include "variant.h" diff --git a/boards/wr3n/variant.h b/boards/wr3n/variant.h deleted file mode 100644 index 38645fb..0000000 --- a/boards/wr3n/variant.h +++ /dev/null @@ -1,64 +0,0 @@ -/* This file was auto-generated from wr3n.json using boardgen */ - -#pragma once - -#include - -// clang-format off - -// Pins -// ---- -#define PINS_COUNT 10 -#define NUM_ANALOG_INPUTS 1 -#define NUM_DIGITAL_PINS 9 -#define NUM_ANALOG_OUTPUTS 0 - -// Analog pins -// ----------- -#define PIN_A1 9u // AD_2 -#define A1 PIN_A1 - -// SPI Interfaces -// -------------- -#define SPI_INTERFACES_COUNT 0 - -// Wire Interfaces -// --------------- -#define WIRE_INTERFACES_COUNT 2 -#define PIN_WIRE0_SCL 0u // PA_29 -#define PIN_WIRE0_SDA 4u // PA_30 -#define PIN_WIRE1_SCL 7u // PA_18 -#define PIN_WIRE1_SDA 8u // PA_23 - -// Serial ports -// ------------ -#define SERIAL_INTERFACES_COUNT 2 -#define PIN_SERIAL0_RX 7u // PA_18 -#define PIN_SERIAL0_TX 8u // PA_23 -#define PIN_SERIAL2_RX 0u // PA_29 -#define PIN_SERIAL2_TX 4u // PA_30 - -// Pin function macros -// ------------------- -#define PIN_FUNCTION_ADC2 9u // AD_2 -#define PIN_FUNCTION_MOSI0 8u // PA_23 -#define PIN_FUNCTION_MOSI1 8u // PA_23 -#define PIN_FUNCTION_PA00 3u // PA_0 -#define PIN_FUNCTION_PA05 5u // PA_5 -#define PIN_FUNCTION_PA12 6u // PA_12 -#define PIN_FUNCTION_PA14 1u // PA_14 -#define PIN_FUNCTION_PA15 2u // PA_15 -#define PIN_FUNCTION_PA18 7u // PA_18 -#define PIN_FUNCTION_PA23 8u // PA_23 -#define PIN_FUNCTION_PA29 0u // PA_29 -#define PIN_FUNCTION_PA30 4u // PA_30 -#define PIN_FUNCTION_RX0 7u // PA_18 -#define PIN_FUNCTION_RX2 0u // PA_29 -#define PIN_FUNCTION_SCK0 7u // PA_18 -#define PIN_FUNCTION_SCK1 7u // PA_18 -#define PIN_FUNCTION_SCL0 0u // PA_29 -#define PIN_FUNCTION_SCL1 7u // PA_18 -#define PIN_FUNCTION_SDA0 4u // PA_30 -#define PIN_FUNCTION_SDA1 8u // PA_23 -#define PIN_FUNCTION_TX0 8u // PA_23 -#define PIN_FUNCTION_TX2 4u // PA_30 diff --git a/builder/arduino-common.py b/builder/arduino-common.py deleted file mode 100644 index 3cb2879..0000000 --- a/builder/arduino-common.py +++ /dev/null @@ -1,167 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-04-23. - -from os.path import isdir, join - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() -platform = env.PioPlatform() - -API_DIR = platform.get_package_dir("framework-arduino-api") -LT_ARDUINO_DIR = join(platform.get_dir(), "arduino", "libretuya") -assert isdir(API_DIR) -assert isdir(LT_ARDUINO_DIR) - -# Flags -env.Append( - CPPDEFINES=[ - ("LIBRETUYA_ARDUINO", "1"), - ("ARDUINO", 10812), - "ARDUINO_SDK", - ], - 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 port/printf/ - "-Wl,-wrap,putchar", - "-Wl,-wrap,puts", - # 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") - -# Sources - ArduinoCore-API -env.AddLibrary( - name="arduino_api", - base_dir=API_DIR, - srcs=[ - "+", - "+", - "+", - "+", - "+", - "+", - ], - includes=[ - "!<.>", - "!", - ], -) - -# Sources - LibreTuya API -env.AddLibrary( - name="libretuya_api", - base_dir=LT_ARDUINO_DIR, - srcs=[ - "+", - "+", - "+", - "+", - "+", - "+", - ], - includes=[ - "!<.>", - "!", - "!", - "!", - "!", - "!", - ], -) - -# Sources - uf2ota library -ltchiptool_dir = platform.get_package_dir(f"tool-ltchiptool") -env.AddLibrary( - name="uf2ota", - base_dir=ltchiptool_dir, - srcs=[ - "+", - ], - includes=[ - "+<.>", - ], -) - -# Sources - board variant -env.AddLibrary( - name="board_${VARIANT}", - base_dir="$BOARD_DIR", - srcs=[ - "+", - ], -) - -for code, base_dir in env["ARDUINO_DIRS"].items(): - code = env.subst(code) - base_dir = env.subst(base_dir) - if not code or not isdir(base_dir): - # Skip unused paths - continue - - # Sources - Arduino Core - env.AddLibrary( - name=f"{code}_arduino_core", - base_dir=base_dir, - srcs=[ - # Wiring core - "+", - "+", - ], - includes=[ - # prepend these as the Arduino core may be incorrectly picking some includes from SDKs - "!", - ], - ) - - # Sources - Arduino libraries - env.AddLibrary( - name=f"{code}_arduino_libs", - base_dir=base_dir, - srcs=[ - "+", - ], - includes=[ - "+", - ], - ) - - # Sources - external library ports - env.AddLibrary( - name=f"{code}_arduino_port", - base_dir=base_dir, - srcs=[ - "+", - ], - includes=[ - "+", - ], - ) - -# Sources - external library ports -env.AddLibraryFlashDB(version="03500fa") -env.AddLibraryPrintf(version="6.0.0") - -# Libs & linker config -env.Append( - LIBS=[ - "stdc++", - "supc++", - ], -) -env.Replace( - # Change to Arduino linker script - LDSCRIPT_PATH=["${LDSCRIPT_ARDUINO}"], -) - -# Build all libraries -env.BuildLibraries(safe=False) diff --git a/builder/frameworks/beken-72xx-sdk.py b/builder/family/beken-72xx.py similarity index 75% rename from builder/frameworks/beken-72xx-sdk.py rename to builder/family/beken-72xx.py index 26f0220..167b438 100644 --- a/builder/frameworks/beken-72xx-sdk.py +++ b/builder/family/beken-72xx.py @@ -2,11 +2,13 @@ from os.path import join -from ltchiptool.soc.bk72xx.binary import to_offset -from SCons.Script import Builder, DefaultEnvironment +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import DefaultEnvironment, Environment -env = DefaultEnvironment() -board = env.BoardConfig() +env: Environment = DefaultEnvironment() +board: PlatformBoardConfig = env.BoardConfig() +queue = env.AddLibraryQueue("beken-72xx") +env.ConfigureFamily() ROOT_DIR = join("$SDK_DIR", "beken378") APP_DIR = join(ROOT_DIR, "app") @@ -14,7 +16,7 @@ DRIVER_DIR = join(ROOT_DIR, "driver") FUNC_DIR = join(ROOT_DIR, "func") # Load sys_config.h into env -env.LoadConfig(join("$FAMILY_DIR", "config", "sys_config.h")) +env.LoadConfig(join("$FAMILY_DIR", "base", "config", "sys_config.h")) # Define vars used during build SOC_BK7231 = 1 @@ -36,47 +38,20 @@ SOC = env.Cfg("CFG_SOC_NAME") WPA_VERSION = "wpa_supplicant_2_9" if env.Cfg("CFG_USE_WPA_29") else "hostapd-2.5" # Flags -env.Append( +queue.AppendPublic( CCFLAGS=[ "-mcpu=arm968e-s", "-march=armv5te", "-mthumb", "-mthumb-interwork", - "-g", + "-Wno-write-strings", + "-Wno-attributes", # anything higher, like -O2 or -Os, causes random issues # like bootlooping, missing (blank) strings, random lockups during boot - "-O1", - "-fdata-sections", - "-ffunction-sections", - "-fno-inline-functions", - "-fno-strict-aliasing", - "-fsigned-char", - "-fno-delete-null-pointer-checks", - "-Wno-comment", - ], - CFLAGS=[ - "-std=gnu99", - "-nostdlib", - "-Wall", - "-Wno-format", - "-Wno-unknown-pragmas", - "-Werror=implicit-function-declaration", - ], - CXXFLAGS=[ - "-std=gnu++11", - "-MMD", - "-fno-exceptions", - "-fno-rtti", - "-Wno-literal-suffix", - "-Wno-psabi", - "-Wno-return-type", + "+<-O1>", + "-<-Os>", ], CPPDEFINES=[ - # LibreTuya configuration - ("LT_HAS_LWIP", "1"), - ("LT_HAS_LWIP2", "1"), - ("LT_HAS_FREERTOS", "1"), - ("LT_HAS_MBEDTLS", "1"), # SDK options ("CFG_OS_FREERTOS", "1"), ("MBEDTLS_CONFIG_FILE", r"\"tls_config.h\""), @@ -98,42 +73,44 @@ env.Append( "-mcpu=arm968e-s", "-marm", "-mthumb-interwork", - "-g", - "-nostartfiles", "--specs=nano.specs", - "-Wl,--gc-sections", - "-Wl,-wrap,_free_r", - "-Wl,-wrap,_malloc_r", - "-Wl,-wrap,calloc", - "-Wl,-wrap,free", - "-Wl,-wrap,malloc", - "-Wl,-wrap,realloc", - "-Wl,-wrap,zalloc", - "-Wl,-wrap,_realloc_r", - "-Wl,-wrap,printf", - "-Wl,-wrap,puts", - "-Wl,-wrap,snprintf", - "-Wl,-wrap,sprintf", - "-Wl,-wrap,vsnprintf", "-Wl,-wrap,bk_flash_get_info", "-Wl,-wrap,bk_flash_erase", "-Wl,-wrap,bk_flash_write", "-Wl,-wrap,bk_flash_read", + # stdio wrappers (base/port/printf.c) + "-Wl,-wrap,bk_printf", + ], +) +queue.AppendPrivate( + CCFLAGS=[ + "-Wno-comment", + "-Wno-char-subscripts", + "-Wno-missing-braces", + "-Wno-return-type", + ], + CFLAGS=[ + "-Wno-format", + "-Wno-unknown-pragmas", ], ) srcs_core = [] -srcs_fixups = [] # Fix for BK7231T's bootloader compatibility if board.get("build.bkboot_version") == "1.0.5-bk7231s": - env.Append(CPPDEFINES=[("CFG_SUPPORT_BOOTLOADER", "1")]) - srcs_fixups.append("+") + # this has to be public, so that fixups/intc.c sees it + queue.AppendPublic(CPPDEFINES=[("CFG_SUPPORT_BOOTLOADER", "1")]) + queue.AddLibrary( + name="bdk_boot", + base_dir="$FAMILY_DIR/base/fixups", + srcs=["+"], + ) else: srcs_core.append("+") # Sources - from framework-beken-bdk/beken378/beken_src.mk -env.AddLibrary( +queue.AddLibrary( name="bdk_core", base_dir=ROOT_DIR, srcs=[ @@ -154,32 +131,8 @@ env.AddLibrary( ], ) -# Sources - parent family fixups -env.AddLibrary( - name="${FAMILY_PARENT_CODE}_fixups", - base_dir="$PARENT_DIR/fixups", - srcs=[ - "+", - "+", - "+", - "+", - "+", - "+", - *srcs_fixups, - ], -) - -# Sources - family fixups -env.AddLibrary( - name="${FAMILY_CODE}_fixups", - base_dir="$FAMILY_DIR/fixups", - srcs=[ - "+", - ], -) - # Sources - app module -env.AddLibrary( +queue.AddLibrary( name="bdk_app", base_dir=APP_DIR, srcs=[ @@ -199,7 +152,7 @@ env.AddLibrary( ) # Sources - drivers -env.AddLibrary( +queue.AddLibrary( name="bdk_driver", base_dir=DRIVER_DIR, srcs=[ @@ -227,7 +180,7 @@ env.AddLibrary( "+", "+", "+", - "+", + "+", "+", ], includes=[ @@ -256,7 +209,7 @@ env.AddLibrary( ) # Sources - functional components -env.AddLibrary( +queue.AddLibrary( name="bdk_func", base_dir=FUNC_DIR, srcs=[ @@ -320,66 +273,55 @@ env.AddLibrary( ) # Sources - FreeRTOS -env.AddLibrary( +freertos_opts = dict( + CCFLAGS=[ + # build FreeRTOS port in ARM mode + "+<-marm>", + "-<-mthumb>", + ], +) +env.Replace(FREERTOS_PORT="beken-bdk", FREERTOS_PORT_DEFINE="BEKEN_BDK") +queue.AddExternalLibrary("freertos", options=freertos_opts) +queue.AddExternalLibrary("freertos-port", options=freertos_opts) +queue.AddLibrary( name="bdk_freertos_thumb", base_dir=ROOT_DIR, srcs=[ "+", + "-", ], includes=[ "+", ], ) -env.AddLibrary( - name="bdk_freertos_arm", - base_dir="$SDK_DIR", - srcs=[ - "+", - ], - includes=[ - "+", - "+", - ], - options=dict( - CCFLAGS=[ - # build FreeRTOS port in ARM mode - "+<-marm>", - "-<-mthumb>", - ], - ), -) -# Sources - lwIP 2.1.3 -env.AddLibraryLwIP(version="2.1.3", port="bdk") +# Sources - lwIP +queue.AddExternalLibrary("lwip", port="bdk") # Sources - mbedTLS 2.6.0 -env.AddLibrary( +queue.AddLibrary( name="bdk_mbedtls", base_dir=join(FUNC_DIR, "mbedtls"), srcs=[ "+", - "+", "+", ], includes=[ "+", - "+", "+", ], options=dict( CCFLAGS=[ "-Wno-unused-variable", "-Wno-implicit-function-declaration", - "-Wno-incompatible-pointer-types", - "-Wno-int-conversion", + "-w", ], - CFLAGS=["-<-Wall>"], ), ) # Sources - chip-specific drivers if SOC in [SOC_BK7231U, SOC_BK7251]: - env.AddLibrary( + queue.AddLibrary( name="bdk_driver_spi", base_dir=join(DRIVER_DIR, "spi"), srcs=[ @@ -389,7 +331,7 @@ if SOC in [SOC_BK7231U, SOC_BK7251]: ], ) if SOC in [SOC_BK7231N]: - env.AddLibrary( + queue.AddLibrary( name="bdk_driver_spi", base_dir=join(DRIVER_DIR, "spi"), srcs=[ @@ -399,7 +341,7 @@ if SOC in [SOC_BK7231N]: ], ) if SOC in [SOC_BK7251]: - env.AddLibrary( + queue.AddLibrary( name="bdk_bk7251", base_dir=ROOT_DIR, srcs=[ @@ -416,7 +358,7 @@ if SOC in [SOC_BK7251]: # Sources - enabled through config if env.Cfg("CFG_SDIO"): - env.AddLibrary( + queue.AddLibrary( name="bdk_driver_sdio", base_dir=ROOT_DIR, srcs=[ @@ -425,7 +367,7 @@ if env.Cfg("CFG_SDIO"): ], ) if env.Cfg("CFG_BK_AWARE"): - env.AddLibrary( + queue.AddLibrary( name="bdk_driver_sdio", base_dir="$SDK_DIR", srcs=[ @@ -437,7 +379,7 @@ if env.Cfg("CFG_BK_AWARE"): ], ) if env.Cfg("CFG_USE_SDCARD_HOST"): - env.AddLibrary( + queue.AddLibrary( name="bdk_func_fatfs", base_dir=join(FUNC_DIR, "fatfs"), srcs=[ @@ -449,7 +391,7 @@ if env.Cfg("CFG_USE_SDCARD_HOST"): ], ) if env.Cfg("CFG_WPA3"): - env.AddLibrary( + queue.AddLibrary( name="bdk_wolfssl", base_dir=join(FUNC_DIR, "wolfssl"), srcs=[ @@ -467,7 +409,7 @@ if env.Cfg("CFG_WPA3"): if env.Cfg("CFG_SUPPORT_BLE") and env.Cfg("CFG_BLE_VERSION") == env.Cfg( "BLE_VERSION_4_2" ): - env.AddLibrary( + queue.AddLibrary( name="bdk_ble_4_2", base_dir=join(DRIVER_DIR, "ble"), srcs=[ @@ -487,7 +429,7 @@ if env.Cfg("CFG_SUPPORT_BLE") and env.Cfg("CFG_BLE_VERSION") == env.Cfg( if env.Cfg("CFG_SUPPORT_BLE") and env.Cfg("CFG_BLE_VERSION") == env.Cfg( "BLE_VERSION_5_x" ): - env.AddLibrary( + queue.AddLibrary( name="bdk_ble_5_x", base_dir=join(DRIVER_DIR, "ble_5_x_rw"), srcs=[ @@ -509,7 +451,7 @@ if env.Cfg("CFG_SUPPORT_BLE") and env.Cfg("CFG_BLE_VERSION") == env.Cfg( ], ) if env.Cfg("ATSVR_CFG"): - env.AddLibrary( + queue.AddLibrary( name="bdk_atsvr", base_dir=join(FUNC_DIR, "at_server"), srcs=[ @@ -521,7 +463,7 @@ if env.Cfg("ATSVR_CFG"): ], ) if env.Cfg("CFG_USB") or env.Cfg("CFG_USE_SDCARD_HOST"): - env.AddLibrary( + queue.AddLibrary( name="bdk_driver_usb", base_dir=ROOT_DIR, srcs=[ @@ -534,7 +476,7 @@ if env.Cfg("CFG_USB") or env.Cfg("CFG_USE_SDCARD_HOST"): ) # Libs & linker config -env.Append( +queue.AppendPublic( LIBPATH=[ join("$SDK_DIR", "beken378", "lib"), join("$SDK_DIR", "beken378", "func", "airkiss"), @@ -566,6 +508,13 @@ env.Replace( SIZECHECKCMD="$SIZETOOL -A -d $SOURCES", SIZEPRINTCMD="$SIZETOOL -B -d $SOURCES", ) +# Generate linker scripts with correct flash offsets +env.GenerateLinkerScript(board, board.get("build.ldscript")) + + +def to_offset(addr: int) -> int: + return int(addr + (addr // 32) * 2) + # Calculate RBL header offset app_offs = int(env["FLASH_APP_OFFSET"], 16) @@ -574,34 +523,29 @@ rbl_offs = to_offset(app_size) - 102 env.Replace(FLASH_RBL_OFFSET=f"0x{app_offs + rbl_offs:06X}") # Build all libraries -env.BuildLibraries() +queue.BuildLibraries() -# Main firmware outputs and actions -env.Replace( - # linker command (encryption + packaging) - LINK="${LTCHIPTOOL} link2bin ${VARIANT} '' ''", - # UF2OTA input list - UF2OTA=[ - # app binary image (enc+crc), OTA1 (uploader) only - ( - "app", - "${BUILD_DIR}/${MCULC}_app_${FLASH_APP_OFFSET}.crc", - "", - "", - ), - # app RBL header (crc), OTA1 (uploader) only - ( - f"app+{rbl_offs}", - "${BUILD_DIR}/${MCULC}_app_${FLASH_RBL_OFFSET}.rblh", - "", # not used for OTA2 - "", - ), - # OTA RBL package, OTA2 (uf2ota lib) only - ( - "", # not used for OTA1 - "", - "download", - "${BUILD_DIR}/${MCULC}_app.ota.rbl", - ), +# Rename Arduino's delay() to delayMilliseconds() +env.Append( + CPPDEFINES=[ + ("delay", "delayMilliseconds"), + ], +) + +# Main firmware outputs and actions +image_app_crc = "${BUILD_DIR}/image_${MCULC}_app.${FLASH_APP_OFFSET}.crc" +image_app_rblh = "${BUILD_DIR}/image_${MCULC}_app.${FLASH_RBL_OFFSET}.rblh" +image_ota_rbl = "${BUILD_DIR}/image_${MCULC}_app.ota.rbl" +env.Replace( + # linker command (encryption + packaging) + LINK="${LTCHIPTOOL} link2bin ${BOARD_JSON} '' ''", + # UF2OTA input list + UF2OTA=[ + # app binary image (enc+crc) for flasher + f"{image_app_crc}=flasher:app", + # app RBL header (with crc) for flasher + f"{image_app_rblh}+{rbl_offs}=flasher:app", + # OTA RBL package for device only + f"{image_ota_rbl}=device:download", ], ) diff --git a/builder/frameworks/realtek-ambz-sdk.py b/builder/family/realtek-ambz.py similarity index 74% rename from builder/frameworks/realtek-ambz-sdk.py rename to builder/family/realtek-ambz.py index dd18cf5..38b3c67 100644 --- a/builder/frameworks/realtek-ambz-sdk.py +++ b/builder/family/realtek-ambz.py @@ -2,50 +2,24 @@ from os.path import join -from SCons.Script import Builder, DefaultEnvironment +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import Builder, DefaultEnvironment, Environment -env = DefaultEnvironment() -board = env.BoardConfig() +env: Environment = DefaultEnvironment() +board: PlatformBoardConfig = env.BoardConfig() +queue = env.AddLibraryQueue("realtek-ambz") +env.ConfigureFamily() # Flags -env.Append( +queue.AppendPublic( CCFLAGS=[ "-mcpu=cortex-m4", "-mthumb", "-mfloat-abi=hard", "-mfpu=fpv4-sp-d16", - "-g2", - "-w", - "-Os", - "-fdata-sections", - "-ffunction-sections", - "-fno-inline-functions", - "-fmessage-length=0", - "-fno-common", "-fno-short-enums", - "-fomit-frame-pointer", - "-fsigned-char", - "-fno-delete-null-pointer-checks", - ], - CFLAGS=[ - "-std=gnu99", - "-Wno-pointer-sign", - ], - CXXFLAGS=[ - # borrowed from RtlDuino/development/rtl87xx/platform.txt - "-std=gnu++11", - "-MMD", - "-fno-exceptions", - "-fno-rtti", - "-Wno-psabi", ], CPPDEFINES=[ - # LibreTuya configuration - ("LT_HAS_LWIP", "1"), - ("LT_HAS_LWIP2", "1"), - ("LT_HAS_FREERTOS", "1"), - ("LT_HAS_MBEDTLS", "1"), - ("LT_PRINTF_BROKEN", "1"), # printf does not handle %.3f properly # other options "M3", "CONFIG_PLATFORM_8711B", @@ -59,18 +33,11 @@ env.Append( "-mthumb", "-mfloat-abi=hard", "-mfpu=fpv4-sp-d16", - "-g", "--specs=nano.specs", - "-nostartfiles", - "-Os", - "-Wl,--gc-sections", - "-Wl,--cref", + # the entrypoint in ROM (?) "-Wl,--entry=Reset_Handler", - "-Wl,--no-enum-size-warning", - "-Wl,--no-wchar-size-warning", - "-Wl,-wrap,malloc", - "-Wl,-wrap,free", - "-Wl,-wrap,realloc", + # start function table in startup.c + "-Wl,--undefined=gImage2EntryFun0", "-Wl,-wrap,rom_psk_CalcGTK", "-Wl,-wrap,rom_psk_CalcPTK", "-Wl,-wrap,CalcMIC", @@ -78,13 +45,61 @@ env.Append( "-Wl,-wrap,aes_80211_encrypt", "-Wl,-wrap,aes_80211_decrypt", "-Wl,-wrap,DecGTK", + # ROM stdlib (wraps/stdlib.c) + # stock SDK defines these as macros + "-Wl,-wrap,atoi", + "-Wl,-wrap,atol", + "-Wl,-wrap,strtol", + "-Wl,-wrap,strtoul", + "-Wl,-wrap,rand", + "-Wl,-wrap,strcat", + "-Wl,-wrap,strcpy", + "-Wl,-wrap,strncat", + "-Wl,-wrap,strncpy", + "-Wl,-wrap,strchr", + "-Wl,-wrap,strcmp", + "-Wl,-wrap,strlen", + "-Wl,-wrap,strncmp", + "-Wl,-wrap,strpbrk", + "-Wl,-wrap,strstr", + "-Wl,-wrap,strtok", + "-Wl,-wrap,memchr", + "-Wl,-wrap,memcmp", + "-Wl,-wrap,memcpy", + "-Wl,-wrap,memmove", + "-Wl,-wrap,memset", + "-Wl,-wrap,strsep", + # stdio wrappers (base/port/printf.c) + "-Wl,-wrap,rtl_printf", + "-Wl,-wrap,rtl_sprintf", + "-Wl,-wrap,rtl_snprintf", + "-Wl,-wrap,rtl_vsnprintf", + "-Wl,-wrap,rtl_vsnprintf_r", + "-Wl,-wrap,rtl_vprintf", + "-Wl,-wrap,rtl_vfprintf", + "-Wl,-wrap,DiagPrintf", + "-Wl,-wrap,DiagSPrintf", + "-Wl,-wrap,DiagSnPrintf", + "-Wl,-wrap,prvDiagPrintf", + "-Wl,-wrap,prvDiagSPrintf", + "-Wl,-wrap,VSprintf", + "-Wl,-wrap,LOG_PRINTF", + "-Wl,-wrap,__rtl_vfprintf_r_v1_00", + ], +) +queue.AppendPrivate( + CFLAGS=[ + "-Wno-implicit-function-declaration", + "-Wno-incompatible-pointer-types", + "-Wno-int-conversion", + "-Wno-pointer-sign", ], ) # Sources - from SDK project/realtek_amebaz_va0_example/GCC-RELEASE/application.mk # - "console" is disabled as it introduces build error, and is generally useless # - "utilities example" are also not really needed -env.AddLibrary( +queue.AddLibrary( name="ambz_sdk", base_dir="$SDK_DIR", srcs=[ @@ -97,7 +112,7 @@ env.AddLibrary( "+", "+", "+", - "+", + "ARDUINO" not in "ENV" and "+", "+", "+", "+", @@ -105,17 +120,8 @@ env.AddLibrary( "+", "+", "+", - "+", - "+", - # "+", "+", - "+", - "+", "+", - "+", - "+", - "+", - "+", "+", "+", "+", @@ -153,8 +159,6 @@ env.AddLibrary( includes=[ "+", "+", - "+", - "+", "+", "+", "+", @@ -195,43 +199,36 @@ env.AddLibrary( "+", "+", ], + options=dict( + CFLAGS=["-w"], + ), ) -# Sources - lwIP 2.1.3 -env.AddLibraryLwIP(version="2.1.3", port="amb1") +# Sources - FreeRTOS +env.Replace(FREERTOS_PORT=env["FAMILY_NAME"], FREERTOS_PORT_DEFINE="REALTEK_AMB1") +queue.AddExternalLibrary("freertos") +queue.AddExternalLibrary("freertos-port") + +# Sources - lwIP +queue.AddExternalLibrary("lwip", port="amb1") # Sources - mbedTLS -env.AddLibrary( +queue.AddLibrary( name="ambz_mbedtls", base_dir="$SDK_DIR", srcs=[ # mbedTLS from SDK "+", - # replace these with fixups + # replace this with a fixup "-", - "-", ], includes=[ "+", ], ) -# Sources - family fixups -env.AddLibrary( - name="ambz_fixups", - base_dir="$FAMILY_DIR/fixups", - srcs=[ - "+", - "+", - "+", - "+", # fix non-blocking sockets (Realtek disabled this for unknown reason) - "+", # rtl sdk defines S1 and S2 which conflicts here - "+", - ], -) - # Libs & linker config -env.Append( +queue.AppendPublic( LIBPATH=[ # fmt: off join("$SDK_DIR", "component", "soc", "realtek", "8711b", "misc", "bsp", "lib", "common", "GCC"), @@ -262,6 +259,9 @@ env.Replace( SIZECHECKCMD="$SIZETOOL -A -d $SOURCES", SIZEPRINTCMD="$SIZETOOL -B -d $SOURCES", ) +# Generate linker scripts with correct flash offsets +env.GenerateLinkerScript(board, board.get("build.ldscript")) +env.GenerateLinkerScript(board, board.get("build.ldscript").replace("xip1", "xip2")) env.Append( BUILDERS=dict( @@ -286,27 +286,23 @@ target_boot = env.StaticLibrary( join("$BUILD_DIR", "boot_all"), env.BinToObj( join("$BUILD_DIR", "boot_all.o"), - join("$BIN_DIR", boot_all), + join("$MISC_DIR", boot_all), ), ) env.Prepend(LIBS=[target_boot]) # Build all libraries -env.BuildLibraries() +queue.BuildLibraries() # Main firmware outputs and actions +image_ota1 = "${BUILD_DIR}/image_ota1.${FLASH_OTA1_OFFSET}.bin" +image_ota2 = "${BUILD_DIR}/image_ota2.${FLASH_OTA2_OFFSET}.bin" env.Replace( # linker command (dual .bin outputs) - LINK="${LTCHIPTOOL} link2bin ${VARIANT} xip1 xip2", - # default output .bin name - IMG_FW="image_${FLASH_OTA1_OFFSET}.ota1.bin", + LINK="${LTCHIPTOOL} link2bin ${BOARD_JSON} xip1 xip2", # UF2OTA input list UF2OTA=[ - ( - "ota1", - "${BUILD_DIR}/image_${FLASH_OTA1_OFFSET}.ota1.bin", - "ota2", - "${BUILD_DIR}/image_${FLASH_OTA2_OFFSET}.ota2.bin", - ), + # same OTA images for flasher and device + f"{image_ota1},{image_ota2}=device:ota1,ota2;flasher:ota1,ota2", ], ) diff --git a/builder/frameworks/realtek-ambz2-sdk.py b/builder/family/realtek-ambz2.py similarity index 88% rename from builder/frameworks/realtek-ambz2-sdk.py rename to builder/family/realtek-ambz2.py index 0d80ea0..2cab2fe 100644 --- a/builder/frameworks/realtek-ambz2-sdk.py +++ b/builder/family/realtek-ambz2.py @@ -2,53 +2,36 @@ from os.path import join -from SCons.Script import Builder, DefaultEnvironment +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import DefaultEnvironment, Environment -env = DefaultEnvironment() -board = env.BoardConfig() +env: Environment = DefaultEnvironment() +platform: PlatformBase = env.PioPlatform() +board: PlatformBoardConfig = env.BoardConfig() +queue = env.AddLibraryQueue("realtek-ambz2") +env.ConfigureFamily() COMPONENT_DIR = join("$SDK_DIR", "component") # Flags -env.Append( +queue.AppendPublic( CCFLAGS=[ "-march=armv8-m.main+dsp", "-mthumb", "-mcmse", "-mfloat-abi=soft", - "-g", - "-gdwarf-3", - "-Os", - "-MMD", - "-fstack-usage", - "-fdata-sections", - "-ffunction-sections", - "-fmessage-length=0", - "-fno-common", "-fno-short-enums", - "-fomit-frame-pointer", - "-fsigned-char", ], CFLAGS=[ - "-std=gnu99", - "-Wall", "-Wpointer-arith", - "-Wundef", "-Wno-write-strings", "-Wno-maybe-uninitialized", ], CXXFLAGS=[ - "-std=c++11", - "-fno-exceptions", - "-fno-rtti", "-fno-use-cxa-atexit", ], CPPDEFINES=[ - # LibreTuya configuration - ("LT_HAS_LWIP", "1"), - ("LT_HAS_LWIP2", "1"), - ("LT_HAS_FREERTOS", "1"), - ("LT_HAS_MBEDTLS", "1"), # other options "__thumb2__", "CONFIG_PLATFORM_8710C", @@ -56,70 +39,22 @@ env.Append( ("CONFIG_BUILD_RAM", "1"), "V8M_STKOVF", ], + CPPPATH=[ + # allow including from GCC instead of RTL SDK + join( + platform.get_package_dir("toolchain-gccarmnoneeabi"), + "arm-none-eabi", + "include", + ), + ], LINKFLAGS=[ "-march=armv8-m.main+dsp", "-mthumb", "-mcmse", "-mfloat-abi=soft", - "-g", "--specs=nosys.specs", - "-nostartfiles", - "-nodefaultlibs", - "-nostdlib", - "-Os", - "-Wl,--gc-sections", - "-Wl,--warn-section-align", - "-Wl,--cref", - "-Wl,--build-id=none", "-Wl,--use-blx", - "-Wl,-no-enum-size-warning", - # TODO fix wraps - "-Wl,-wrap,strcat", - "-Wl,-wrap,strchr", - "-Wl,-wrap,strcmp", - "-Wl,-wrap,strncmp", - "-Wl,-wrap,strnicmp", - "-Wl,-wrap,strcpy", - "-Wl,-wrap,strncpy", - "-Wl,-wrap,strlcpy", - "-Wl,-wrap,strlen", - "-Wl,-wrap,strnlen", - "-Wl,-wrap,strncat", - "-Wl,-wrap,strpbrk", - "-Wl,-wrap,strspn", - "-Wl,-wrap,strstr", - "-Wl,-wrap,strtok", - "-Wl,-wrap,strxfrm", - "-Wl,-wrap,strsep", - "-Wl,-wrap,strtod", - "-Wl,-wrap,strtof", - "-Wl,-wrap,strtold", - "-Wl,-wrap,strtoll", - "-Wl,-wrap,strtoul", - "-Wl,-wrap,strtoull", - "-Wl,-wrap,atoi", - "-Wl,-wrap,atoui", - "-Wl,-wrap,atol", - "-Wl,-wrap,atoul", - "-Wl,-wrap,atoull", - "-Wl,-wrap,atof", - "-Wl,-wrap,malloc", - "-Wl,-wrap,realloc", - "-Wl,-wrap,calloc", - "-Wl,-wrap,free", - "-Wl,-wrap,_malloc_r", - "-Wl,-wrap,_calloc_r", - "-Wl,-wrap,memcmp", - "-Wl,-wrap,memcpy", - "-Wl,-wrap,memmove", - "-Wl,-wrap,memset", - "-Wl,-wrap,printf", - "-Wl,-wrap,sprintf", - "-Wl,-wrap,puts", - "-Wl,-wrap,putc", - "-Wl,-wrap,putchar", - "-Wl,-wrap,snprintf", - "-Wl,-wrap,vsnprintf", + "-Wl,--undefined=gRamStartFun", "-Wl,-wrap,aesccmp_construct_mic_iv", "-Wl,-wrap,aesccmp_construct_mic_header1", "-Wl,-wrap,aesccmp_construct_ctr_preload", @@ -127,17 +62,44 @@ env.Append( "-Wl,-wrap,rom_psk_CalcPTK", "-Wl,-wrap,aes_80211_encrypt", "-Wl,-wrap,aes_80211_decrypt", + # stdlib wrappers + "-Wl,-wrap,strcat", + "-Wl,-wrap,strchr", + "-Wl,-wrap,strcmp", + "-Wl,-wrap,strncmp", + "-Wl,-wrap,strcpy", + "-Wl,-wrap,strncpy", + "-Wl,-wrap,strlen", + "-Wl,-wrap,strncat", + "-Wl,-wrap,strpbrk", + "-Wl,-wrap,strspn", + "-Wl,-wrap,strstr", + "-Wl,-wrap,strtok", + "-Wl,-wrap,strxfrm", + "-Wl,-wrap,strtod", + "-Wl,-wrap,strtof", + "-Wl,-wrap,strtold", + "-Wl,-wrap,strtoll", + "-Wl,-wrap,strtoul", + "-Wl,-wrap,strtoull", + "-Wl,-wrap,atoi", + "-Wl,-wrap,atol", + "-Wl,-wrap,atof", + "-Wl,-wrap,memcmp", + "-Wl,-wrap,memcpy", + "-Wl,-wrap,memmove", + "-Wl,-wrap,memset", + # TODO remove this if possible + "-Wl,-wrap,putc", ], ) # Sources - from SDK project/realtek_amebaz2_v0_example/GCC-RELEASE/application.is.mk # - without "utilities - example", "bluetooth - example" and "network - app - mqtt" -env.AddLibrary( +queue.AddLibrary( name="ambz2_sdk", base_dir=COMPONENT_DIR, srcs=[ - # libc api wrapper - "+", # cmsis "+", "+", @@ -223,27 +185,28 @@ env.AddLibrary( "+", "+", "+", - "+", + "+", ], options=dict( CCFLAGS=[ "-Wno-int-conversion", "-Wno-unused-label", "-Wno-unused-but-set-variable", - "-Wno-undef", "-Wno-pointer-sign", "-Wno-parentheses", "-Wno-implicit-function-declaration", "-Wno-misleading-indentation", - # TODO remove this; only for example_wlan_fast_connect.c + "-Wno-unused-value", + # TODO remove this; only for example_wlan_fast_connect.c and at_cmd/* "-Wno-format-truncation", "-Wno-return-type", + "-Wno-unused-variable", ], ), ) # Sources - network utilities -env.AddLibrary( +queue.AddLibrary( name="ambz2_net", base_dir=COMPONENT_DIR, srcs=[ @@ -309,7 +272,7 @@ env.AddLibrary( ) # Sources - Bluetooth support -env.AddLibrary( +queue.AddLibrary( name="ambz2_bluetooth", base_dir=join(COMPONENT_DIR, "common", "bluetooth", "realtek", "sdk"), srcs=[ @@ -354,7 +317,7 @@ env.AddLibrary( # Sources - lwIP 2.0.2 -env.AddLibrary( +queue.AddLibrary( name="ambz2_lwip", base_dir=join(COMPONENT_DIR, "common", "network", "lwip", "lwip_v2.0.2"), srcs=[ @@ -373,10 +336,15 @@ env.AddLibrary( "+", "+", ], + options=dict( + CFLAGS=[ + "-Wno-implicit-function-declaration", + ], + ), ) # Sources - mbedTLS -env.AddLibrary( +queue.AddLibrary( name="ambz2_mbedtls", base_dir=join(COMPONENT_DIR, "common", "network", "ssl", "mbedtls-2.4.0"), srcs=[ @@ -432,7 +400,7 @@ env.AddLibrary( ) # Libs & linker config -env.Append( +queue.AppendPublic( LIBPATH=[ # fmt: off join(COMPONENT_DIR, "soc", "realtek", "8710c", "misc", "bsp", "lib", "common", "GCC"), @@ -469,7 +437,7 @@ env.Replace( ) # Build all libraries -env.BuildLibraries() +queue.BuildLibraries() # Main firmware outputs and actions env.Replace( diff --git a/builder/frameworks/arduino.py b/builder/frameworks/arduino.py index 0d37e48..3d150e1 100644 --- a/builder/frameworks/arduino.py +++ b/builder/frameworks/arduino.py @@ -1,14 +1,90 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-05-16. +# Copyright (c) Kuba SzczodrzyƄski 2022-04-23. -from SCons.Script import DefaultEnvironment +from os.path import join -env = DefaultEnvironment() -board = env.BoardConfig() -platform = env.PioPlatform() +import click +from ltchiptool import Family +from SCons.Script import DefaultEnvironment, Environment -# support passing "arduino" as framework -frameworks = board.get("frameworks") -framework = next(fw for fw in frameworks if "arduino" in fw) -builder = platform.frameworks[framework]["script"] -builder = builder.rpartition("/")[2] -env.SConscript(builder, exports="env") +# Let everyone know we're using the Arduino framework +env: Environment = DefaultEnvironment() +env["ARDUINO"] = True +family: Family = env["FAMILY_OBJ"] + +# Add base cores' sources first +env.SConscript("base.py") + +# Build a safe environment for this script +queue = env.AddLibraryQueue("arduino", prepend_includes=True) + +# Add sources common among all families +env.AddCoreSources( + queue=queue, + name="common_arduino", + path=join("$COMMON_DIR", "arduino", "src"), +) +env.AddArduinoLibraries( + queue=queue, + name="common_arduino", + path=join("$COMMON_DIR", "arduino", "libraries"), +) +# Add sources for this family and each parent +found = False +for f in family.inheritance: + code = f"{f.code}_arduino" + path = join("$CORES_DIR", f.name, "arduino") + + found = found or env.AddCoreSources(queue, name=code, path=join(path, "src")) + env.AddArduinoLibraries(queue, name=code, path=join(path, "libraries")) + + if f.short_name: + env.Prepend(CPPDEFINES=[(f"ARDUINO_ARCH_{f.short_name}", "1")]) + if f.code: + env.Prepend(CPPDEFINES=[(f"ARDUINO_ARCH_{f.code.upper()}", "1")]) + +# Fail if Arduino core wasn't found +if not found: + click.secho( + f"Platform '{family.name}' doesn't support Arduino framework - " + "the Arduino core source files are absent.", + fg="red", + ) + exit(1) + +# Sources - ArduinoCore-API +queue.AddExternalLibrary("arduino-api") + +# Sources - board variant +queue.AddLibrary( + name="board_${VARIANT}", + base_dir="$VARIANTS_DIR", + srcs=[ + "+<${VARIANT}.c>", + ], + # not adding includes since they're added with the base core +) + +# Flags & linker options +queue.AppendPublic( + CPPDEFINES=[ + ("LIBRETUYA_ARDUINO", 1), + ("LIBRETINY_ARDUINO", 1), + ("ARDUINO", 10812), + ("ARDUINO_SDK", 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", + ], +) + +# Build all libraries +queue.BuildLibraries() diff --git a/builder/frameworks/base.py b/builder/frameworks/base.py new file mode 100644 index 0000000..bf1eaa6 --- /dev/null +++ b/builder/frameworks/base.py @@ -0,0 +1,166 @@ +# Copyright (c) Kuba SzczodrzyƄski 2023-02-26. + +from os.path import join + +import click +from ltchiptool import Family +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Errors import UserError +from SCons.Script import DefaultEnvironment, Environment + +env: Environment = DefaultEnvironment() +board: PlatformBoardConfig = env.BoardConfig() +platform: PlatformBase = env.PioPlatform() +family: Family = env["FAMILY_OBJ"] + +# Parse custom options +env.ParseCustomOptions(platform) +# Parse custom flash layout +env.ParseCustomFlashLayout(platform, board) +# Add flash layout C defines +env.AddFlashLayout(board) +# Write custom header options +env.ApplyCustomOptions(platform) +# Export board manifest for ltchiptool +env.ExportBoardData(board) +# Print information about versions and custom options +env.PrintInfo(platform, board) + +# TODO remove include path prepending ("!<...>") +# Move common core sources (env.AddCoreSources()) and Arduino libs +# below per-family sources (to maintain child families taking precedence) + +# Global public flags +# Refer to https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html +env.Append( + CCFLAGS=[ + # C Language Options + "-fsigned-char", # Let the type char be signed + # Debugging Options + "-g2", # produce debugging information; the default level is 2 + # Optimization Options + "-Os", # optimize for size; enables all -O2 optimizations except those that often increase code size + "-fdata-sections", # place each function or data item into its own section + "-ffunction-sections", # place each function or data item into its own section + "-fno-strict-aliasing", # (don't) assume the strictest aliasing rules applicable + "-fno-inline-functions", # (don't) consider all functions for inlining + "-fno-delete-null-pointer-checks", # assume that programs can safely dereference null pointers + # Preprocessor Options + "-MMD", # output a rule suitable for make describing the dependencies of the main source file + # Code Generation Options + "-fno-common", # place uninitialized global variables in the BSS section of the object file + "-fno-exceptions", # disable exception handling + # Developer Options + "-fstack-usage", # output stack usage information for the program, on a per-function basis + ], + CFLAGS=[ + "-std=gnu99", + ], + CXXFLAGS=[ + "-std=gnu++11", + "-fno-rtti", # disable generation of information about every class with virtual functions + ], +) + +# Include SDK builder scripts +# No environment options that follow later will be considered +found = False +for f in family.inheritance: + try: + env.Prepend(LIBPATH=[join("$CORES_DIR", f.name, "misc")]) + 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) + +# Build a safe environment for this script +queue = env.AddLibraryQueue("base", prepend_includes=True) +# Add sources & include paths for each core +env.AddCoreSources(queue, name="common", path=join("$COMMON_DIR", "base")) +for f in family.inheritance: + env.AddCoreSources(queue, name=f.code, path=join("$CORES_DIR", f.name, "base")) + + if f.short_name: + env.Prepend(CPPDEFINES=[(f"LT_{f.short_name}", "1")]) + if f.code: + env.Prepend(CPPDEFINES=[(f"LT_{f.code.upper()}", "1")]) + +# Sources - external libraries +queue.AddExternalLibrary("ltchiptool") # uf2ota source code +queue.AddExternalLibrary("flashdb") +queue.AddExternalLibrary("printf") + +# Find optimization level and add __OPTIMIZE_LEVEL__ macro +for flag in env["CCFLAGS"]: + if not flag.startswith("-O"): + continue + env.Append(CPPDEFINES=[("__OPTIMIZE_LEVEL__", flag[2])]) + +# Non-SDK defines & linker options +queue.AppendPublic( + CCFLAGS=[ + "-Wreturn-type", + "-Wno-undef", + ], + CFLAGS=[ + "-Werror=implicit-function-declaration", + ], + CXXFLAGS=[ + "-Wno-literal-suffix", + "-Wno-write-strings", + "-Wno-psabi", # parameter passing for argument of type ... changed in GCC 7.1 + ], + CPPDEFINES=[ + ("LIBRETUYA", 1), + ("LIBRETINY", 1), + ("LT_VERSION", env["LT_VERSION"]), + ("LT_BOARD", "${VARIANT}"), + ("LT_VARIANT_H", r"\"${VARIANT}.h\""), + ("F_CPU", board.get("build.f_cpu")), + ("MCU", "${MCU}"), + ("MCULC", "${MCULC}"), + ("FAMILY", "F_${FAMILY_SHORT_NAME}"), + # Add flash layout defines created in env.AddFlashLayout() + *env["FLASH_DEFINES"].items(), + ], + CPPPATH=[ + "$VARIANTS_DIR", + ], + LINKFLAGS=[ + "-g2", + "-Os", + "-Wl,--build-id=none", + "-Wl,--cref", + "-Wl,--gc-sections", + "-Wl,--no-enum-size-warning", + "-Wl,--no-wchar-size-warning", + # malloc.c wrappers + "-Wl,-wrap,malloc", + "-Wl,-wrap,calloc", + "-Wl,-wrap,zalloc", + "-Wl,-wrap,realloc", + "-Wl,-wrap,free", + "-Wl,-wrap,_malloc_r", + "-Wl,-wrap,_calloc_r", + "-Wl,-wrap,_realloc_r", + "-Wl,-wrap,_free_r", + # linker map path + '"-Wl,-Map=' + join("$BUILD_DIR", "${PROGNAME}.map") + '"', + ], + LIBS=[ + "stdc++", + "supc++", + ], +) + +# Build everything from the base core +queue.BuildLibraries() diff --git a/builder/frameworks/beken-72xx-arduino.py b/builder/frameworks/beken-72xx-arduino.py deleted file mode 100644 index 285e4cb..0000000 --- a/builder/frameworks/beken-72xx-arduino.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-06-14. - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() - -# SDK options -env.Replace( - LIB_BDK_DRIVER_SKIP=[ - # using printf library wrappers instead - "uart/printf.c", - ] -) - -env.SConscript("beken-72xx-sdk.py", exports="env") -env.SConscript("../arduino-common.py", exports="env") - -# Flags -env.Append( - CCFLAGS=[ - "-Wno-write-strings", - "-Wno-char-subscripts", - "-Wno-missing-braces", - "-Wno-attributes", - ], - CPPDEFINES=[ - # LibreTuya configuration - ("LT_ARD_HAS_WIFI", "1"), - ("LT_ARD_HAS_MD5", "1"), - # macros - # mbedtls_net_set_nonblock is commented out in tls_net.c - ("mbedtls_net_set_nonblock", "net_set_nonblock"), - ], - LINKFLAGS=[ - # stdio wrappers (port/printf/printf.c) - "-Wl,-wrap,bk_printf", - ], -) - -# Build all libraries -env.BuildLibraries() diff --git a/builder/frameworks/realtek-ambz-arduino.py b/builder/frameworks/realtek-ambz-arduino.py deleted file mode 100644 index ba6d369..0000000 --- a/builder/frameworks/realtek-ambz-arduino.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-04-22. - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() - -# SDK options -env.Replace(AMBZ_NO_POLARSSL=True) -env.Replace( - LIB_AMBZ_SDK_SKIP=[ - "component/common/api/wifi/wifi_ind.c", - ] -) - -env.SConscript("realtek-ambz-sdk.py", exports="env") -env.SConscript("../arduino-common.py", exports="env") - -# Flags -env.Append( - CPPDEFINES=[ - "ARDUINO_AMEBA", - "ARDUINO_ARCH_AMBZ", - # the SDK declares bool if not defined before - # which conflicts with C++ built-in bool - # so it's either -fpermissive or this: - ("bool", "bool"), - # LibreTuya configuration - ("LT_ARD_HAS_WIFI", "1"), - ("LT_ARD_HAS_MD5", "1"), - ("LT_ARD_HAS_SOFTSERIAL", "1"), - # not broken anymore with printf() library - ("LT_PRINTF_BROKEN", "0"), - ], - LINKFLAGS=[ - "-Wl,--undefined=InfraStart", - # stdio wrappers (port/printf/printf.c) - "-Wl,-wrap,rtl_printf", - "-Wl,-wrap,rtl_sprintf", - "-Wl,-wrap,rtl_snprintf", - "-Wl,-wrap,rtl_vsnprintf", - "-Wl,-wrap,rtl_vsnprintf_r", - "-Wl,-wrap,rtl_vprintf", - "-Wl,-wrap,rtl_vfprintf", - "-Wl,-wrap,DiagPrintf", - "-Wl,-wrap,DiagSPrintf", - "-Wl,-wrap,DiagSnPrintf", - "-Wl,-wrap,prvDiagPrintf", - "-Wl,-wrap,prvDiagSPrintf", - "-Wl,-wrap,VSprintf", - "-Wl,-wrap,LOG_PRINTF", - "-Wl,-wrap,__rtl_vfprintf_r_v1_00", - ], -) - -# Build all libraries -env.BuildLibraries() diff --git a/builder/libs/flashdb.py b/builder/libs/flashdb.py deleted file mode 100644 index 8051ba7..0000000 --- a/builder/libs/flashdb.py +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-05-24. - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() -platform = env.PioPlatform() - - -def env_add_flashdb( - env, - version: str, -): - package_dir = platform.get_package_dir(f"library-flashdb@{version}") - - env.AddLibrary( - name=f"flashdb{version}", - base_dir=package_dir, - srcs=[ - "+", - "+", - ], - includes=[ - "+", - "+", - ], - ) - - -env.AddMethod(env_add_flashdb, "AddLibraryFlashDB") diff --git a/builder/libs/lwip.py b/builder/libs/lwip.py deleted file mode 100644 index 1441dd7..0000000 --- a/builder/libs/lwip.py +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-05-18. - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() -platform = env.PioPlatform() - - -def env_add_lwip( - env, - version: str, - port: str, -): - # version = env["LIB_LWIP_VERSION"] if "LIB_LWIP_VERSION" in env else version_default - package_dir = platform.get_package_dir(f"library-lwip@{version}-{port}") - port_srcs = [] - port_includes = [] - - if port in ["amb1"]: - port_srcs = [ - "+", - "+", - ] - port_includes = [ - "+", - "+", - ] - elif port in ["bdk"]: - port_srcs = [ - "+", - ] - port_includes = [ - "+", - ] - - env.AddLibrary( - name=f"lwip{version}_{port}", - base_dir=package_dir, - srcs=[ - "+", - "+", - "+", - "+", # 2.0.x - "+", # 1.4.x - "+", - "+", - *port_srcs, - ], - includes=[ - "+", - "+", - *port_includes, - ], - ) - - -env.AddMethod(env_add_lwip, "AddLibraryLwIP") diff --git a/builder/libs/printf.py b/builder/libs/printf.py deleted file mode 100644 index 62851d4..0000000 --- a/builder/libs/printf.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-06-19. - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() -platform = env.PioPlatform() - - -def env_add_printf( - env, - version: str, -): - package_dir = platform.get_package_dir(f"library-printf@{version}") - - env.AddLibrary( - name=f"printf{version}", - base_dir=package_dir, - srcs=[ - "+", - ], - includes=[ - "+", - ], - options=dict( - CFLAGS=["-Wno-maybe-uninitialized"], - CPPDEFINES=[("PRINTF_INCLUDE_CONFIG_H", "1")], - LINKFLAGS=[ - "-Wl,-wrap,printf", - "-Wl,-wrap,sprintf", - "-Wl,-wrap,vsprintf", - "-Wl,-wrap,snprintf", - "-Wl,-wrap,vsnprintf", - "-Wl,-wrap,vprintf", - "-Wl,-wrap,puts", - "-Wl,-wrap,putchar", - ], - ), - ) - - -env.AddMethod(env_add_printf, "AddLibraryPrintf") diff --git a/builder/main.py b/builder/main.py index 66c44b1..36ad3ae 100644 --- a/builder/main.py +++ b/builder/main.py @@ -1,32 +1,37 @@ # Copyright (c) Kuba SzczodrzyƄski 2022-04-20. import sys +from os.path import join -from SCons.Script import Default, DefaultEnvironment +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import ( + COMMAND_LINE_TARGETS, + AlwaysBuild, + Default, + DefaultEnvironment, + Environment, +) -env = DefaultEnvironment() -platform = env.PioPlatform() -board = env.BoardConfig() - -# Make tools available -sys.path.insert(0, platform.get_dir()) +env: Environment = DefaultEnvironment() +platform: PlatformBase = env.PioPlatform() +board: PlatformBoardConfig = env.BoardConfig() # Utilities env.SConscript("utils/config.py", exports="env") +env.SConscript("utils/cores.py", exports="env") env.SConscript("utils/env.py", exports="env") env.SConscript("utils/flash.py", exports="env") -env.SConscript("utils/libs.py", exports="env") +env.SConscript("utils/libs-external.py", exports="env") +env.SConscript("utils/libs-queue.py", exports="env") env.SConscript("utils/ltchiptool.py", exports="env") -# Vendor-specific library ports -env.SConscript("libs/flashdb.py", exports="env") -env.SConscript("libs/lwip.py", exports="env") -env.SConscript("libs/printf.py", exports="env") # Firmware name if env.get("PROGNAME", "program") == "program": - env.Replace(PROGNAME="firmware") + env.Replace(PROGNAME="raw_firmware") env.Replace(PROGSUFFIX=".elf") +# Configure the toolchain prefix = board.get("build.prefix", "") env.Replace( AR=prefix + "gcc-ar", @@ -42,10 +47,8 @@ env.Replace( SIZETOOL=prefix + "size", ) -# Default environment options -env.AddDefaults(platform, board) -# Flash layout defines -env.AddFlashLayout(board) +# Environment variables, include paths, etc. +env.ConfigureEnvironment(platform, board) # Family builders details: # - call env.AddLibrary("lib name", "base dir", [sources]) to add lib sources @@ -63,19 +66,63 @@ env.AddFlashLayout(board) # - env.BuildLibraries() # - # Main firmware outputs and actions -target_elf = env.BuildProgram() -targets = [target_elf] +# Framework builder (base.py/arduino.py) is executed in BuildProgram() +# Force including the base framework in case no other is specified +if "nobuild" not in COMMAND_LINE_TARGETS and not env.get("PIOFRAMEWORK"): + env.SConscript("frameworks/base.py") -if "UF2OTA" in env: - target_uf2 = env.BuildUF2OTA(target_elf) - targets.append(target_uf2) - env.AddFlashWriter(target_uf2) -elif "IMG_FW" in env: - target_fw = env.subst("$IMG_FW") - env.AddPlatformTarget("upload", target_fw, env["UPLOAD_ACTIONS"], "Upload") +# +# Target: Build executable and linkable firmware +# +target_uf2 = join("${BUILD_DIR}", "firmware.uf2") +if "nobuild" in COMMAND_LINE_TARGETS: + target_elf = join("${BUILD_DIR}", "${PROGNAME}.elf") + env["UF2OTA"] = "dummy" # forcefully allow uploading using ltchiptool else: - sys.stderr.write( - "Warning! Firmware outputs not specified. Uploading is not possible.\n" - ) + target_elf = env.BuildProgram() + target_uf2 = env.BuildUF2OTA(target_uf2, target_elf) + env.Depends(target_uf2, "checkprogsize") -Default(targets) +AlwaysBuild(env.Alias("nobuild", target_uf2)) +target_buildprog = env.Alias("buildprog", target_uf2, target_uf2) + +# +# Target: Print binary size +# +target_size = env.Alias( + "size", + target_elf, + env.VerboseAction("${SIZEPRINTCMD}", "Calculating size ${SOURCE}"), +) +AlwaysBuild(target_size) + +# +# Target: Upload firmware +# +upload_protocol = env.subst("${UPLOAD_PROTOCOL}") or "uart" +upload_actions = [] +upload_source = target_uf2 +ltchiptool_flags = "UF2OTA" in env and env.GetLtchiptoolWriteFlags() + +if ltchiptool_flags: + # use ltchiptool for flashing, if available + env.Replace( + LTCHIPTOOL_FLAGS=ltchiptool_flags, + UPLOADER="${LTCHIPTOOL} flash write", + UPLOADCMD="${UPLOADER} ${LTCHIPTOOL_FLAGS} ${UPLOADERFLAGS} ${SOURCE}", + ) + upload_actions = [ + env.VerboseAction(env.AutodetectUploadPort, "Looking for upload port..."), + env.VerboseAction("${UPLOADCMD}", "Uploading ${SOURCE}"), + ] +elif upload_protocol == "custom": + upload_actions = [env.VerboseAction("$UPLOADCMD", "Uploading $SOURCE")] +else: + sys.stderr.write("Warning! Unknown upload protocol %s\n" % upload_protocol) + +AlwaysBuild(env.Alias("upload", upload_source, upload_actions)) + +# +# Default targets +# +Default([target_buildprog, target_size]) diff --git a/builder/utils/config.py b/builder/utils/config.py index 505b79b..8a49589 100644 --- a/builder/utils/config.py +++ b/builder/utils/config.py @@ -2,12 +2,38 @@ from os.path import isfile -from SCons.Script import DefaultEnvironment +from SCons.Script import DefaultEnvironment, Environment -env = DefaultEnvironment() +env: Environment = DefaultEnvironment() -def env_load_config(env, path): +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 + if not line.startswith("#define"): + continue + line = line[7:].strip() + line = line.split(None, 2) + if len(line) == 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() + + +def env_load_config(env: Environment, path: str): path = env.subst(path) if not isfile(path): raise FileNotFoundError(f"Config file not found ({path})") @@ -35,7 +61,7 @@ def env_load_config(env, path): f.close() -def env_get_config(env, key): +def env_get_config(env: Environment, key: str): config: dict = env["CONFIG"] if not config: return None @@ -45,6 +71,7 @@ def env_get_config(env, key): return value +env.AddMethod(env_load_defines, "LoadDefines") env.AddMethod(env_load_config, "LoadConfig") env.AddMethod(env_get_config, "Cfg") env.AddMethod(env_get_config, "GetConfig") diff --git a/builder/utils/cores.py b/builder/utils/cores.py new file mode 100644 index 0000000..f4a8ad4 --- /dev/null +++ b/builder/utils/cores.py @@ -0,0 +1,104 @@ +# Copyright (c) Kuba SzczodrzyƄski 2023-02-26. + +from os.path import isdir, join + +from ltchiptool import Family +from SCons.Script import DefaultEnvironment, Environment + +env: Environment = DefaultEnvironment() + + +def env_configure_family(env: Environment): + env.Prepend( + CPPPATH=[ + join("$COMMON_DIR", "base", "fixups"), + join("$COMMON_DIR", "base", "config"), + join("$COMMON_DIR", "base", "compat"), + ], + ) + + family: Family = env["FAMILY_OBJ"] + for f in family.inheritance: + path = join("$CORES_DIR", f.name, "base") + if not isdir(env.subst(path)): + continue + env.Prepend( + CPPPATH=[ + join(path, "fixups"), + join(path, "config"), + join(path, "compat"), + ], + LIBPATH=[ + join(path, "fixups"), + ], + ) + + +def env_add_core_sources(env: Environment, queue, name: str, path: str) -> bool: + if not isdir(env.subst(path)): + return False + try: + env.LoadDefines(join(path, "lt_defs.h")) + except FileNotFoundError: + pass + queue.AddLibrary( + name=f"core_{name}", + base_dir=path, + srcs=[ + "+<*.c*>", + "+", + "+", + "+", + "+", + "+", + ], + includes=[ + # prepend the paths before SDK directories + "!<.>", + "!", + "!", + "!", + ], + ) + queue.AddLibrary( + name=f"core_{name}_fixups", + base_dir=path, + srcs=[ + "+", + ], + includes=[ + "!", + ], + options=dict( + # disable all warnings for fixups + CCFLAGS=["-w"], + ), + ) + return True + + +def env_add_arduino_libraries(env: Environment, queue, name: str, path: str) -> bool: + if not isdir(env.subst(path)): + return False + queue.AddLibrary( + name=f"core_{name}_libraries", + base_dir=path, + srcs=[ + "+<**/*.c*>", + ], + includes=[ + "!<*/.>", + "!<*/*>", + ] + if name.startswith("common") + else [ + "!<.>", + "!<*>", + ], + ) + return True + + +env.AddMethod(env_configure_family, "ConfigureFamily") +env.AddMethod(env_add_core_sources, "AddCoreSources") +env.AddMethod(env_add_arduino_libraries, "AddArduinoLibraries") diff --git a/builder/utils/env.py b/builder/utils/env.py index 91a7ff7..43fa200 100644 --- a/builder/utils/env.py +++ b/builder/utils/env.py @@ -1,13 +1,19 @@ # Copyright (c) Kuba SzczodrzyƄski 2022-05-04. +import json import sys +from os import makedirs from os.path import isdir, join from subprocess import PIPE, Popen +from typing import Dict -from ltchiptool import Family -from SCons.Script import DefaultEnvironment +from ltchiptool import Family, get_version +from ltchiptool.util.misc import sizeof +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import DefaultEnvironment, Environment -env = DefaultEnvironment() +env: Environment = DefaultEnvironment() def read_version(platform_dir: str, version: str): @@ -25,13 +31,8 @@ def read_version(platform_dir: str, version: str): return version sha = p.stdout.read().decode().strip() - p = Popen(["git", "status", "--short"], stdout=PIPE, cwd=platform_dir) - if p.wait() != 0: - sys.stderr.write( - f"Warning! Non-zero return code received from Git: {p.returncode}\n" - ) - return version - dirty = p.stdout.read().strip() + p = Popen(["git", "diff", "--quiet"], stdout=PIPE, cwd=platform_dir) + dirty = p.wait() != 0 except (FileNotFoundError, IndexError): sys.stderr.write( "Warning! Git executable not found, or unreadable data received. Cannot read version information.\n" @@ -47,33 +48,32 @@ def read_version(platform_dir: str, version: str): return f"{version}+{build_str}" if build_str else version -def env_add_defaults(env, platform, board): +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) # Get Family object for this board family = Family.get(short_name=board.get("build.family")) # Default environment variables - vars = dict( - SDK_DIR=platform.get_package_dir(family.framework), + env.Replace( + SDK_DIR=platform.get_package_dir(board.get("package")), LT_DIR=platform.get_dir(), - # Root dirs - BOARD_DIR=join("${LT_DIR}", "boards", "${VARIANT}"), - ARDUINO_DIRS={ - "$FAMILY_CODE": join("${LT_DIR}", "arduino", "${FAMILY_NAME}"), - "$FAMILY_PARENT_CODE": join("${LT_DIR}", "arduino", "${FAMILY_PARENT}"), - }, - FAMILY_DIR=join("${LT_DIR}", "platform", "${FAMILY_NAME}"), - PARENT_DIR=join("${LT_DIR}", "platform", "${FAMILY_PARENT}"), - TOOLS_DIR=join("${LT_DIR}", "tools"), - # Family-specific paths - BIN_DIR=join("${FAMILY_DIR}", "bin"), - OPENOCD_DIR=join("${FAMILY_DIR}", "openocd"), - # Use SDK linker script by default - LDSCRIPT_PATH=["${LDSCRIPT_SDK}"], + CORES_DIR=join("${LT_DIR}", "cores"), + COMMON_DIR=join("${LT_DIR}", "cores", "common"), + LT_VERSION=read_version(platform.get_dir(), platform.version), + # Build directories & paths + VARIANTS_DIR=join("${LT_DIR}", "boards", "variants"), + FAMILY_DIR=join("${LT_DIR}", "cores", "${FAMILY_NAME}"), + MISC_DIR=join("${FAMILY_DIR}", "misc"), + LDSCRIPT_PATH=[board.get("build.ldscript")], # Board config variables MCU=board.get("build.mcu").upper(), - MCULC=board.get("build.mcu"), + MCULC=board.get("build.mcu").lower(), VARIANT=board.get("build.variant"), - LDSCRIPT_SDK=board.get("build.ldscript_sdk"), - LDSCRIPT_ARDUINO=board.get("build.ldscript_arduino"), # ltchiptool config: # -r output raw log messages # -i 1 indent log messages @@ -81,42 +81,110 @@ def env_add_defaults(env, platform, board): # Fix for link2bin to get tmpfile name in argv LINKCOM="${LINK} ${LINKARGS}", LINKARGS="${TEMPFILE('-o $TARGET $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS', '$LINKCOMSTR')}", + # Store the family object + FAMILY_OBJ=family, + EXTERNAL_LIBS=external_libs, ) - env.Replace(**vars) # Store family parameters as environment variables env.Replace(**dict(family)) - # Default build options - env.Prepend( - CPPPATH=[ - "$LT_DIR/platform/common/config", - "$LT_DIR/platform/common/fixups", - "$LT_DIR/platform/common/fixups/lib_inc", - "$BOARD_DIR", - "$FAMILY_DIR/config", - "$PARENT_DIR/config", - "$FAMILY_DIR/fixups", - "$PARENT_DIR/fixups", - "$FAMILY_DIR/fixups/inc", - "$PARENT_DIR/fixups/inc", - ], - LIBPATH=[ - "$FAMILY_DIR/ld", - "$PARENT_DIR/ld", - "$FAMILY_DIR/fixups", - "$PARENT_DIR/fixups", - ], - CPPDEFINES=[ - ("LIBRETUYA", "1"), - ("LT_VERSION", read_version(platform.get_dir(), platform.version)), - ("LT_BOARD", "${VARIANT}"), - ("F_CPU", board.get("build.f_cpu")), - ("MCU", "${MCU}"), - ("FAMILY", "F_${FAMILY}"), - ], - LINKFLAGS=[ - '"-Wl,-Map=' + join("$BUILD_DIR", "${PROGNAME}.map") + '"', - ], - ) + return family -env.AddMethod(env_add_defaults, "AddDefaults") +def env_print_info( + env: Environment, + platform: PlatformBase, + board: PlatformBoardConfig, +): + TAB = " " * 4 + + def dump(k, v, indent=""): + k = k.replace("#", ".") + if isinstance(v, dict): + print(f"{indent} - {k}:") + for k, v in sorted(v.items()): + dump(k, v, indent + TAB) + elif isinstance(v, list): + print(f"{indent} - {k}:") + for k, v in enumerate(v): + dump(k, v, indent + TAB) + else: + print(f"{indent} - {k} = {v}") + + # Print information about installed core versions + print("PLATFORM VERSIONS:") + print(" - libretiny @", env["LT_VERSION"]) + print(" - ltchiptool @", get_version()) + # Print custom platformio.ini options + if platform.custom_opts: + print("CUSTOM OPTIONS:") + for k, v in sorted(platform.custom_opts.items()): + dump(k, v) + # Print custom flash layout + if env.get("FLASH_IS_CUSTOM", False): + print("CUSTOM FLASH LAYOUT:") + for name, layout in board.get("flash").items(): + (_, _, length) = v.partition("+") + length = int(length, 16) + print(f" - {name}: {layout} ({sizeof(length)})") + + +def env_parse_custom_options(env: Environment, platform: PlatformBase): + opts: dict = platform.custom_opts.get("options", None) + if not opts: + return + headers = { + "lwip": "lwipopts.h", + "freertos": "FreeRTOSConfig.h", + } + for header, options in list(opts.items()): + if not isinstance(options, str): + raise TypeError("Options value should be str") + options = options.strip().splitlines() + opts_dict = {} + for line in options: + if "=" not in line: + raise ValueError(f"Invalid option: {line}") + k, _, v = line.partition("=") + k = k.strip() + v = v.strip() + opts_dict[k] = v + # replace predefined header names + opts.pop(header) + header = headers.get(header, header) + header = header.replace(".", "#") + opts[header] = opts_dict + + +def env_apply_custom_options(env: Environment, platform: PlatformBase): + opts = platform.custom_opts.get("options", None) + if not opts: + return + header_dir = join("${BUILD_DIR}", "include") + real_dir = env.subst(header_dir) + makedirs(real_dir, exist_ok=True) + + for header, options in opts.items(): + header: str + options: Dict[str, str] + # open the header file for writing + header = header.replace("#", ".") + f = open(join(real_dir, header), "w") + f.write(f'#include_next "{header}"\n' "\n" "#pragma once\n" "\n") + # write all #defines + for k, v in options.items(): + f.write( + f"// {k} = {v}\n" + f"#ifdef {k}\n" + f"#undef {k}\n" + f"#endif\n" + f"#define {k} {v}\n" + ) + f.close() + # prepend newly created headers before any other + env.Prepend(CPPPATH=[header_dir]) + + +env.AddMethod(env_configure, "ConfigureEnvironment") +env.AddMethod(env_print_info, "PrintInfo") +env.AddMethod(env_parse_custom_options, "ParseCustomOptions") +env.AddMethod(env_apply_custom_options, "ApplyCustomOptions") diff --git a/builder/utils/flash.py b/builder/utils/flash.py index 546d0b9..69b8141 100644 --- a/builder/utils/flash.py +++ b/builder/utils/flash.py @@ -1,34 +1,117 @@ # Copyright (c) Kuba SzczodrzyƄski 2022-06-12. -from SCons.Script import DefaultEnvironment +import re +from os.path import isfile, join +from typing import Dict -env = DefaultEnvironment() +from ltchiptool.util.fileio import chext +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import DefaultEnvironment, Environment + +env: Environment = DefaultEnvironment() -def env_add_flash_layout(env, board): +def env_parse_custom_flash_layout( + env: Environment, + platform: PlatformBase, + board: PlatformBoardConfig, +): + opts: dict = platform.custom_opts.get("flash", None) + if not opts: + return + flash_layout: dict = board.get("flash") + + # find all default partitions + partitions: Dict[str, int] = {} + flash_size = 0 + for name, layout in flash_layout.items(): + (offset, _, length) = layout.partition("+") + offset = int(offset, 16) + length = int(length, 16) + partitions[name] = offset + flash_size = max(flash_size, offset + length) + + # set custom offsets + for name, offset in opts.items(): + offset = int(offset, 0) + partitions[name] = offset + + # recalculate partition sizes + flash_layout = {} + partitions = sorted(partitions.items(), key=lambda p: p[1]) + for i, (name, offset) in enumerate(partitions): + end = partitions[i + 1][1] if i + 1 < len(partitions) else flash_size + length = end - offset + flash_layout[name] = f"0x{offset:06X}+0x{length:X}" + board.manifest["flash"] = flash_layout + env["FLASH_IS_CUSTOM"] = True + + +def env_add_flash_layout(env: Environment, board: PlatformBoardConfig): flash_layout: dict = board.get("flash") if flash_layout: defines = {} flash_size = 0 fal_items = "" # add "root" partition - fal_items += "FAL_PART_TABLE_ITEM(root, ROOT)" + fal_items += "FAL_PART_TABLE_ITEM(root,ROOT)" # add all partitions for name, layout in flash_layout.items(): name = name.upper() (offset, _, length) = layout.partition("+") - defines[f"FLASH_{name}_OFFSET"] = offset - defines[f"FLASH_{name}_LENGTH"] = length + offset = int(offset, 16) + length = int(length, 16) + defines[f"FLASH_{name}_OFFSET"] = f"0x{offset:06X}" + defines[f"FLASH_{name}_LENGTH"] = f"0x{length:06X}" fal_items += f"FAL_PART_TABLE_ITEM({name.lower()}, {name})" - flash_size = max(flash_size, int(offset, 16) + int(length, 16)) - defines["FLASH_LENGTH"] = flash_size + flash_size = max(flash_size, offset + length) + defines["FLASH_LENGTH"] = f"0x{flash_size:06X}" # for "root" partition - defines["FLASH_ROOT_OFFSET"] = 0 - defines["FLASH_ROOT_LENGTH"] = flash_size + defines["FLASH_ROOT_OFFSET"] = "0x000000" + defines["FLASH_ROOT_LENGTH"] = f"0x{flash_size:06X}" # add partition table array defines["FAL_PART_TABLE"] = "{" + fal_items + "}" - env.Append(CPPDEFINES=list(defines.items())) + env.Replace(FLASH_DEFINES=defines) env.Replace(**defines) +def env_generate_linker_script(env: Environment, board: PlatformBoardConfig, name: str): + template_name = chext(name, "template.ld") + + # find the linker script template in LIBPATH + input = None + for path in env["LIBPATH"]: + path = env.subst(path) + if isfile(join(path, template_name)): + input = join(path, template_name) + break + if not input: + raise FileNotFoundError(template_name) + + # load the .template.ld script + with open(input, "r") as f: + ldscript = f.read() + + def transform(match: re.Match): + key = match[1] + if key in env: + return env[key] + if key.startswith("BOARD_"): + key = key[6:].lower() + return board.get(key) + raise ValueError(f"Unrecognized template key: {key}") + + ldscript = re.sub(r"\${([A-Z0-9_.]+)}", transform, ldscript) + + # write .ld script + output = join("${BUILD_DIR}", name) + with open(env.subst(output), "w") as f: + f.write(ldscript) + + env.Prepend(LIBPATH=["${BUILD_DIR}"]) + + +env.AddMethod(env_parse_custom_flash_layout, "ParseCustomFlashLayout") env.AddMethod(env_add_flash_layout, "AddFlashLayout") +env.AddMethod(env_generate_linker_script, "GenerateLinkerScript") diff --git a/builder/utils/libs-external.py b/builder/utils/libs-external.py new file mode 100644 index 0000000..14dd477 --- /dev/null +++ b/builder/utils/libs-external.py @@ -0,0 +1,67 @@ +# Copyright (c) Kuba SzczodrzyƄski 2023-02-26. + +from dataclasses import dataclass +from typing import Dict, List, Optional, Union + +from ltchiptool.util.dict import merge_dicts +from platformio.package.meta import PackageItem +from platformio.platform.base import PlatformBase +from SCons.Script import DefaultEnvironment, Environment + +env: Environment = DefaultEnvironment() +platform: PlatformBase = env.PioPlatform() + + +@dataclass +class ExternalLibrary: + package: str + sources: List[str] + includes: List[str] + flags: List[str] = None + linkflags: List[str] = None + defines: Dict[str, Union[str, int]] = None + + def __post_init__(self): + self.flags = self.flags or [] + self.linkflags = self.linkflags or [] + self.defines = self.defines or {} + + +def env_add_external_library( + env: Environment, + queue, + name: str, + port: Optional[str] = None, + options: Dict[str, List[str]] = {}, +): + if port: + name += f"-{port}" + external_libs = env["EXTERNAL_LIBS"] + lib = ExternalLibrary(**external_libs[name]) + version = platform.versions.get(lib.package, None) + + package: PackageItem = platform.pm.get_package( + platform.get_package_spec(lib.package, version) + ) + if not package: + raise ValueError( + f"Version '{version}' of library '{name}' ({lib.package}) is not installed" + ) + + opts_default = dict( + CFLAGS=lib.flags, + CPPDEFINES=[(k, v) for k, v in lib.defines.items()], + LINKFLAGS=lib.linkflags, + ) + options = merge_dicts(opts_default, options) + + queue.AddLibrary( + name=name.replace("-", "_"), + base_dir=package.path, + srcs=lib.sources, + includes=lib.includes, + options=options, + ) + + +env.AddMethod(env_add_external_library, "AddExternalLibrary") diff --git a/builder/utils/libs-queue.py b/builder/utils/libs-queue.py new file mode 100644 index 0000000..0e611d8 --- /dev/null +++ b/builder/utils/libs-queue.py @@ -0,0 +1,215 @@ +# Copyright (c) Kuba SzczodrzyƄski 2023-02-28. + +import fnmatch +from dataclasses import InitVar, dataclass, field +from glob import glob +from os.path import isdir, join +from typing import Dict, Generator, List, Tuple + +from ltchiptool.util.dict import merge_dicts +from SCons.Script import DefaultEnvironment, Environment + +env: Environment = DefaultEnvironment() +ENV_PUBLIC_ONLY = ["CPPPATH", "LIBPATH", "LIBS", "LINKFLAGS"] + + +def add_base_dir( + env: Environment, + base_dir: str, + expressions: List[str], + subst: bool = False, +): + out = [] + for expr in expressions: + if expr == False: + # support '[cond] and [path]' logical expressions + continue + if expr[1] != "<" or expr[-1] != ">": + raise ValueError(f"Not a valid glob: {expr}") + if expr[2] == "$": + # do not append base path + path = expr[2:-1] + else: + path = join(base_dir, expr[2:-1]) + if subst: + path = env.subst(path) + out.append(expr[0] + "<" + path + ">") + return out + + +def iter_expressions(expressions: List[str]) -> Generator[Tuple[str, str], None, None]: + for expr in expressions: + if expr[1:2] != "<" or expr[-1:] != ">": + yield ("+", expr) + continue + yield (expr[0], expr[2:-1]) + + +def apply_options(env: Environment, options: Dict[str, List[str]]): + non_expr_keys = ["CPPDEFINES"] + for key, values in options.items(): + if not values: + continue + if key in non_expr_keys or not isinstance(values[0], str): + env.Append(**{key: values}) + continue + for dir, value in iter_expressions(values): + if dir == "+": + env.Append(**{key: [value]}) + elif dir == "!": + env.Prepend(**{key: [value]}) + elif dir == "-": + if value not in env[key]: + raise ValueError(f"Invalid option; {value} is not in {key}") + env[key].remove(value) + + +@dataclass +class Library: + env: InitVar[Environment] + name: str + base_dir: str + srcs: List[str] + includes: List[str] = field(default_factory=lambda: []) + options: Dict[str, List[str]] = field(default_factory=lambda: {}) + + def __post_init__(self, env: Environment): + # add base dir to all globs + self.srcs = add_base_dir(env, self.base_dir, self.srcs) + self.includes = add_base_dir(env, self.base_dir, self.includes, subst=True) + + +class LibraryQueue: + env: Environment + name: str + queue: List[Library] + includes: List[str] + options_public: dict + options_private: dict + prepend_includes: bool + built: bool = False + + def __init__( + self, + env: Environment, + name: str, + prepend_includes: bool = False, + ) -> None: + self.env = env + self.name = name + self.queue = [] + self.includes = [] + self.options_public = {} + self.options_private = {} + self.prepend_includes = prepend_includes + + def AddLibrary(self, **kwargs): + lib = Library(env=self.env, **kwargs) + # search all include paths + for dir, expr in iter_expressions(lib.includes): + if dir == "-": + for item in fnmatch.filter(self.includes, expr): + if item in self.includes: + self.includes.remove(item) + continue + for item in glob(expr, recursive=True): + if not isdir(item): + continue + if dir == "!": + self.includes.insert(0, item) + else: + self.includes.append(item) + # move public-only options to the global env + for key in ENV_PUBLIC_ONLY: + if key not in lib.options: + continue + option = lib.options.pop(key) + self.options_public = merge_dicts(self.options_public, {key: option}) + self.queue.append(lib) + + def AddExternalLibrary(self, *args, **kwargs): + return self.env.AddExternalLibrary(self, *args, **kwargs) + + def AppendPublic(self, **kwargs): + if "CPPPATH" in kwargs: + self.includes += kwargs["CPPPATH"] + kwargs.pop("CPPPATH") + self.options_public = merge_dicts(self.options_public, kwargs) + + def AppendPrivate(self, **kwargs): + if any(key in ENV_PUBLIC_ONLY for key in kwargs.keys()): + raise ValueError("Cannot set these as private options") + self.options_private = merge_dicts(self.options_private, kwargs) + + def Print(self): + def print_list(items): + print( + "\n".join( + f"{i+1: 4d}. {self.env.subst(str(item))}" + for i, item in enumerate(items) + ) + ) + + print() + print(f"Library Queue - {self.name}") + print("Environment paths:") + print_list(self.env["CPPPATH"]) + print( + "Include paths (%s):" % ("prepend" if self.prepend_includes else "append") + ) + print_list(self.includes) + print("Environment options:") + opts = ["CFLAGS", "CCFLAGS", "CXXFLAGS", "CPPDEFINES", "ASFLAGS"] + opts = {k: v for k, v in self.env.items() if k in opts} + print_list(opts.items()) + print("Options - public:") + print_list(self.options_public.items()) + print("Options - private:") + print_list(self.options_private.items()) + print("Libraries:") + print_list(self.queue) + + def BuildLibraries(self): + if self.built: + raise RuntimeError("Cannot build a library queue twice") + + # add public options to the environment + apply_options(self.env, self.options_public) + # treat all include paths as public + if self.prepend_includes: + self.env.Prepend(CPPPATH=self.includes) + else: + self.env.Append(CPPPATH=self.includes) + + # clone the environment for the whole library queue + queue_env = self.env.Clone() + # add private options to the cloned environment + apply_options(queue_env, self.options_private) + + for lib in self.queue: + if lib.options: + # clone the environment separately for each library + lib_env = queue_env.Clone() + # add library-scoped options + apply_options(lib_env, lib.options) + else: + # no library-scoped options, just use the base env + lib_env = queue_env + # build library with (name, base_dir, sources) options + target = lib_env.BuildLibrary( + join("$BUILD_DIR", lib.name), lib.base_dir, lib.srcs + ) + self.env.Prepend(LIBS=[target]) + + self.built = True + + +def env_add_library_queue( + env: Environment, + name: str, + prepend_includes: bool = False, +) -> LibraryQueue: + return LibraryQueue(env, name, prepend_includes) + + +env.AddMethod(env_add_library_queue, "AddLibraryQueue") diff --git a/builder/utils/libs.py b/builder/utils/libs.py deleted file mode 100644 index 056b588..0000000 --- a/builder/utils/libs.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) Kuba SzczodrzyƄski 2022-05-04. - -import fnmatch -from glob import glob -from os.path import isdir, join -from typing import Dict, Generator, List, Tuple - -from SCons.Script import DefaultEnvironment - -env = DefaultEnvironment() - - -def add_base_dir(env, base_dir: str, expressions: List[str], subst: bool = False): - out = [] - for expr in expressions: - if expr[1] != "<" or expr[-1] != ">": - raise ValueError(f"Not a valid glob: {expr}") - if expr[2] == "$": - # do not append base path - path = expr[2:-1] - else: - path = join(base_dir, expr[2:-1]) - if subst: - path = env.subst(path) - out.append(expr[0] + "<" + path + ">") - return out - - -def iter_expressions(expressions: List[str]) -> Generator[Tuple[str, str], None, None]: - for expr in expressions: - if expr[1] != "<" or expr[-1] != ">": - yield ("+", expr) - continue - yield (expr[0], expr[2:-1]) - - -def env_add_library( - env, - name: str, - base_dir: str, - srcs: List[str], - includes: List[str] = [], - options: Dict[str, List[str]] = {}, -): - name = env.subst(name) - # add base dir to all globs - srcs = add_base_dir(env, base_dir, srcs) - includes = add_base_dir(env, base_dir, includes, subst=True) - - # allow removing sources from parent builders - key = f"LIB_{name.upper()}_SKIP" - if key in env: - for expr in env[key]: - srcs.append("-<" + expr + ">") - - # queue library for further env clone and build - if srcs: - env.Prepend( - LIBQUEUE=[ - (join("$BUILD_DIR", name), base_dir, srcs, options), - ] - ) - - # search all include paths - for dir, expr in iter_expressions(includes): - if dir == "-": - for item in fnmatch.filter(env["CPPPATH"], expr): - if item in env["CPPPATH"]: - env["CPPPATH"].remove(item) - else: - for item in glob(expr, recursive=True): - if not isdir(item): - continue - if dir == "!": - env.Prepend(CPPPATH=[item]) - else: - env.Append(CPPPATH=[item]) - - -def env_build_libraries(env, safe: bool = True): - # add lib targets and clone safe envs - if not "LIBQUEUE" in env: - return - queue = env["LIBQUEUE"] - env["LIBQUEUE"] = [] - for lib in queue: - envsafe = env.Clone() if safe else env - # get env options to add/remove - options: Dict[str, List[str]] = lib[3] - # change only safe env options - for key, values in options.items(): - for dir, value in iter_expressions(values): - if dir == "+": - envsafe.Append(**{key: [value]}) - elif dir == "!": - envsafe.Prepend(**{key: [value]}) - elif dir == "-": - if value not in envsafe[key]: - raise ValueError(f"Invalid option; {value} is not in {key}") - envsafe[key].remove(value) - # build library with (name, base_dir, sources) options - target = envsafe.BuildLibrary(*lib[0:3]) - env.Prepend(LIBS=[target]) - - -env.AddMethod(env_add_library, "AddLibrary") -env.AddMethod(env_build_libraries, "BuildLibraries") diff --git a/builder/utils/ltchiptool.py b/builder/utils/ltchiptool.py index 59a6c3c..fc1238d 100644 --- a/builder/utils/ltchiptool.py +++ b/builder/utils/ltchiptool.py @@ -1,16 +1,18 @@ # Copyright (c) Kuba SzczodrzyƄski 2022-06-02. -import sys +import json from datetime import datetime from os.path import basename, join, normpath -from SCons.Script import Builder, DefaultEnvironment +from platformio.platform.base import PlatformBase +from platformio.platform.board import PlatformBoardConfig +from SCons.Script import Builder, DefaultEnvironment, Environment -env = DefaultEnvironment() -platform = env.PioPlatform() +env: Environment = DefaultEnvironment() +platform: PlatformBase = env.PioPlatform() -def env_uf2ota(env, *args, **kwargs): +def env_uf2ota(env: Environment, *args, **kwargs): now = datetime.now() project_dir = env.subst("$PROJECT_DIR") project_name = basename(normpath(project_dir)) @@ -22,68 +24,60 @@ def env_uf2ota(env, *args, **kwargs): if platform.custom("fw_version"): project_version = platform.custom("fw_version") - inputs = " ".join(f'"{";".join(input)}"' for input in env["UF2OTA"]) output = [ project_name, project_version, "${VARIANT}", - "${FAMILY}", + "${MCULC}", f"lt{lt_version}", ] output = "_".join(output) + ".uf2" if platform.custom("fw_output"): output = platform.custom("fw_output") - output = join("${BUILD_DIR}", output) - env["UF2OUT"] = output - env["UF2OUT_BASE"] = basename(output) + + outputs = [ + join("${BUILD_DIR}", output), + join("${BUILD_DIR}", "firmware.uf2"), + join("${BUILD_DIR}", "firmware.bin"), + ] + output_opts = [f'--output "{output}"' for output in outputs] cmd = [ "@${LTCHIPTOOL} uf2 write", - f'--output "{output}"', - "--family ${FAMILY}", - "--board ${VARIANT}", - f"--version {lt_version}", + *output_opts, + "--board ${BOARD_JSON}", + f"--lt-version {lt_version}", f'--fw "{project_name}:{project_version}"', f"--date {int(now.timestamp())}", - inputs, + "--legacy", + *(f'"{arg}"' for arg in env["UF2OTA"]), ] - print(f"|-- {basename(env.subst(output))}") - + for output in outputs: + print(f"|-- {basename(env.subst(output))}") env.Execute(" ".join(cmd)) -def env_flash_write(env, target): +def env_flash_write(env: Environment): protocol = env.subst("${UPLOAD_PROTOCOL}") - actions = [] - # from platform-espressif32/builder/main.py if protocol == "uart": # upload via UART - env["UPLOADERFLAGS_UF2"] = [ - "${UF2OUT}", + return [ "-d", "${UPLOAD_PORT}", "-b", "${UPLOAD_SPEED}", ] - actions = [ - env.VerboseAction(env.AutodetectUploadPort, "Looking for upload port..."), - ] - elif protocol == "custom": - actions = [ - env.VerboseAction("${UPLOADCMD}", "Uploading firmware"), - ] else: - sys.stderr.write("Warning! Unknown upload protocol %s\n" % protocol) - return + # can't upload via ltchiptool + return [] - # add main upload target - env.Replace( - UPLOADER="${LTCHIPTOOL} flash write", - UPLOADCMD="${UPLOADER} ${UPLOADERFLAGS_UF2} ${UPLOADERFLAGS}", - ) - actions.append(env.VerboseAction("${UPLOADCMD}", "Uploading ${UF2OUT_BASE}")) - env.AddPlatformTarget("upload", target, actions, "Upload") + +def env_export_board_data(env: Environment, board: PlatformBoardConfig): + output = join("${BUILD_DIR}", "board.json") + with open(env.subst(output), "w") as f: + json.dump(board.manifest, f, indent="\t") + env["BOARD_JSON"] = output env.Append( @@ -93,4 +87,5 @@ env.Append( ) ) ) -env.AddMethod(env_flash_write, "AddFlashWriter") +env.AddMethod(env_flash_write, "GetLtchiptoolWriteFlags") +env.AddMethod(env_export_board_data, "ExportBoardData") diff --git a/platform/beken-7231n/config/sys_config.h b/cores/beken-7231n/base/config/sys_config.h similarity index 100% rename from platform/beken-7231n/config/sys_config.h rename to cores/beken-7231n/base/config/sys_config.h diff --git a/platform/beken-7231n/fixups/temp_detect.c b/cores/beken-7231n/base/fixups/temp_detect.c similarity index 100% rename from platform/beken-7231n/fixups/temp_detect.c rename to cores/beken-7231n/base/fixups/temp_detect.c diff --git a/platform/beken-7231u/config/sys_config.h b/cores/beken-7231u/base/config/sys_config.h similarity index 100% rename from platform/beken-7231u/config/sys_config.h rename to cores/beken-7231u/base/config/sys_config.h diff --git a/platform/beken-72xx/fixups/boot_handlers_105_bk7231s.S b/cores/beken-7231u/base/fixups/boot_handlers_105_bk7231s.S similarity index 100% rename from platform/beken-72xx/fixups/boot_handlers_105_bk7231s.S rename to cores/beken-7231u/base/fixups/boot_handlers_105_bk7231s.S diff --git a/platform/beken-7251/config/sys_config.h b/cores/beken-7251/base/config/sys_config.h similarity index 100% rename from platform/beken-7251/config/sys_config.h rename to cores/beken-7251/base/config/sys_config.h diff --git a/arduino/beken-72xx/cores/arduino/SerialClass.cpp b/cores/beken-72xx/arduino/libraries/Serial/Serial.cpp similarity index 96% rename from arduino/beken-72xx/cores/arduino/SerialClass.cpp rename to cores/beken-72xx/arduino/libraries/Serial/Serial.cpp index 09e2c49..6e90c20 100644 --- a/arduino/beken-72xx/cores/arduino/SerialClass.cpp +++ b/cores/beken-72xx/arduino/libraries/Serial/Serial.cpp @@ -1,6 +1,8 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-23. */ -#include "SerialClass.h" +#include "Serial.h" + +#include extern "C" { @@ -12,10 +14,10 @@ extern int uart_rx_callback_set(int uport, uart_callback callback, void *param); } // extern "C" -#ifdef PIN_SERIAL1_TX +#if HAS_SERIAL1 SerialClass Serial1(UART1_PORT); #endif -#ifdef PIN_SERIAL2_TX +#if HAS_SERIAL2 SerialClass Serial2(UART2_PORT); #endif diff --git a/arduino/beken-72xx/cores/arduino/SerialClass.h b/cores/beken-72xx/arduino/libraries/Serial/Serial.h similarity index 92% rename from arduino/beken-72xx/cores/arduino/SerialClass.h rename to cores/beken-72xx/arduino/libraries/Serial/Serial.h index 19ef39c..5c77c4d 100644 --- a/arduino/beken-72xx/cores/arduino/SerialClass.h +++ b/cores/beken-72xx/arduino/libraries/Serial/Serial.h @@ -2,7 +2,7 @@ #pragma once -#include +#include #include #include @@ -34,5 +34,3 @@ class SerialClass : public HardwareSerial { using Print::write; }; - -#define HAS_SERIAL_CLASS 1 diff --git a/arduino/beken-72xx/libraries/WiFi/WiFi.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFi.cpp similarity index 62% rename from arduino/beken-72xx/libraries/WiFi/WiFi.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFi.cpp index 6091204..b5e3545 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFi.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFi.cpp @@ -1,38 +1,18 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-26. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" WiFiClass::WiFiClass() { - memset(&data, 0x00, sizeof(WiFiData)); - data.scanSem = xSemaphoreCreateBinary(); + data = (WiFiData *)calloc(1, sizeof(WiFiData)); + + DATA->scanSem = xSemaphoreCreateBinary(); + STA_CFG.dhcp_mode = DHCP_CLIENT; } WiFiClass::~WiFiClass() { - vSemaphoreDelete(data.scanSem); -} - -void WiFiClass::dataInitialize() { - if (data.statusIp) - return; - LT_DM(WIFI, "Data init"); - data.configSta = zalloc(sizeof(network_InitTypeDef_st)); - data.configAp = zalloc(sizeof(network_InitTypeDef_ap_st)); - data.statusIp = malloc(sizeof(IPStatusTypedef)); - data.statusLink = malloc(sizeof(LinkStatusTypeDef)); - STA_CFG->dhcp_mode = DHCP_CLIENT; - LT_DM(WIFI, "Data = %p", data.configSta); -} - -void WiFiClass::dataFree() { - LT_DM(WIFI, "Data free"); - free(data.configSta); - free(data.configAp); - free(data.statusIp); - free(data.statusLink); - data.configSta = NULL; - data.configAp = NULL; - data.statusIp = NULL; - data.statusLink = NULL; + vSemaphoreDelete(DATA->scanSem); + free(data); + data = NULL; } WiFiStatus eventTypeToStatus(uint8_t type) { @@ -56,6 +36,7 @@ WiFiStatus eventTypeToStatus(uint8_t type) { case RW_EVT_STA_DISCONNECTED: return WL_DISCONNECTED; } + return WL_IDLE_STATUS; } WiFiAuthMode securityTypeToAuthMode(uint8_t type) { diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiAP.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFiAP.cpp similarity index 67% rename from arduino/beken-72xx/libraries/WiFi/WiFiAP.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiAP.cpp index c1111f7..3c98e01 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiAP.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiAP.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-07-01. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bool ssidHidden, int maxClients) { if (!enableAP(true)) @@ -13,32 +13,32 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo // Beken SDK bug: bk_wlan_ap_init_adv() doesn't null-terminate the passphrase memset(g_ap_param_ptr->key, '\0', 65); - strcpy(AP_CFG->wifi_ssid, ssid); + strcpy(AP_CFG.wifi_ssid, ssid); if (passphrase) { - strcpy(AP_CFG->wifi_key, passphrase); - AP_CFG->security = BK_SECURITY_TYPE_WPA2_MIXED; + strcpy(AP_CFG.wifi_key, passphrase); + AP_CFG.security = BK_SECURITY_TYPE_WPA2_MIXED; } else { - AP_CFG->wifi_key[0] = '\0'; - AP_CFG->security = BK_SECURITY_TYPE_NONE; + AP_CFG.wifi_key[0] = '\0'; + AP_CFG.security = BK_SECURITY_TYPE_NONE; } - AP_CFG->channel = channel; - AP_CFG->ssid_hidden = ssidHidden; - AP_CFG->max_con = maxClients; - AP_CFG->dhcp_mode = DHCP_SERVER; - AP_CFG->wifi_retry_interval = 100; + AP_CFG.channel = channel; + AP_CFG.ssid_hidden = ssidHidden; + AP_CFG.max_con = maxClients; + AP_CFG.dhcp_mode = DHCP_SERVER; + AP_CFG.wifi_retry_interval = 100; LT_IM(WIFI, "Creating SoftAP %s", ssid); - if (!AP_CFG->local_ip_addr[0]) { + if (!AP_CFG.local_ip_addr[0]) { LT_DM(WIFI, "Setting default IP config"); softAPConfig((uint32_t)0, (uint32_t)0, (uint32_t)0); } - LT_DM(WIFI, "Static IP: %s / %s / %s", AP_CFG->local_ip_addr, AP_CFG->net_mask, AP_CFG->gateway_ip_addr); + LT_DM(WIFI, "Static IP: %s / %s / %s", AP_CFG.local_ip_addr, AP_CFG.net_mask, AP_CFG.gateway_ip_addr); __wrap_bk_printf_disable(); - OSStatus ret = bk_wlan_start_ap_adv(AP_CFG); + OSStatus ret = bk_wlan_start_ap_adv(&AP_CFG); __wrap_bk_printf_enable(); if (ret != 0) { @@ -50,24 +50,23 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo } bool WiFiClass::softAPConfig(IPAddress localIP, IPAddress gateway, IPAddress subnet) { - dataInitialize(); if (!localIP) { localIP = gateway = IPAddress(192, 168, 43, 1); subnet = IPAddress(255, 255, 255, 0); } - sprintf(AP_CFG->local_ip_addr, IP_FMT, localIP[0], localIP[1], localIP[2], localIP[3]); - sprintf(AP_CFG->net_mask, IP_FMT, subnet[0], subnet[1], subnet[2], subnet[3]); - sprintf(AP_CFG->gateway_ip_addr, IP_FMT, gateway[0], gateway[1], gateway[2], gateway[3]); + sprintf(AP_CFG.local_ip_addr, IP_FMT, localIP[0], localIP[1], localIP[2], localIP[3]); + sprintf(AP_CFG.net_mask, IP_FMT, subnet[0], subnet[1], subnet[2], subnet[3]); + sprintf(AP_CFG.gateway_ip_addr, IP_FMT, gateway[0], gateway[1], gateway[2], gateway[3]); // from wlan_ui.c:1370 if (uap_ip_is_start()) { uap_ip_down(); ip_address_set( BK_STATION, - AP_CFG->dhcp_mode, - AP_CFG->local_ip_addr, - AP_CFG->net_mask, - AP_CFG->gateway_ip_addr, - AP_CFG->dns_server_ip_addr + AP_CFG.dhcp_mode, + AP_CFG.local_ip_addr, + AP_CFG.net_mask, + AP_CFG.gateway_ip_addr, + AP_CFG.dns_server_ip_addr ); uap_ip_start(); } @@ -88,14 +87,14 @@ uint8_t WiFiClass::softAPgetStationNum() { IPAddress WiFiClass::softAPIP() { AP_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->ip); + ip.fromString(IP_STATUS.ip); return ip; } IPAddress WiFiClass::softAPSubnetMask() { AP_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->mask); + ip.fromString(IP_STATUS.mask); return ip; } @@ -123,5 +122,5 @@ String WiFiClass::softAPmacAddress(void) { const String WiFiClass::softAPSSID(void) { AP_GET_LINK_STATUS_RETURN(""); - return AP_CFG->wifi_ssid; + return AP_CFG.wifi_ssid; } diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiEvents.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFiEvents.cpp similarity index 97% rename from arduino/beken-72xx/libraries/WiFi/WiFiEvents.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiEvents.cpp index 5836c1e..6aa3cef 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiEvents.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiEvents.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-07-10. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" #include @@ -53,9 +53,9 @@ void wifiEventHandler(rw_evt_type event) { LT_DM(WIFI, "BK event %u", event); if (event <= RW_EVT_STA_GOT_IP) - pWiFi->data.lastStaEvent = event; + pDATA->lastStaEvent = event; else - pWiFi->data.lastApEvent = event; + pDATA->lastApEvent = event; EventId eventId; EventInfo eventInfo; diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiGeneric.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFiGeneric.cpp similarity index 87% rename from arduino/beken-72xx/libraries/WiFi/WiFiGeneric.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiGeneric.cpp index 20ec5e3..9004219 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiGeneric.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiGeneric.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-26. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" bool WiFiClass::modePriv(WiFiMode mode, WiFiModeAction sta, WiFiModeAction ap) { __wrap_bk_printf_disable(); @@ -45,21 +45,18 @@ bool WiFiClass::modePriv(WiFiMode mode, WiFiModeAction sta, WiFiModeAction ap) { if (ap == WLMODE_ENABLE) { LT_DM(WIFI, "Enabling AP"); // fake it - on BK7231, enabling the AP without starting it breaks all connection attempts - data.apEnabled = true; + DATA->apEnabled = true; wifiEventSendArduino(ARDUINO_EVENT_WIFI_AP_START); } else if (ap == WLMODE_DISABLE) { LT_DM(WIFI, "Disabling AP"); bk_wlan_stop(BK_SOFT_AP); - data.apEnabled = false; + DATA->apEnabled = false; wifiEventSendArduino(ARDUINO_EVENT_WIFI_AP_STOP); } // force checking actual mode again mode = getMode(); - if (!mode) - dataFree(); - LT_HEAP_I(); __wrap_bk_printf_enable(); @@ -68,13 +65,13 @@ bool WiFiClass::modePriv(WiFiMode mode, WiFiModeAction sta, WiFiModeAction ap) { WiFiMode WiFiClass::getMode() { uint8_t sta = !!bk_wlan_has_role(VIF_STA) * WIFI_MODE_STA; - uint8_t ap = data.apEnabled * WIFI_MODE_AP; // report the faked value + uint8_t ap = DATA->apEnabled * WIFI_MODE_AP; // report the faked value return (WiFiMode)(sta | ap); } WiFiStatus WiFiClass::status() { - rw_evt_type status = data.lastStaEvent; - if (status == RW_EVT_STA_CONNECTED && STA_CFG->dhcp_mode == DHCP_DISABLE) + rw_evt_type status = DATA->lastStaEvent; + if (status == RW_EVT_STA_CONNECTED && STA_CFG.dhcp_mode == DHCP_DISABLE) status = RW_EVT_STA_GOT_IP; return eventTypeToStatus(status); } diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiPriv.h b/cores/beken-72xx/arduino/libraries/WiFi/WiFiPrivate.h similarity index 77% rename from arduino/beken-72xx/libraries/WiFi/WiFiPriv.h rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiPrivate.h index 0b9a5d2..eb4eeb0 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiPriv.h +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiPrivate.h @@ -2,7 +2,8 @@ #pragma once -#include +#include +#include extern "C" { @@ -19,6 +20,7 @@ extern "C" { #include #include #include +#include #include #include #include @@ -52,25 +54,41 @@ extern void wifiEventHandler(rw_evt_type event); #define IP_FMT "%u.%u.%u.%u" -#define STA_CFG ((network_InitTypeDef_st *)data.configSta) -#define AP_CFG ((network_InitTypeDef_ap_st *)data.configAp) -#define IP_STATUS ((IPStatusTypedef *)data.statusIp) -#define LINK_STATUS ((LinkStatusTypeDef *)data.statusLink) +typedef struct { + network_InitTypeDef_st configSta; + network_InitTypeDef_ap_st configAp; + unsigned long scannedAt; + SemaphoreHandle_t scanSem; + IPStatusTypedef statusIp; + LinkStatusTypeDef statusLink; + rw_evt_type lastStaEvent; + rw_evt_type lastApEvent; + bool apEnabled; +} WiFiData; + +#define DATA ((WiFiData *)data) +#define pDATA ((WiFiData *)pWiFi->data) +#define cDATA ((WiFiData *)cls->data) + +#define STA_CFG (DATA->configSta) +#define AP_CFG (DATA->configAp) +#define IP_STATUS (DATA->statusIp) +#define LINK_STATUS (DATA->statusLink) #define STA_GET_LINK_STATUS_RETURN(ret) \ { \ if (!sta_ip_is_start()) \ return ret; \ - memset(LINK_STATUS, 0x00, sizeof(LinkStatusTypeDef)); \ - bk_wlan_get_link_status(LINK_STATUS); \ + memset(&LINK_STATUS, 0x00, sizeof(LinkStatusTypeDef)); \ + bk_wlan_get_link_status(&LINK_STATUS); \ } #define STA_GET_IP_STATUS_RETURN(ret) \ { \ if (!sta_ip_is_start()) \ return ret; \ - memset(IP_STATUS, 0x00, sizeof(IPStatusTypedef)); \ - bk_wlan_get_ip_status(IP_STATUS, BK_STATION); \ + memset(&IP_STATUS, 0x00, sizeof(IPStatusTypedef)); \ + bk_wlan_get_ip_status(&IP_STATUS, BK_STATION); \ } #define AP_GET_LINK_STATUS_RETURN(ret) \ @@ -83,8 +101,8 @@ extern void wifiEventHandler(rw_evt_type event); { \ if (!uap_ip_is_start()) \ return ret; \ - memset(IP_STATUS, 0x00, sizeof(IPStatusTypedef)); \ - bk_wlan_get_ip_status(IP_STATUS, BK_SOFT_AP); \ + memset(&IP_STATUS, 0x00, sizeof(IPStatusTypedef)); \ + bk_wlan_get_ip_status(&IP_STATUS, BK_SOFT_AP); \ } } // extern "C" diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiSTA.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFiSTA.cpp similarity index 63% rename from arduino/beken-72xx/libraries/WiFi/WiFiSTA.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiSTA.cpp index 9200a1f..2ac77c6 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiSTA.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiSTA.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" WiFiStatus WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, const uint8_t *bssid, bool connect) { @@ -13,11 +13,11 @@ WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, cons disconnect(false); - strcpy(STA_CFG->wifi_ssid, ssid); + strcpy(STA_CFG.wifi_ssid, ssid); if (passphrase) { - strcpy(STA_CFG->wifi_key, passphrase); + strcpy(STA_CFG.wifi_key, passphrase); } else { - STA_CFG->wifi_bssid[0] = '\0'; + STA_CFG.wifi_bssid[0] = '\0'; } if (reconnect(bssid)) @@ -27,23 +27,21 @@ WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, cons } bool WiFiClass::config(IPAddress localIP, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) { - dataInitialize(); - - STA_CFG->dhcp_mode = localIP ? DHCP_DISABLE : DHCP_CLIENT; + STA_CFG.dhcp_mode = localIP ? DHCP_DISABLE : DHCP_CLIENT; if (localIP) { - sprintf(STA_CFG->local_ip_addr, IP_FMT, localIP[0], localIP[1], localIP[2], localIP[3]); - sprintf(STA_CFG->net_mask, IP_FMT, subnet[0], subnet[1], subnet[2], subnet[3]); - sprintf(STA_CFG->gateway_ip_addr, IP_FMT, gateway[0], gateway[1], gateway[2], gateway[3]); + sprintf(STA_CFG.local_ip_addr, IP_FMT, localIP[0], localIP[1], localIP[2], localIP[3]); + sprintf(STA_CFG.net_mask, IP_FMT, subnet[0], subnet[1], subnet[2], subnet[3]); + sprintf(STA_CFG.gateway_ip_addr, IP_FMT, gateway[0], gateway[1], gateway[2], gateway[3]); if (dns1) { - sprintf(STA_CFG->dns_server_ip_addr, IP_FMT, dns1[0], dns1[1], dns1[2], dns1[3]); + sprintf(STA_CFG.dns_server_ip_addr, IP_FMT, dns1[0], dns1[1], dns1[2], dns1[3]); } else { - STA_CFG->dns_server_ip_addr[0] = '\0'; + STA_CFG.dns_server_ip_addr[0] = '\0'; } } else { - STA_CFG->local_ip_addr[0] = '\0'; - STA_CFG->net_mask[0] = '\0'; - STA_CFG->gateway_ip_addr[0] = '\0'; - STA_CFG->dns_server_ip_addr[0] = '\0'; + STA_CFG.local_ip_addr[0] = '\0'; + STA_CFG.net_mask[0] = '\0'; + STA_CFG.gateway_ip_addr[0] = '\0'; + STA_CFG.dns_server_ip_addr[0] = '\0'; } // from wlan_ui.c:1370 @@ -51,11 +49,11 @@ bool WiFiClass::config(IPAddress localIP, IPAddress gateway, IPAddress subnet, I sta_ip_down(); ip_address_set( BK_STATION, - STA_CFG->dhcp_mode, - STA_CFG->local_ip_addr, - STA_CFG->net_mask, - STA_CFG->gateway_ip_addr, - STA_CFG->dns_server_ip_addr + STA_CFG.dhcp_mode, + STA_CFG.local_ip_addr, + STA_CFG.net_mask, + STA_CFG.gateway_ip_addr, + STA_CFG.dns_server_ip_addr ); sta_ip_start(); } @@ -63,8 +61,7 @@ bool WiFiClass::config(IPAddress localIP, IPAddress gateway, IPAddress subnet, I } bool WiFiClass::reconnect(const uint8_t *bssid) { - dataInitialize(); - if (!bssid && !STA_CFG->wifi_ssid[0]) { + if (!bssid && !STA_CFG.wifi_ssid[0]) { LT_EM(WIFI, "(B)SSID not specified"); goto error; } @@ -72,21 +69,21 @@ bool WiFiClass::reconnect(const uint8_t *bssid) { if (bssid) { LT_IM(WIFI, "Connecting to " MACSTR, MAC2STR(bssid)); } else { - LT_IM(WIFI, "Connecting to %s", STA_CFG->wifi_ssid); + LT_IM(WIFI, "Connecting to %s", STA_CFG.wifi_ssid); } - LT_DM(WIFI, "Data = %p", data.configSta); + LT_DM(WIFI, "Data = %p", DATA->configSta); - STA_CFG->wifi_mode = BK_STATION; - STA_CFG->wifi_retry_interval = 100; + STA_CFG.wifi_mode = BK_STATION; + STA_CFG.wifi_retry_interval = 100; if (bssid) - memcpy(STA_CFG->wifi_bssid, bssid, 6); + memcpy(STA_CFG.wifi_bssid, bssid, 6); else - memset(STA_CFG->wifi_bssid, 0x00, 6); + memset(STA_CFG.wifi_bssid, 0x00, 6); - if (STA_CFG->dhcp_mode == DHCP_DISABLE) { - LT_DM(WIFI, "Static IP: %s / %s / %s", STA_CFG->local_ip_addr, STA_CFG->net_mask, STA_CFG->gateway_ip_addr); - LT_DM(WIFI, "Static DNS: %s", STA_CFG->dns_server_ip_addr); + if (STA_CFG.dhcp_mode == DHCP_DISABLE) { + LT_DM(WIFI, "Static IP: %s / %s / %s", STA_CFG.local_ip_addr, STA_CFG.net_mask, STA_CFG.gateway_ip_addr); + LT_DM(WIFI, "Static DNS: %s", STA_CFG.dns_server_ip_addr); } else { LT_DM(WIFI, "Using DHCP"); } @@ -94,7 +91,7 @@ bool WiFiClass::reconnect(const uint8_t *bssid) { LT_DM(WIFI, "Starting WiFi..."); __wrap_bk_printf_disable(); - bk_wlan_start_sta(STA_CFG); + bk_wlan_start_sta(&STA_CFG); __wrap_bk_printf_enable(); LT_DM(WIFI, "Start OK"); @@ -106,9 +103,9 @@ error: bool WiFiClass::disconnect(bool wifiOff) { #if LT_DEBUG_WIFI - memset(LINK_STATUS, 0x00, sizeof(LinkStatusTypeDef)); - bk_wlan_get_link_status(LINK_STATUS); - LT_DM(WIFI, "Disconnecting from %s (wifiOff=%d)", LINK_STATUS ? LINK_STATUS->ssid : NULL, wifiOff); + memset(&LINK_STATUS, 0x00, sizeof(LinkStatusTypeDef)); + bk_wlan_get_link_status(&LINK_STATUS); + LT_DM(WIFI, "Disconnecting from %s (wifiOff=%d)", LINK_STATUS.ssid, wifiOff); #endif bk_wlan_connection_loss(); if (wifiOff) @@ -127,28 +124,28 @@ bool WiFiClass::getAutoReconnect() { IPAddress WiFiClass::localIP() { STA_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->ip); + ip.fromString(IP_STATUS.ip); return ip; } IPAddress WiFiClass::subnetMask() { STA_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->mask); + ip.fromString(IP_STATUS.mask); return ip; } IPAddress WiFiClass::gatewayIP() { STA_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->gate); + ip.fromString(IP_STATUS.gate); return ip; } IPAddress WiFiClass::dnsIP(uint8_t dns_no) { STA_GET_IP_STATUS_RETURN((uint32_t)0); IPAddress ip; - ip.fromString(IP_STATUS->dns); + ip.fromString(IP_STATUS.dns); return ip; } @@ -191,7 +188,7 @@ bool WiFiClass::setMacAddress(const uint8_t *mac) { const String WiFiClass::SSID() { STA_GET_LINK_STATUS_RETURN(""); - return (char *)LINK_STATUS->ssid; + return (char *)LINK_STATUS.ssid; } const String WiFiClass::psk() { @@ -205,20 +202,20 @@ const String WiFiClass::psk() { uint8_t *WiFiClass::BSSID() { STA_GET_LINK_STATUS_RETURN(NULL); - return LINK_STATUS->bssid; + return LINK_STATUS.bssid; } int32_t WiFiClass::channel() { STA_GET_LINK_STATUS_RETURN(0); - return LINK_STATUS->channel; + return LINK_STATUS.channel; } int8_t WiFiClass::RSSI() { STA_GET_LINK_STATUS_RETURN(0); - return LINK_STATUS->wifi_strength; + return LINK_STATUS.wifi_strength; } WiFiAuthMode WiFiClass::getEncryption() { STA_GET_LINK_STATUS_RETURN(WIFI_AUTH_INVALID); - return securityTypeToAuthMode(LINK_STATUS->security); + return securityTypeToAuthMode(LINK_STATUS.security); } diff --git a/arduino/beken-72xx/libraries/WiFi/WiFiScan.cpp b/cores/beken-72xx/arduino/libraries/WiFi/WiFiScan.cpp similarity index 89% rename from arduino/beken-72xx/libraries/WiFi/WiFiScan.cpp rename to cores/beken-72xx/arduino/libraries/WiFi/WiFiScan.cpp index 1ac5619..ca585fa 100644 --- a/arduino/beken-72xx/libraries/WiFi/WiFiScan.cpp +++ b/cores/beken-72xx/arduino/libraries/WiFi/WiFiScan.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-27. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" static void scanHandler(void *ctx, uint8_t param) { LT_HEAP_I(); @@ -36,7 +36,7 @@ static void scanHandler(void *ctx, uint8_t param) { memcpy(scan->ap[i].bssid.addr, result.ApList[i].bssid, 6); } - cls->data.scannedAt = millis(); + cDATA->scannedAt = millis(); wifiEventSendArduino(ARDUINO_EVENT_WIFI_SCAN_DONE); @@ -45,7 +45,7 @@ end: if (scan->running) { // running == false means it was discarded (timeout) scan->running = false; - xSemaphoreGive(cls->data.scanSem); + xSemaphoreGive(cDATA->scanSem); } LT_HEAP_I(); return; @@ -78,8 +78,8 @@ int16_t WiFiClass::scanNetworks(bool async, bool showHidden, bool passive, uint3 int16_t ret = WIFI_SCAN_RUNNING; if (!async) { LT_IM(WIFI, "Waiting for results"); - xSemaphoreTake(data.scanSem, 1); // reset the semaphore quickly - xSemaphoreTake(data.scanSem, pdMS_TO_TICKS(maxMsPerChannel * 20)); + xSemaphoreTake(DATA->scanSem, 1); // reset the semaphore quickly + xSemaphoreTake(DATA->scanSem, pdMS_TO_TICKS(maxMsPerChannel * 20)); if (scan->running) { scanDelete(); ret = WIFI_SCAN_FAILED; diff --git a/cores/beken-72xx/arduino/src/ArduinoFamily.h b/cores/beken-72xx/arduino/src/ArduinoFamily.h new file mode 100644 index 0000000..9e3801c --- /dev/null +++ b/cores/beken-72xx/arduino/src/ArduinoFamily.h @@ -0,0 +1,27 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +// Provide GPIO names to variant.cpp files +#define LT_VARIANT_INCLUDE "gpio_pub.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +extern void vPortClearInterruptMask(uint32_t ulNewMaskValue); +extern uint32_t ulPortSetInterruptMask(void); + +// TODO +// #define clockCyclesPerMicrosecond() (SystemCoreClock / 1000000L) +// #define clockCyclesToMicroseconds(a) (a * 1000L / (SystemCoreClock / 1000L)) +// #define microsecondsToClockCycles(a) (a * (SystemCoreClock / 1000000L)) + +#define interrupts() vPortClearInterruptMask(0) +#define noInterrupts() ulPortSetInterruptMask() + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/beken-72xx/arduino/src/lt_defs.h b/cores/beken-72xx/arduino/src/lt_defs.h new file mode 100644 index 0000000..6250f1c --- /dev/null +++ b/cores/beken-72xx/arduino/src/lt_defs.h @@ -0,0 +1,8 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_ARD_HAS_WIFI 1 +#define LT_ARD_HAS_SERIAL 1 + +#define LT_ARD_MD5_HOSTAPD 1 diff --git a/arduino/beken-72xx/cores/arduino/main.cpp b/cores/beken-72xx/arduino/src/main.cpp similarity index 78% rename from arduino/beken-72xx/cores/arduino/main.cpp rename to cores/beken-72xx/arduino/src/main.cpp index c813e04..baf3ff7 100644 --- a/arduino/beken-72xx/cores/arduino/main.cpp +++ b/cores/beken-72xx/arduino/src/main.cpp @@ -7,22 +7,14 @@ extern "C" { #include #include -extern int uart_print_port; - -void __sync_synchronize(void) {} - -} // extern "C" - beken_thread_t mainThread; -void initArduino() { - // set default UART output port - uart_print_port = LT_UART_DEFAULT_PORT - 1; #if LT_AUTO_DOWNLOAD_REBOOT && defined(PIN_SERIAL1_RX) && defined(PIN_SERIAL1_TX) +void lt_init_arduino() { // initialize auto-download-reboot parser Serial1.begin(115200); -#endif } +#endif bool startMainTask() { OSStatus ret = rtos_create_thread( @@ -38,3 +30,5 @@ bool startMainTask() { vTaskStartScheduler(); return true; } + +} // extern "C" diff --git a/arduino/beken-72xx/cores/arduino/wiring.c b/cores/beken-72xx/arduino/src/wiring.c similarity index 99% rename from arduino/beken-72xx/cores/arduino/wiring.c rename to cores/beken-72xx/arduino/src/wiring.c index 2e1ee54..a1f5d48 100644 --- a/arduino/beken-72xx/cores/arduino/wiring.c +++ b/cores/beken-72xx/arduino/src/wiring.c @@ -1,6 +1,8 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-19. */ #include +#include + #include #include #include diff --git a/arduino/beken-72xx/cores/arduino/wiring_analog.c b/cores/beken-72xx/arduino/src/wiring_analog.c similarity index 99% rename from arduino/beken-72xx/cores/arduino/wiring_analog.c rename to cores/beken-72xx/arduino/src/wiring_analog.c index be67415..71971df 100644 --- a/arduino/beken-72xx/cores/arduino/wiring_analog.c +++ b/cores/beken-72xx/arduino/src/wiring_analog.c @@ -1,6 +1,8 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-20. */ #include + +#include #include #include diff --git a/arduino/beken-72xx/cores/arduino/wiring_digital.c b/cores/beken-72xx/arduino/src/wiring_digital.c similarity index 98% rename from arduino/beken-72xx/cores/arduino/wiring_digital.c rename to cores/beken-72xx/arduino/src/wiring_digital.c index 6ebce50..27f0016 100644 --- a/arduino/beken-72xx/cores/arduino/wiring_digital.c +++ b/cores/beken-72xx/arduino/src/wiring_digital.c @@ -2,6 +2,8 @@ #include +#include + void pinMode(pin_size_t pinNumber, PinMode pinMode) { PinInfo *pin = pinInfo(pinNumber); if (!pin) diff --git a/arduino/beken-72xx/cores/arduino/wiring_irq.c b/cores/beken-72xx/arduino/src/wiring_irq.c similarity index 64% rename from arduino/beken-72xx/cores/arduino/wiring_irq.c rename to cores/beken-72xx/arduino/src/wiring_irq.c index cc20170..d014b42 100644 --- a/arduino/beken-72xx/cores/arduino/wiring_irq.c +++ b/cores/beken-72xx/arduino/src/wiring_irq.c @@ -2,35 +2,32 @@ #include +#include + static void *irqHandlerList[PINS_COUNT] = {NULL}; static void *irqHandlerArgs[PINS_COUNT] = {NULL}; static bool irqChangeList[PINS_COUNT]; static void irqHandler(unsigned char gpio) { - int pin = -1; - for (pin_size_t i = 0; i < PINS_COUNT; i++) { - if (pinTable[i].gpio == gpio) { - pin = i; - break; + PinInfo *pin = pinByGpio(gpio); + if (pin == NULL) + return; + uint32_t index = pinIndex(pin); + if (!irqHandlerList[index]) + return; + if (irqChangeList[index]) { + if (pin->mode == INPUT_PULLDOWN) { + pin->mode = INPUT_PULLUP; + gpio_int_enable(pin->gpio, GPIO_INT_LEVEL_FALLING, irqHandler); + } else if (pin->mode == INPUT_PULLUP) { + pin->mode = INPUT_PULLDOWN; + gpio_int_enable(pin->gpio, GPIO_INT_LEVEL_RISING, irqHandler); } } - if (pin == -1) - return; - if (!irqHandlerList[pin]) - return; - if (irqChangeList[pin]) { - if (pinTable[pin].mode == INPUT_PULLDOWN) { - pinTable[pin].mode = INPUT_PULLUP; - gpio_int_enable(pinTable[pin].gpio, GPIO_INT_LEVEL_FALLING, irqHandler); - } else if (pinTable[pin].mode == INPUT_PULLUP) { - pinTable[pin].mode = INPUT_PULLDOWN; - gpio_int_enable(pinTable[pin].gpio, GPIO_INT_LEVEL_RISING, irqHandler); - } - } - if (irqHandlerArgs[pin] == NULL) { - ((voidFuncPtr)irqHandlerList[pin])(); + if (irqHandlerArgs[index] == NULL) { + ((voidFuncPtr)irqHandlerList[index])(); } else { - ((voidFuncPtrParam)irqHandlerList[pin])(irqHandlerArgs[pin]); + ((voidFuncPtrParam)irqHandlerList[index])(irqHandlerArgs[index]); } } @@ -44,6 +41,7 @@ void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, return; if (!pinSupported(pin, PIN_IRQ)) return; + uint32_t index = pinIndex(pin); uint32_t event = 0; PinMode modeNew = 0; bool change = 0; @@ -77,9 +75,9 @@ void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, default: return; } - irqHandlerList[interruptNumber] = callback; - irqHandlerArgs[interruptNumber] = param; - irqChangeList[interruptNumber] = change; + irqHandlerList[index] = callback; + irqHandlerArgs[index] = param; + irqChangeList[index] = change; gpio_int_enable(pin->gpio, event, irqHandler); pin->enabled |= PIN_IRQ | PIN_GPIO; pin->mode = modeNew; @@ -91,9 +89,10 @@ void detachInterrupt(pin_size_t interruptNumber) { return; if (!pinSupported(pin, PIN_IRQ)) return; - irqHandlerList[interruptNumber] = NULL; - irqHandlerArgs[interruptNumber] = NULL; - irqChangeList[interruptNumber] = false; + uint32_t index = pinIndex(pin); + irqHandlerList[index] = NULL; + irqHandlerArgs[index] = NULL; + irqChangeList[index] = false; gpio_int_disable(pin->gpio); pin->enabled &= ~PIN_IRQ; } diff --git a/platform/beken-72xx/config/lwipopts.h b/cores/beken-72xx/base/config/lwipopts.h similarity index 85% rename from platform/beken-72xx/config/lwipopts.h rename to cores/beken-72xx/base/config/lwipopts.h index c60d282..13eaa4d 100644 --- a/platform/beken-72xx/config/lwipopts.h +++ b/cores/beken-72xx/base/config/lwipopts.h @@ -2,9 +2,7 @@ #pragma once -#include "lwip-2.0.2/port/lwipopts.h" - -#include +#include_next "lwipopts.h" // mDNS support #undef MEMP_NUM_UDP_PCB diff --git a/arduino/libretuya/libraries/HTTPClient/strptime/.clang-format b/cores/beken-72xx/base/fixups/.clang-format similarity index 100% rename from arduino/libretuya/libraries/HTTPClient/strptime/.clang-format rename to cores/beken-72xx/base/fixups/.clang-format diff --git a/platform/beken-72xx/fixups/arch_main.c b/cores/beken-72xx/base/fixups/arch_main.c similarity index 97% rename from platform/beken-72xx/fixups/arch_main.c rename to cores/beken-72xx/base/fixups/arch_main.c index 1ca42b1..0e22688 100644 --- a/platform/beken-72xx/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/platform/beken-72xx/fixups/ate_app.c b/cores/beken-72xx/base/fixups/ate_app.c similarity index 100% rename from platform/beken-72xx/fixups/ate_app.c rename to cores/beken-72xx/base/fixups/ate_app.c diff --git a/platform/beken-72xx/fixups/clock_cal.c b/cores/beken-72xx/base/fixups/clock_cal.c similarity index 100% rename from platform/beken-72xx/fixups/clock_cal.c rename to cores/beken-72xx/base/fixups/clock_cal.c diff --git a/platform/beken-72xx/fixups/clock_rtos.c b/cores/beken-72xx/base/fixups/clock_rtos.c similarity index 99% rename from platform/beken-72xx/fixups/clock_rtos.c rename to cores/beken-72xx/base/fixups/clock_rtos.c index 2926cb4..fb7596a 100644 --- a/platform/beken-72xx/fixups/clock_rtos.c +++ b/cores/beken-72xx/base/fixups/clock_rtos.c @@ -11,7 +11,7 @@ #include "sys_rtos.h" #include "uart_pub.h" -// from LibreTuyaConfig.h +// from lt_config.h #ifndef LT_MICROS_HIGH_RES #define LT_MICROS_HIGH_RES 1 #endif diff --git a/cores/beken-72xx/base/fixups/gcc10.c b/cores/beken-72xx/base/fixups/gcc10.c new file mode 100644 index 0000000..2b97eac --- /dev/null +++ b/cores/beken-72xx/base/fixups/gcc10.c @@ -0,0 +1,7 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-13. */ + +// Compiling with GCC 10.3.1 requires this or it will produce linker errors. +// See: +// - https://github.com/purduesigbots/pros/issues/153#issuecomment-519335375 +// - https://stackoverflow.com/a/64664385 +void __sync_synchronize(void) {} diff --git a/cores/beken-72xx/base/fixups/generic.h b/cores/beken-72xx/base/fixups/generic.h new file mode 100644 index 0000000..f729b13 --- /dev/null +++ b/cores/beken-72xx/base/fixups/generic.h @@ -0,0 +1,17 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-01. */ + +#include_next "generic.h" + +#pragma once + +// allow lwIP to define these (Beken, why) +#undef htons +#undef ntohs +#undef htonl +#undef ntohl + +// fix conflicts with std::max() and std::min() +#ifdef __cplusplus +#undef max +#undef min +#endif diff --git a/cores/beken-72xx/base/fixups/include.h b/cores/beken-72xx/base/fixups/include.h new file mode 100644 index 0000000..ebff54e --- /dev/null +++ b/cores/beken-72xx/base/fixups/include.h @@ -0,0 +1,8 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#include_next "include.h" + +#pragma once + +// force including fixups/generic.h, even by BDK/include.h +#include "generic.h" diff --git a/platform/beken-72xx/fixups/intc.c b/cores/beken-72xx/base/fixups/intc.c similarity index 100% rename from platform/beken-72xx/fixups/intc.c rename to cores/beken-72xx/base/fixups/intc.c diff --git a/platform/beken-72xx/config/param_config.h b/cores/beken-72xx/base/fixups/param_config.h similarity index 100% rename from platform/beken-72xx/config/param_config.h rename to cores/beken-72xx/base/fixups/param_config.h index 759eda6..68cef1b 100644 --- a/platform/beken-72xx/config/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/platform/beken-72xx/fixups/inc/uart_pub.h b/cores/beken-72xx/base/fixups/uart_pub.h similarity index 94% rename from platform/beken-72xx/fixups/inc/uart_pub.h rename to cores/beken-72xx/base/fixups/uart_pub.h index ca8521e..9626f78 100644 --- a/platform/beken-72xx/fixups/inc/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_api.c b/cores/beken-72xx/base/lt_api.c new file mode 100644 index 0000000..c8994e9 --- /dev/null +++ b/cores/beken-72xx/base/lt_api.c @@ -0,0 +1,190 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#include +#include + +// can't include as it collides with on Windows -_- +#define REG_FLASH_BASE 0x00803000 +#define REG_FLASH_OPERATE_SW (REG_FLASH_BASE + 0 * 4) +#define REG_FLASH_RDID (REG_FLASH_BASE + 4 * 4) +#define FLASH_BUSY_SW (0x01UL << 31) +#define FLASH_WP_VALUE (0x01UL << 30) +#define FLASH_OP_SW (0x01UL << 29) +#define FLASH_OP_TYPE_POS 24 +#define FLASH_OP_RDID 20 + +void lt_init_family() { + // set default UART output port + uart_print_port = LT_UART_DEFAULT_PORT - 1; +} + +/* _____ _____ _ _ + / ____| __ \| | | | + | | | |__) | | | | + | | | ___/| | | | + | |____| | | |__| | + \_____|_| \____*/ +lt_cpu_model_t lt_cpu_get_model() { + uint8_t chipId = *(uint8_t *)(SCTRL_CHIP_ID); + return CPU_MODEL_ENUM(FAMILY, chipId); +} + +uint32_t lt_cpu_get_unique_id() { + return lt_cpu_get_mac_id(); +} + +uint32_t lt_cpu_get_mac_id() { + uint8_t mac[6]; + cfg_load_mac(mac); // force loading MAC from TLV (ignore user-set WiFi MAC) + return (mac[3]) | (mac[4] << 8) | (mac[5] << 16); +} + +const char *lt_cpu_get_core_type() { + return "ARM968E-S"; +} + +/*_____ _ + | __ \ (_) + | | | | _____ ___ ___ ___ + | | | |/ _ \ \ / / |/ __/ _ \ + | |__| | __/\ V /| | (_| __/ + |_____/ \___| \_/ |_|\___\__*/ +void lt_reboot() { + bk_reboot(); +} + +bool lt_reboot_download_mode() { + bk_reboot(); + return true; +} + +lt_reboot_reason_t lt_get_reboot_reason() { + switch (bk_misc_get_start_type()) { + case RESET_SOURCE_POWERON: + return REBOOT_REASON_POWER; + case RESET_SOURCE_REBOOT: + return REBOOT_REASON_SOFTWARE; + case RESET_SOURCE_WATCHDOG: + return REBOOT_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 REBOOT_REASON_CRASH; + case RESET_SOURCE_DEEPPS_GPIO: + case RESET_SOURCE_DEEPPS_RTC: + case RESET_SOURCE_DEEPPS_USB: + return REBOOT_REASON_SLEEP; + default: + return REBOOT_REASON_UNKNOWN; + } +} + +/*______ _ _ + | ____| | | | + | |__ | | __ _ ___| |__ + | __| | |/ _` / __| '_ \ + | | | | (_| \__ \ | | | + |_| |_|\__,_|___/_| |*/ +lt_flash_id_t lt_flash_get_id() { + uint32_t data = (FLASH_OP_RDID << FLASH_OP_TYPE_POS) | FLASH_OP_SW | FLASH_WP_VALUE; + REG_WRITE(REG_FLASH_OPERATE_SW, data); + while (REG_READ(REG_FLASH_OPERATE_SW) & FLASH_BUSY_SW) {} + lt_flash_id_t id = { + .manufacturer_id = REG_RD8(REG_FLASH_RDID, 2), + .chip_id = REG_RD8(REG_FLASH_RDID, 1), + .chip_size_id = REG_RD8(REG_FLASH_RDID, 0), + }; + return id; +} + +/*__ __ + | \/ | + | \ / | ___ _ __ ___ ___ _ __ _ _ + | |\/| |/ _ \ '_ ` _ \ / _ \| '__| | | | + | | | | __/ | | | | | (_) | | | |_| | + |_| |_|\___|_| |_| |_|\___/|_| \__, | + __/ | + |__*/ +uint32_t lt_ram_get_size() { + return 256 * 1024; +} + +uint32_t lt_heap_get_size() { +#if configDYNAMIC_HEAP_SIZE + extern unsigned char _empty_ram; +#if CFG_SOC_NAME == SOC_BK7231N + return (0x00400000 + 192 * 1024) - (uint32_t)(&_empty_ram); +#else + return (0x00400000 + 256 * 1024) - (uint32_t)(&_empty_ram); +#endif +#else + return configTOTAL_HEAP_SIZE; +#endif +} + +/* ____ _______ + / __ \__ __|/\ + | | | | | | / \ + | | | | | | / /\ \ + | |__| | | |/ ____ \ + \____/ |_/_/ \*/ + +lt_ota_type_t lt_ota_get_type() { + return OTA_TYPE_SINGLE; +} + +bool lt_ota_is_valid(uint8_t index) { + if (index != 0) + return false; + // check download RBL + // TODO: maybe check header CRC or even binary hashes + uint32_t magic; + lt_flash_read(FLASH_DOWNLOAD_OFFSET, (uint8_t *)&magic, 4); + return magic == 0x004C4252; // "RBL\0", little-endian +} + +uint8_t lt_ota_dual_get_current() { + return 0; +} + +uint8_t lt_ota_dual_get_stored() { + return 0; +} + +bool lt_ota_switch(bool revert) { + if (!lt_ota_is_valid(0)) + // no valid "download" image + // - return false when trying to activate + // - return true when trying to revert + return revert; + if (revert) { + // there's a valid "download" image, which has to be removed + return lt_flash_erase_block(FLASH_DOWNLOAD_OFFSET); + } + return true; +} + +/*_ __ _ _ _ + \ \ / / | | | | | | + \ \ /\ / /_ _| |_ ___| |__ __| | ___ __ _ + \ \/ \/ / _` | __/ __| '_ \ / _` |/ _ \ / _` | + \ /\ / (_| | || (__| | | | (_| | (_) | (_| | + \/ \/ \__,_|\__\___|_| |_|\__,_|\___/ \__, | + __/ | + |___*/ +bool lt_wdt_enable(uint32_t timeout) { + wdt_ctrl(WCMD_SET_PERIOD, &timeout); + wdt_ctrl(WCMD_POWER_UP, NULL); + return true; +} + +void lt_wdt_disable() { + wdt_ctrl(WCMD_POWER_DOWN, NULL); +} + +void lt_wdt_feed() { + wdt_ctrl(WCMD_RELOAD_PERIOD, NULL); +} diff --git a/cores/beken-72xx/base/lt_defs.h b/cores/beken-72xx/base/lt_defs.h new file mode 100644 index 0000000..e80ef9d --- /dev/null +++ b/cores/beken-72xx/base/lt_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#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 +#define LT_REALLOC_FUNC pvPortRealloc +#define LT_REMALLOC 1 diff --git a/cores/beken-72xx/base/lt_family.h b/cores/beken-72xx/base/lt_family.h new file mode 100644 index 0000000..4484a1d --- /dev/null +++ b/cores/beken-72xx/base/lt_family.h @@ -0,0 +1,16 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#pragma once + +#include LT_VARIANT_H + +// Choose the main UART output port +#ifndef LT_UART_DEFAULT_PORT +#if HAS_SERIAL2 +#define LT_UART_DEFAULT_PORT 2 +#elif HAS_SERIAL1 +#define LT_UART_DEFAULT_PORT 1 +#else +#error "No serial port is available" +#endif +#endif diff --git a/arduino/beken-72xx/port/flashdb/fal_flash_bk72xx_port.c b/cores/beken-72xx/base/port/fal_flash_bk72xx_port.c similarity index 94% rename from arduino/beken-72xx/port/flashdb/fal_flash_bk72xx_port.c rename to cores/beken-72xx/base/port/fal_flash_bk72xx_port.c index abca7a0..d8b723a 100644 --- a/arduino/beken-72xx/port/flashdb/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) @@ -47,6 +46,7 @@ static int write(long offset, const uint8_t *buf, size_t size) { static int erase(long offset, size_t size) { unprotect(); + offset &= ~(FLASH_ERASE_MIN_SIZE - 1); size = ((size - 1) / FLASH_ERASE_MIN_SIZE) + 1; for (uint16_t i = 0; i < size; i++) { uint32_t addr = offset + i * FLASH_ERASE_MIN_SIZE; diff --git a/arduino/beken-72xx/port/printf/printf.c b/cores/beken-72xx/base/port/printf.c similarity index 79% rename from arduino/beken-72xx/port/printf/printf.c rename to cores/beken-72xx/base/port/printf.c index 93fd8ca..4967136 100644 --- a/arduino/beken-72xx/port/printf/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/arduino/beken-72xx/port/printf/printf_port.h b/cores/beken-72xx/base/port/printf_port.h similarity index 55% rename from arduino/beken-72xx/port/printf/printf_port.h rename to cores/beken-72xx/base/port/printf_port.h index a3242a7..c627e53 100644 --- a/arduino/beken-72xx/port/printf/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_private.h b/cores/beken-72xx/base/sdk_private.h new file mode 100644 index 0000000..41d6a56 --- /dev/null +++ b/cores/beken-72xx/base/sdk_private.h @@ -0,0 +1,35 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-18. */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +// most stuff is here +#include +// other includes +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern uint8_t system_mac[]; +extern uint32_t wdt_ctrl(uint32_t cmd, void *param); +extern int uart_print_port; + +// conflict with stl_algobase.h +#undef min +#undef max + +// from fixups/arch_main.c +extern unsigned char __bk_rf_is_init; + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/platform/beken-72xx/fixups/wrap_BkDriverFlash.c b/cores/beken-72xx/base/wraps/BkDriverFlash.c similarity index 100% rename from platform/beken-72xx/fixups/wrap_BkDriverFlash.c rename to cores/beken-72xx/base/wraps/BkDriverFlash.c diff --git a/platform/beken-72xx/fixups/wrap_wlan_ui.c b/cores/beken-72xx/base/wraps/wlan_ui.c similarity index 98% rename from platform/beken-72xx/fixups/wrap_wlan_ui.c rename to cores/beken-72xx/base/wraps/wlan_ui.c index a698c70..c003e5c 100644 --- a/platform/beken-72xx/fixups/wrap_wlan_ui.c +++ b/cores/beken-72xx/base/wraps/wlan_ui.c @@ -1,5 +1,7 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-07-01. */ +#if 0 + #include #include @@ -26,3 +28,5 @@ void __wrap_bk_wlan_sta_init_adv(network_InitTypeDef_adv_st *inNetworkInitParaAd } g_sta_param_ptr->fast_connect_set = fast_connect; } + +#endif diff --git a/platform/beken-72xx/ld/bk7231_bsp.ld b/cores/beken-72xx/misc/bk7231_bsp.template.ld similarity index 97% rename from platform/beken-72xx/ld/bk7231_bsp.ld rename to cores/beken-72xx/misc/bk7231_bsp.template.ld index 66af5ff..b0e90b0 100644 --- a/platform/beken-72xx/ld/bk7231_bsp.ld +++ b/cores/beken-72xx/misc/bk7231_bsp.template.ld @@ -29,7 +29,7 @@ /* Split memory into area for vectors and ram */ MEMORY { - flash (rx) : ORIGIN = 0x00010000, LENGTH = 1912K + flash (rx) : ORIGIN = ${BOARD_BUILD.BKOFFSET_APP}, LENGTH = ${BOARD_BUILD.BKRBL_SIZE_APP} ram (rw!x): ORIGIN = 0x00400100, LENGTH = 256k - 0x100 } diff --git a/platform/beken-72xx/ld/bk7231n_bsp.ld b/cores/beken-72xx/misc/bk7231n_bsp.template.ld similarity index 99% rename from platform/beken-72xx/ld/bk7231n_bsp.ld rename to cores/beken-72xx/misc/bk7231n_bsp.template.ld index 8b507cd..c7ab853 100644 --- a/platform/beken-72xx/ld/bk7231n_bsp.ld +++ b/cores/beken-72xx/misc/bk7231n_bsp.template.ld @@ -29,7 +29,7 @@ /* Split memory into area for vectors and ram */ MEMORY { - flash (rx) : ORIGIN = 0x00010000, LENGTH = 1912K + flash (rx) : ORIGIN = ${BOARD_BUILD.BKOFFSET_APP}, LENGTH = ${BOARD_BUILD.BKRBL_SIZE_APP} tcm (rw!x): ORIGIN = 0x003F0000, LENGTH = 60k - 512 itcm (rwx): ORIGIN = 0x003FEE00, LENGTH = 4k + 512 ram (rw!x): ORIGIN = 0x00400100, LENGTH = 192k - 0x100 diff --git a/platform/beken-72xx/openocd/bk72xx.cfg b/cores/beken-72xx/misc/bk72xx.cfg similarity index 100% rename from platform/beken-72xx/openocd/bk72xx.cfg rename to cores/beken-72xx/misc/bk72xx.cfg diff --git a/arduino/libretuya/api/SoftwareSerial.cpp b/cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.cpp similarity index 96% rename from arduino/libretuya/api/SoftwareSerial.cpp rename to cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.cpp index 00ad31d..af60a5f 100644 --- a/arduino/libretuya/api/SoftwareSerial.cpp +++ b/cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.cpp @@ -2,7 +2,7 @@ #include "SoftwareSerial.h" -#ifdef LT_ARD_HAS_SOFTSERIAL +#if LT_ARD_HAS_SOFTSERIAL SoftwareSerial::SoftwareSerial(pin_size_t receivePin, pin_size_t transmitPin, bool inverted) { data.rx.buf = NULL; diff --git a/arduino/libretuya/api/SoftwareSerial.h b/cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.h similarity index 96% rename from arduino/libretuya/api/SoftwareSerial.h rename to cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.h index 5bcafda..151b194 100644 --- a/arduino/libretuya/api/SoftwareSerial.h +++ b/cores/common/arduino/libraries/api/SoftwareSerial/SoftwareSerial.h @@ -2,7 +2,7 @@ #pragma once -#ifdef LT_ARD_HAS_SOFTSERIAL +#if LT_ARD_HAS_SOFTSERIAL || DOXYGEN #include #include diff --git a/arduino/libretuya/api/WiFi/WiFi.cpp b/cores/common/arduino/libraries/api/WiFi/WiFi.cpp similarity index 100% rename from arduino/libretuya/api/WiFi/WiFi.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFi.cpp diff --git a/arduino/libretuya/api/WiFi/WiFi.h b/cores/common/arduino/libraries/api/WiFi/WiFi.h similarity index 94% rename from arduino/libretuya/api/WiFi/WiFi.h rename to cores/common/arduino/libraries/api/WiFi/WiFi.h index cd1b8e5..92e0266 100644 --- a/arduino/libretuya/api/WiFi/WiFi.h +++ b/cores/common/arduino/libraries/api/WiFi/WiFi.h @@ -22,24 +22,22 @@ #pragma once #include -#include +#include #include #include #include #include "WiFiType.h" -#ifdef LT_ARD_HAS_WIFI -// family's data structure -#include -#endif +#include +#include +#include +#include class WiFiClass { public: -#ifdef LT_ARD_HAS_WIFI // must be public for WiFiEvents & WiFiScan static handlers - WiFiData data; -#endif + void *data; WiFiScanData *scan = NULL; public: /* WiFi.cpp */ @@ -73,6 +71,12 @@ class WiFiClass { static uint8_t calculateSubnetCIDR(IPAddress subnetMask); static String macToString(uint8_t *mac); + static void resetNetworkInfo(WiFiNetworkInfo &info); + + private: /* WiFiGeneric.cpp */ + bool restoreSTAConfig(const WiFiNetworkInfo &info); + bool restoreAPConfig(const WiFiNetworkInfo &info); + protected: /* WiFiEvents.cpp */ static std::vector handlers; diff --git a/arduino/libretuya/api/WiFi/WiFiAP.cpp b/cores/common/arduino/libraries/api/WiFi/WiFiAP.cpp similarity index 100% rename from arduino/libretuya/api/WiFi/WiFiAP.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFiAP.cpp diff --git a/arduino/libretuya/api/WiFi/WiFiEvents.cpp b/cores/common/arduino/libraries/api/WiFi/WiFiEvents.cpp similarity index 100% rename from arduino/libretuya/api/WiFi/WiFiEvents.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFiEvents.cpp diff --git a/arduino/libretuya/api/WiFi/WiFiEvents.h b/cores/common/arduino/libraries/api/WiFi/WiFiEvents.h similarity index 100% rename from arduino/libretuya/api/WiFi/WiFiEvents.h rename to cores/common/arduino/libraries/api/WiFi/WiFiEvents.h diff --git a/arduino/libretuya/api/WiFi/WiFiGeneric.cpp b/cores/common/arduino/libraries/api/WiFi/WiFiGeneric.cpp similarity index 72% rename from arduino/libretuya/api/WiFi/WiFiGeneric.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFiGeneric.cpp index 2621f5d..7e205bc 100644 --- a/arduino/libretuya/api/WiFi/WiFiGeneric.cpp +++ b/cores/common/arduino/libraries/api/WiFi/WiFiGeneric.cpp @@ -2,6 +2,10 @@ #include "WiFi.h" +#if LT_HAS_FREERTOS +#include +#endif + bool WiFiClass::mode(WiFiMode mode) { // store a pointer to WiFi for WiFiEvents.cpp pWiFi = this; @@ -115,3 +119,36 @@ String WiFiClass::macToString(uint8_t *mac) { sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return macStr; } + +void WiFiClass::resetNetworkInfo(WiFiNetworkInfo &info) { + LT_VM(WIFI, "Resetting network info: %s", info.ssid); + free(info.ssid); + free(info.password); + free(info.bssid); + // wipe the structure, except IP addresses + memset(&info, 0x00, sizeof(WiFiNetworkInfo) - 5 * sizeof(uint32_t)); +} + +bool WiFiClass::restoreSTAConfig(const WiFiNetworkInfo &info) { + LT_DM(WIFI, "Restoring %s config: %s", "STA", info.ssid); + if (!info.ssid) + return false; + if (info.localIP) { + LT_DM(WIFI, "Restoring STA IP config"); + if (!config(info.localIP, info.gateway, info.subnet, info.dns1, info.dns2)) + return false; + } + return begin(info.ssid, info.password, info.channel, info.bssid); +} + +bool WiFiClass::restoreAPConfig(const WiFiNetworkInfo &info) { + LT_DM(WIFI, "Restoring %s config: %s", "AP", info.ssid); + if (!info.ssid) + return false; + if (info.localIP) { + LT_DM(WIFI, "Restoring AP IP config"); + if (!softAPConfig(info.localIP, info.gateway, info.subnet)) + return false; + } + return softAP(info.ssid, info.password, info.channel, info.ssidHidden); +} diff --git a/arduino/libretuya/api/WiFi/WiFiSTA.cpp b/cores/common/arduino/libraries/api/WiFi/WiFiSTA.cpp similarity index 100% rename from arduino/libretuya/api/WiFi/WiFiSTA.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFiSTA.cpp diff --git a/arduino/libretuya/api/WiFi/WiFiScan.cpp b/cores/common/arduino/libraries/api/WiFi/WiFiScan.cpp similarity index 97% rename from arduino/libretuya/api/WiFi/WiFiScan.cpp rename to cores/common/arduino/libraries/api/WiFi/WiFiScan.cpp index aabf052..6cd2952 100644 --- a/arduino/libretuya/api/WiFi/WiFiScan.cpp +++ b/cores/common/arduino/libraries/api/WiFi/WiFiScan.cpp @@ -24,7 +24,7 @@ int16_t WiFiClass::scanComplete() { void WiFiClass::scanInit() { if (scan) return; - scan = (WiFiScanData *)zalloc(sizeof(WiFiScanData)); + scan = (WiFiScanData *)calloc(1, sizeof(WiFiScanData)); } void WiFiClass::scanDelete() { diff --git a/arduino/libretuya/api/WiFi/WiFiType.h b/cores/common/arduino/libraries/api/WiFi/WiFiType.h similarity index 95% rename from arduino/libretuya/api/WiFi/WiFiType.h rename to cores/common/arduino/libraries/api/WiFi/WiFiType.h index e5ce074..027f00b 100644 --- a/arduino/libretuya/api/WiFi/WiFiType.h +++ b/cores/common/arduino/libraries/api/WiFi/WiFiType.h @@ -128,6 +128,20 @@ typedef enum { WIFI_REASON_ROAMING = 207, } wifi_err_reason_t; +typedef struct { + char *ssid; + char *password; + uint8_t *bssid; + bool ssidHidden; + int channel; + int auth; + uint32_t localIP; + uint32_t subnet; + uint32_t gateway; + uint32_t dns1; + uint32_t dns2; +} WiFiNetworkInfo; + typedef struct { char *ssid; WiFiAuthMode auth; diff --git a/arduino/libretuya/api/FS.cpp b/cores/common/arduino/libraries/common/FS/FS.cpp similarity index 100% rename from arduino/libretuya/api/FS.cpp rename to cores/common/arduino/libraries/common/FS/FS.cpp diff --git a/arduino/libretuya/api/FS.h b/cores/common/arduino/libraries/common/FS/FS.h similarity index 100% rename from arduino/libretuya/api/FS.h rename to cores/common/arduino/libraries/common/FS/FS.h diff --git a/arduino/libretuya/libraries/NetUtils/IPv6Address.cpp b/cores/common/arduino/libraries/common/IPv6Address/IPv6Address.cpp similarity index 99% rename from arduino/libretuya/libraries/NetUtils/IPv6Address.cpp rename to cores/common/arduino/libraries/common/IPv6Address/IPv6Address.cpp index af94839..454dcb1 100644 --- a/arduino/libretuya/libraries/NetUtils/IPv6Address.cpp +++ b/cores/common/arduino/libraries/common/IPv6Address/IPv6Address.cpp @@ -54,6 +54,7 @@ size_t IPv6Address::printTo(Print &p) const { } return n; */ + return 0; } String IPv6Address::toString() const { diff --git a/arduino/libretuya/libraries/NetUtils/IPv6Address.h b/cores/common/arduino/libraries/common/IPv6Address/IPv6Address.h similarity index 100% rename from arduino/libretuya/libraries/NetUtils/IPv6Address.h rename to cores/common/arduino/libraries/common/IPv6Address/IPv6Address.h diff --git a/arduino/libretuya/libraries/NetUtils/api/IPv6Address.h b/cores/common/arduino/libraries/common/IPv6Address/api/IPv6Address.h similarity index 100% rename from arduino/libretuya/libraries/NetUtils/api/IPv6Address.h rename to cores/common/arduino/libraries/common/IPv6Address/api/IPv6Address.h diff --git a/arduino/libretuya/libraries/MD5/MD5.h b/cores/common/arduino/libraries/common/MD5/MD5.h similarity index 85% rename from arduino/libretuya/libraries/MD5/MD5.h rename to cores/common/arduino/libraries/common/MD5/MD5.h index 88e484e..2971867 100644 --- a/arduino/libretuya/libraries/MD5/MD5.h +++ b/cores/common/arduino/libraries/common/MD5/MD5.h @@ -3,23 +3,22 @@ #pragma once #include -#include // available built-in implementations -#if LT_MD5_USE_POLARSSL +#if LT_ARD_MD5_POLARSSL #include "MD5PolarSSLImpl.h" #endif -#if LT_MD5_USE_MBEDTLS +#if LT_ARD_MD5_MBEDTLS #include "MD5MbedTLSImpl.h" #endif -#if LT_MD5_USE_HOSTAPD +#if LT_ARD_MD5_HOSTAPD #include "MD5HostapdImpl.h" #endif // common API #ifdef __cplusplus extern "C" { -#endif +#endif // __cplusplus #ifndef LT_MD5_CTX_T #define LT_MD5_CTX_T void @@ -33,5 +32,5 @@ void MD5Update(LT_MD5_CTX_T *context, const unsigned char *buf, unsigned len); void MD5Final(unsigned char digest[16], LT_MD5_CTX_T *context); #ifdef __cplusplus -} +} // extern "C" #endif diff --git a/arduino/libretuya/libraries/MD5/MD5HostapdImpl.h b/cores/common/arduino/libraries/common/MD5/MD5HostapdImpl.h similarity index 66% rename from arduino/libretuya/libraries/MD5/MD5HostapdImpl.h rename to cores/common/arduino/libraries/common/MD5/MD5HostapdImpl.h index 76624da..5bc092b 100644 --- a/arduino/libretuya/libraries/MD5/MD5HostapdImpl.h +++ b/cores/common/arduino/libraries/common/MD5/MD5HostapdImpl.h @@ -6,7 +6,12 @@ extern "C" { #endif -#include +struct MD5Context { + unsigned long buf[4]; + unsigned long bits[2]; + unsigned char in[64]; +}; + #define LT_MD5_CTX_T struct MD5Context #ifdef __cplusplus diff --git a/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.cpp b/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.cpp new file mode 100644 index 0000000..8997282 --- /dev/null +++ b/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.cpp @@ -0,0 +1,24 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-07-11. */ + +#if LT_ARD_MD5_MBEDTLS + +extern "C" { + +#include + +void MD5Init(mbedtls_md5_context *context) { + mbedtls_md5_init(context); + mbedtls_md5_starts(context); +} + +void MD5Update(mbedtls_md5_context *context, const unsigned char *buf, unsigned len) { + mbedtls_md5_update(context, buf, len); +} + +void MD5Final(unsigned char digest[16], mbedtls_md5_context *context) { + mbedtls_md5_finish(context, digest); +} + +} // extern "C" + +#endif // LT_ARD_MD5_MBEDTLS diff --git a/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.h b/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.h new file mode 100644 index 0000000..76369c8 --- /dev/null +++ b/cores/common/arduino/libraries/common/MD5/MD5MbedTLSImpl.h @@ -0,0 +1,19 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-07-11. */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + unsigned long total[2]; /*!< number of bytes processed */ + unsigned long state[4]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} mbedtls_md5_context; + +#define LT_MD5_CTX_T mbedtls_md5_context + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.cpp b/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.cpp new file mode 100644 index 0000000..18f9d2c --- /dev/null +++ b/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.cpp @@ -0,0 +1,24 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-03. */ + +#if LT_ARD_MD5_POLARSSL + +extern "C" { + +#include + +void MD5Init(md5_context *context) { + md5_init(context); + md5_starts(context); +} + +void MD5Update(md5_context *context, const unsigned char *buf, unsigned len) { + md5_update(context, buf, len); +} + +void MD5Final(unsigned char digest[16], md5_context *context) { + md5_finish(context, digest); +} + +} // extern "C" + +#endif // LT_ARD_MD5_POLARSSL diff --git a/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.h b/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.h new file mode 100644 index 0000000..6eb7eaa --- /dev/null +++ b/cores/common/arduino/libraries/common/MD5/MD5PolarSSLImpl.h @@ -0,0 +1,19 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-03. */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + unsigned long total[2]; /*!< number of bytes processed */ + unsigned long state[4]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ +} md5_context; + +#define LT_MD5_CTX_T md5_context + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/arduino/libretuya/api/Preferences.h b/cores/common/arduino/libraries/common/Preferences/Preferences.h similarity index 100% rename from arduino/libretuya/api/Preferences.h rename to cores/common/arduino/libraries/common/Preferences/Preferences.h diff --git a/arduino/libretuya/libraries/Update/Update.cpp b/cores/common/arduino/libraries/common/Update/Update.cpp similarity index 95% rename from arduino/libretuya/libraries/Update/Update.cpp rename to cores/common/arduino/libraries/common/Update/Update.cpp index 9f71167..13f83de 100644 --- a/arduino/libretuya/libraries/Update/Update.cpp +++ b/cores/common/arduino/libraries/common/Update/Update.cpp @@ -18,9 +18,9 @@ bool UpdateClass::begin(size_t size, int command, int unused2, uint8_t unused3, return false; cleanup(); - LT_DM(OTA, "begin(%u, ...) / OTA curr: %u, trgt: %u", size, LT.otaGetRunning(), LT.otaGetTarget()); + LT_DM(OTA, "begin(%u, ...) / OTA curr: %u, scheme: %u", size, lt_ota_dual_get_current(), lt_ota_get_uf2_scheme()); - ctx = uf2_ctx_init(LT.otaGetTarget(), FAMILY); + ctx = uf2_ctx_init(lt_ota_get_uf2_scheme(), FAMILY); info = uf2_info_init(); if (!size) { @@ -54,8 +54,8 @@ bool UpdateClass::end(bool evenIfRemaining) { return false; } // TODO what is evenIfRemaining for? - if (!LT.otaSwitch()) { - // try to activate the second OTA + // try to activate the second OTA + if (!lt_ota_switch(/* revert= */ false)) { cleanup(UPDATE_ERROR_ACTIVATE); return false; } diff --git a/arduino/libretuya/libraries/Update/Update.h b/cores/common/arduino/libraries/common/Update/Update.h similarity index 98% rename from arduino/libretuya/libraries/Update/Update.h rename to cores/common/arduino/libraries/common/Update/Update.h index 83b0805..7e81790 100644 --- a/arduino/libretuya/libraries/Update/Update.h +++ b/cores/common/arduino/libraries/common/Update/Update.h @@ -71,7 +71,7 @@ class UpdateClass { const char *errorString(); const char *getFirmwareName(); const char *getFirmwareVersion(); - const char *getLibreTuyaVersion(); + const char *getLibreTinyVersion(); const char *getBoardName(); private: /* UpdateUtil.cpp */ @@ -104,6 +104,7 @@ class UpdateClass { public: String md5String(void) { // return _md5.toString(); + return ""; } void md5(uint8_t *result) { diff --git a/arduino/libretuya/libraries/Update/UpdateUtil.cpp b/cores/common/arduino/libraries/common/Update/UpdateUtil.cpp similarity index 89% rename from arduino/libretuya/libraries/Update/UpdateUtil.cpp rename to cores/common/arduino/libraries/common/Update/UpdateUtil.cpp index 18ae656..d355c7a 100644 --- a/arduino/libretuya/libraries/Update/UpdateUtil.cpp +++ b/cores/common/arduino/libraries/common/Update/UpdateUtil.cpp @@ -2,6 +2,10 @@ #include "Update.h" +extern "C" { +#include +} + static const uint8_t errorMap[] = { UPDATE_ERROR_OK, /* UF2_ERR_OK - no error */ UPDATE_ERROR_OK, /* UF2_ERR_IGNORE - block should be ignored */ @@ -9,9 +13,9 @@ static const uint8_t errorMap[] = { UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_FAMILY - family ID mismatched */ UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_NOT_HEADER - block is not a header */ UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_OTA_VER - unknown/invalid OTA format version */ - UPDATE_ERROR_MAGIC_BYTE, /* UF2_ERR_OTA_WRONG - no data for current OTA index */ + UPDATE_ERROR_MAGIC_BYTE, /* UF2_ERR_OTA_WRONG - no data for current OTA scheme */ UPDATE_ERROR_NO_PARTITION, /* UF2_ERR_PART_404 - no partition with that name */ - UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_PART_ONE - only one partition tag in a block */ + UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_PART_INVALID - invalid partition info tag */ UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_PART_UNSET - attempted to write without target partition */ UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_DATA_TOO_LONG - data too long - tags won't fit */ UPDATE_ERROR_BAD_ARGUMENT, /* UF2_ERR_SEQ_MISMATCH - sequence number mismatched */ @@ -39,7 +43,7 @@ void UpdateClass::cleanup(uint8_t ardErr, uf2_err_t uf2Err) { printErrorContext1(); #endif - free(ctx); // NULL in constructor + uf2_ctx_free(ctx); // NULL in constructor ctx = NULL; uf2_info_free(info); // NULL in constructor info = NULL; @@ -108,10 +112,9 @@ void UpdateClass::printErrorContext1() { if (ctx) LT_EM( OTA, - "- ctx: seq=%u, part1=%s, part2=%s", + "- ctx: seq=%u, part=%s", ctx->seq - 1, // print last parsed block seq - ctx->part1 ? ctx->part1->name : NULL, - ctx->part2 ? ctx->part2->name : NULL + ctx->part ? ctx->part->name : NULL ); uf2_block_t *block = (uf2_block_t *)buf; @@ -158,9 +161,9 @@ const char *UpdateClass::getFirmwareVersion() { } /** - * @brief Get LibreTuya version from UF2 info. + * @brief Get LibreTiny version from UF2 info. */ -const char *UpdateClass::getLibreTuyaVersion() { +const char *UpdateClass::getLibreTinyVersion() { if (info) return info->lt_version; return NULL; @@ -175,16 +178,14 @@ const char *UpdateClass::getBoardName() { return NULL; } -/** - * @brief See LT.otaCanRollback() for more info. - */ +/** @copydoc lt_ota_can_rollback() */ bool UpdateClass::canRollBack() { - return LT.otaCanRollback(); + return lt_ota_can_rollback(); } -/** - * @brief See LT.otaRollback() for more info. - */ +/** @copydoc lt_ota_switch() */ bool UpdateClass::rollBack() { - return LT.otaRollback(); + if (!lt_ota_can_rollback()) + return false; + return lt_ota_switch(false); } diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.cpp b/cores/common/arduino/libraries/common/WiFiClient/LwIPClient.cpp similarity index 99% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.cpp rename to cores/common/arduino/libraries/common/WiFiClient/LwIPClient.cpp index a6ee121..d4b5101 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.cpp +++ b/cores/common/arduino/libraries/common/WiFiClient/LwIPClient.cpp @@ -4,6 +4,8 @@ #include "LwIPClient.h" +#include + #define MAX_SOCK_NUM 4 #define WIFI_CLIENT_CONNECT_TIMEOUT 3000 #define WIFI_CLIENT_READ_TIMEOUT 3000 diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.h b/cores/common/arduino/libraries/common/WiFiClient/LwIPClient.h similarity index 89% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.h rename to cores/common/arduino/libraries/common/WiFiClient/LwIPClient.h index 0cbd125..d4411f9 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPClient.h +++ b/cores/common/arduino/libraries/common/WiFiClient/LwIPClient.h @@ -2,9 +2,11 @@ #pragma once -#include -#include -#include +#if (LT_ARD_HAS_WIFI && LT_HAS_LWIP) || DOXYGEN + +#include "WiFiClient.h" + +#include "LwIPRxBuffer.h" #include class SocketHandle; @@ -54,3 +56,7 @@ class LwIPClient : public IWiFiClient { using Print::write; }; + +typedef LwIPClient WiFiClient; + +#endif diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPRxBuffer.cpp b/cores/common/arduino/libraries/common/WiFiClient/LwIPRxBuffer.cpp similarity index 100% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPRxBuffer.cpp rename to cores/common/arduino/libraries/common/WiFiClient/LwIPRxBuffer.cpp diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPRxBuffer.h b/cores/common/arduino/libraries/common/WiFiClient/LwIPRxBuffer.h similarity index 100% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPRxBuffer.h rename to cores/common/arduino/libraries/common/WiFiClient/LwIPRxBuffer.h diff --git a/arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.cpp b/cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.cpp similarity index 77% rename from arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.cpp rename to cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.cpp index 8f91310..65a8c1d 100644 --- a/arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.cpp +++ b/cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.cpp @@ -4,15 +4,25 @@ #include "MbedTLSClient.h" +#include + extern "C" { #include +#include +#include #include #include #include +#if LT_HAS_FREERTOS +#include +#endif + } // extern "C" +#define _clientKeyC ((mbedtls_pk_context *)_clientKey) + MbedTLSClient::MbedTLSClient() : WiFiClient() { init(); // ensure the context is zero filled } @@ -27,25 +37,42 @@ MbedTLSClient::~MbedTLSClient() { } void MbedTLSClient::stop() { + if (!_sslCtx) + return; LT_VM(SSL, "Stopping SSL"); - if (_sslCfg.ca_chain) { - mbedtls_x509_crt_free(&_caCert); + if (_sslCfg->ca_chain) { + mbedtls_x509_crt_free(_caCert); } - if (_sslCfg.key_cert) { - mbedtls_x509_crt_free(&_clientCert); - mbedtls_pk_free(&_clientKey); + if (_sslCfg->key_cert) { + mbedtls_x509_crt_free(_clientCert); + mbedtls_pk_free(_clientKeyC); } - mbedtls_ssl_free(&_sslCtx); - mbedtls_ssl_config_free(&_sslCfg); + mbedtls_ssl_free(_sslCtx); + mbedtls_ssl_config_free(_sslCfg); + + free(_sslCtx); + free(_sslCfg); + free(_caCert); + free(_clientCert); + free(_clientKey); + _sslCtx = NULL; + LT_HEAP_I(); } void MbedTLSClient::init() { + if (!_sslCtx) { + _sslCtx = (mbedtls_ssl_context *)malloc(sizeof(mbedtls_ssl_context)); + _sslCfg = (mbedtls_ssl_config *)malloc(sizeof(mbedtls_ssl_config)); + _caCert = (mbedtls_x509_crt *)malloc(sizeof(mbedtls_x509_crt)); + _clientCert = (mbedtls_x509_crt *)malloc(sizeof(mbedtls_x509_crt)); + _clientKey = (mbedtls_pk_context *)malloc(sizeof(mbedtls_pk_context)); + } // Realtek AmbZ: init platform here to ensure HW crypto is initialized in ssl_init mbedtls_platform_set_calloc_free(calloc, free); - mbedtls_ssl_init(&_sslCtx); - mbedtls_ssl_config_init(&_sslCfg); + mbedtls_ssl_init(_sslCtx); + mbedtls_ssl_config_init(_sslCfg); } int MbedTLSClient::connect(IPAddress ip, uint16_t port, int32_t timeout) { @@ -129,7 +156,7 @@ int MbedTLSClient::connect( // mbedtls_ssl_conf_dbg(&_sslCfg, debug_cb, NULL); ret = mbedtls_ssl_config_defaults( - &_sslCfg, + _sslCfg, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT @@ -144,14 +171,14 @@ int MbedTLSClient::connect( #endif if (_insecure) { - mbedtls_ssl_conf_authmode(&_sslCfg, MBEDTLS_SSL_VERIFY_NONE); + mbedtls_ssl_conf_authmode(_sslCfg, MBEDTLS_SSL_VERIFY_NONE); } else if (rootCABuf) { - mbedtls_x509_crt_init(&_caCert); - mbedtls_ssl_conf_authmode(&_sslCfg, MBEDTLS_SSL_VERIFY_REQUIRED); - ret = mbedtls_x509_crt_parse(&_caCert, (const unsigned char *)rootCABuf, strlen(rootCABuf) + 1); - mbedtls_ssl_conf_ca_chain(&_sslCfg, &_caCert, NULL); + mbedtls_x509_crt_init(_caCert); + mbedtls_ssl_conf_authmode(_sslCfg, MBEDTLS_SSL_VERIFY_REQUIRED); + ret = mbedtls_x509_crt_parse(_caCert, (const unsigned char *)rootCABuf, strlen(rootCABuf) + 1); + mbedtls_ssl_conf_ca_chain(_sslCfg, _caCert, NULL); if (ret < 0) { - mbedtls_x509_crt_free(&_caCert); + mbedtls_x509_crt_free(_caCert); LT_RET(ret); } } else if (_useRootCA) { @@ -173,7 +200,7 @@ int MbedTLSClient::connect( return -1; pskBin[i / 2] |= c << (4 * ((i & 1) ^ 1)); } - ret = mbedtls_ssl_conf_psk(&_sslCfg, pskBin, len / 2, (const unsigned char *)pskIdent, strlen(pskIdent)); + ret = mbedtls_ssl_conf_psk(_sslCfg, pskBin, len / 2, (const unsigned char *)pskIdent, strlen(pskIdent)); LT_RET_NZ(ret); #else return -1; @@ -183,33 +210,33 @@ int MbedTLSClient::connect( } if (!_insecure && clientCert && clientKey) { - mbedtls_x509_crt_init(&_clientCert); - mbedtls_pk_init(&_clientKey); + mbedtls_x509_crt_init(_clientCert); + mbedtls_pk_init(_clientKeyC); LT_VM(SSL, "Loading client cert"); - ret = mbedtls_x509_crt_parse(&_clientCert, (const unsigned char *)clientCert, strlen(clientCert) + 1); + ret = mbedtls_x509_crt_parse(_clientCert, (const unsigned char *)clientCert, strlen(clientCert) + 1); if (ret < 0) { - mbedtls_x509_crt_free(&_clientCert); + mbedtls_x509_crt_free(_clientCert); LT_RET(ret); } LT_VM(SSL, "Loading private key"); - ret = mbedtls_pk_parse_key(&_clientKey, (const unsigned char *)clientKey, strlen(clientKey) + 1, NULL, 0); + ret = mbedtls_pk_parse_key(_clientKeyC, (const unsigned char *)clientKey, strlen(clientKey) + 1, NULL, 0); if (ret < 0) { - mbedtls_x509_crt_free(&_clientCert); + mbedtls_x509_crt_free(_clientCert); LT_RET(ret); } - mbedtls_ssl_conf_own_cert(&_sslCfg, &_clientCert, &_clientKey); + mbedtls_ssl_conf_own_cert(_sslCfg, _clientCert, _clientKeyC); } LT_VM(SSL, "Setting TLS hostname"); - ret = mbedtls_ssl_set_hostname(&_sslCtx, host); + ret = mbedtls_ssl_set_hostname(_sslCtx, host); LT_RET_NZ(ret); - mbedtls_ssl_conf_rng(&_sslCfg, ssl_random, NULL); - ret = mbedtls_ssl_setup(&_sslCtx, &_sslCfg); + mbedtls_ssl_conf_rng(_sslCfg, ssl_random, NULL); + ret = mbedtls_ssl_setup(_sslCtx, _sslCfg); LT_RET_NZ(ret); _sockTls = fd(); - mbedtls_ssl_set_bio(&_sslCtx, &_sockTls, mbedtls_net_send, mbedtls_net_recv, NULL); + mbedtls_ssl_set_bio(_sslCtx, &_sockTls, mbedtls_net_send, mbedtls_net_recv, NULL); mbedtls_net_set_nonblock((mbedtls_net_context *)&_sockTls); LT_HEAP_I(); @@ -218,7 +245,7 @@ int MbedTLSClient::connect( if (_handshakeTimeout == 0) _handshakeTimeout = timeout; unsigned long start = millis(); - while (ret = mbedtls_ssl_handshake(&_sslCtx)) { + while (ret = mbedtls_ssl_handshake(_sslCtx)) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { LT_RET(ret); } @@ -235,10 +262,10 @@ int MbedTLSClient::connect( LT_DM( SSL, "Protocol %s, ciphersuite %s", - mbedtls_ssl_get_version(&_sslCtx), - mbedtls_ssl_get_ciphersuite(&_sslCtx) + mbedtls_ssl_get_version(_sslCtx), + mbedtls_ssl_get_ciphersuite(_sslCtx) ); - ret = mbedtls_ssl_get_record_expansion(&_sslCtx); + ret = mbedtls_ssl_get_record_expansion(_sslCtx); if (ret >= 0) LT_DM(SSL, "Record expansion: %d", ret); else { @@ -247,7 +274,7 @@ int MbedTLSClient::connect( } LT_VM(SSL, "Verifying certificate"); - ret = mbedtls_ssl_get_verify_result(&_sslCtx); + ret = mbedtls_ssl_get_verify_result(_sslCtx); if (ret) { char buf[512]; memset(buf, 0, sizeof(buf)); @@ -257,17 +284,17 @@ int MbedTLSClient::connect( } if (rootCABuf) - mbedtls_x509_crt_free(&_caCert); + mbedtls_x509_crt_free(_caCert); if (clientCert) - mbedtls_x509_crt_free(&_clientCert); + mbedtls_x509_crt_free(_clientCert); if (clientKey != NULL) - mbedtls_pk_free(&_clientKey); + mbedtls_pk_free(_clientKeyC); return 0; // OK } size_t MbedTLSClient::write(const uint8_t *buf, size_t size) { int ret = -1; - while ((ret = mbedtls_ssl_write(&_sslCtx, buf, size)) <= 0) { + while ((ret = mbedtls_ssl_write(_sslCtx, buf, size)) <= 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0) { LT_RET(ret); } @@ -281,12 +308,12 @@ int MbedTLSClient::available() { if (!connected()) return peeked; - int ret = mbedtls_ssl_read(&_sslCtx, NULL, 0); + int ret = mbedtls_ssl_read(_sslCtx, NULL, 0); if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret < 0) { stop(); return peeked ? peeked : ret; } - return mbedtls_ssl_get_bytes_avail(&_sslCtx) + peeked; + return mbedtls_ssl_get_bytes_avail(_sslCtx) + peeked; } int MbedTLSClient::read(uint8_t *buf, size_t size) { @@ -307,7 +334,7 @@ int MbedTLSClient::read(uint8_t *buf, size_t size) { peeked = true; } - int ret = mbedtls_ssl_read(&_sslCtx, buf, size); + int ret = mbedtls_ssl_read(_sslCtx, buf, size); if (ret < 0) { stop(); return peeked ? peeked : ret; @@ -337,6 +364,9 @@ void MbedTLSClient::setInsecure() { _insecure = true; } +// TODO only allocate _caCert, _clientCert and _clientKey when one +// of the following functions is used + void MbedTLSClient::setPreSharedKey(const char *pskIdent, const char *psk) { _pskIdentStr = pskIdent; _pskStr = psk; @@ -437,7 +467,7 @@ void MbedTLSClient::setAlpnProtocols(const char **alpnProtocols) { } bool MbedTLSClient::getFingerprintSHA256(uint8_t result[32]) { - const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&_sslCtx); + const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(_sslCtx); if (!cert) { LT_EM(SSL, "Failed to get peer certificate"); return false; diff --git a/arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.h b/cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.h similarity index 85% rename from arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.h rename to cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.h index 5b0c629..98f9251 100644 --- a/arduino/libretuya/libraries/NetUtils/ssl/MbedTLSClient.h +++ b/cores/common/arduino/libraries/common/WiFiClient/MbedTLSClient.h @@ -2,25 +2,21 @@ #pragma once -#include -#include -#include +#if (LT_ARD_HAS_WIFI && LT_HAS_MBEDTLS) || DOXYGEN -#include // extend family's WiFiClient impl +#include "WiFiClientSecure.h" -extern "C" { - -#include - -} // extern "C" +struct mbedtls_ssl_context; +struct mbedtls_ssl_config; +struct mbedtls_x509_crt; class MbedTLSClient : public WiFiClient, public IWiFiClientSecure { private: - mbedtls_ssl_context _sslCtx; - mbedtls_ssl_config _sslCfg; - mbedtls_x509_crt _caCert; - mbedtls_x509_crt _clientCert; - mbedtls_pk_context _clientKey; + mbedtls_ssl_context *_sslCtx = NULL; + mbedtls_ssl_config *_sslCfg; + mbedtls_x509_crt *_caCert; + mbedtls_x509_crt *_clientCert; + void *_clientKey; uint32_t _handshakeTimeout = 0; void init(); @@ -86,3 +82,7 @@ class MbedTLSClient : public WiFiClient, public IWiFiClientSecure { using WiFiClient::connect; using WiFiClient::read; }; + +typedef MbedTLSClient WiFiClientSecure; + +#endif diff --git a/arduino/libretuya/api/WiFiClient.h b/cores/common/arduino/libraries/common/WiFiClient/WiFiClient.h similarity index 96% rename from arduino/libretuya/api/WiFiClient.h rename to cores/common/arduino/libraries/common/WiFiClient/WiFiClient.h index 8a60dea..e0650b8 100644 --- a/arduino/libretuya/api/WiFiClient.h +++ b/cores/common/arduino/libraries/common/WiFiClient/WiFiClient.h @@ -72,3 +72,7 @@ class IWiFiClient : public Client { using Print::write; }; + +#if LT_ARD_HAS_WIFI && LT_HAS_LWIP +#include "LwIPClient.h" +#endif diff --git a/arduino/libretuya/api/WiFiClientSecure.h b/cores/common/arduino/libraries/common/WiFiClient/WiFiClientSecure.h similarity index 97% rename from arduino/libretuya/api/WiFiClientSecure.h rename to cores/common/arduino/libraries/common/WiFiClient/WiFiClientSecure.h index 2391d77..296a416 100644 --- a/arduino/libretuya/api/WiFiClientSecure.h +++ b/cores/common/arduino/libraries/common/WiFiClient/WiFiClientSecure.h @@ -47,3 +47,7 @@ class IWiFiClientSecure { virtual void setAlpnProtocols(const char **alpnProtocols) = 0; virtual bool getFingerprintSHA256(uint8_t result[32]) = 0; }; + +#if LT_ARD_HAS_WIFI && LT_HAS_MBEDTLS +#include "MbedTLSClient.h" +#endif diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.cpp b/cores/common/arduino/libraries/common/WiFiServer/LwIPServer.cpp similarity index 99% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.cpp rename to cores/common/arduino/libraries/common/WiFiServer/LwIPServer.cpp index 710a96d..70dc7cc 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.cpp +++ b/cores/common/arduino/libraries/common/WiFiServer/LwIPServer.cpp @@ -61,6 +61,7 @@ bool LwIPServer::begin(uint16_t port, bool reuseAddr) { _active = true; _noDelay = false; _sockAccepted = -1; + return true; } void LwIPServer::end() { diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.h b/cores/common/arduino/libraries/common/WiFiServer/LwIPServer.h similarity index 89% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.h rename to cores/common/arduino/libraries/common/WiFiServer/LwIPServer.h index 5e63571..ca2e03b 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPServer.h +++ b/cores/common/arduino/libraries/common/WiFiServer/LwIPServer.h @@ -2,10 +2,9 @@ #pragma once -#include -#include +#if (LT_ARD_HAS_WIFI && LT_HAS_LWIP) || DOXYGEN -#include +#include "WiFiServer.h" class LwIPServer : public IWiFiServer { private: @@ -45,3 +44,7 @@ class LwIPServer : public IWiFiServer { bool getNoDelay(); bool hasClient(); }; + +typedef LwIPServer WiFiServer; + +#endif diff --git a/arduino/libretuya/api/WiFiServer.h b/cores/common/arduino/libraries/common/WiFiServer/WiFiServer.h similarity index 96% rename from arduino/libretuya/api/WiFiServer.h rename to cores/common/arduino/libraries/common/WiFiServer/WiFiServer.h index 4dde9d5..0b8dbc1 100644 --- a/arduino/libretuya/api/WiFiServer.h +++ b/cores/common/arduino/libraries/common/WiFiServer/WiFiServer.h @@ -70,3 +70,7 @@ class IWiFiServer : public Print { // arduino::Server is useless anyway using Print::write; }; + +#if LT_ARD_HAS_WIFI && LT_HAS_LWIP +#include "LwIPServer.h" +#endif diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.cpp b/cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.cpp similarity index 99% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.cpp rename to cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.cpp index 575e0e1..6e2dede 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.cpp +++ b/cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.cpp @@ -17,7 +17,6 @@ #if LT_ARD_HAS_WIFI && LT_HAS_LWIP #include "LwIPUdp.h" -#include extern "C" { diff --git a/arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.h b/cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.h similarity index 89% rename from arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.h rename to cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.h index 687afe0..7ff6d4a 100644 --- a/arduino/libretuya/libraries/NetUtils/lwip/LwIPUdp.h +++ b/cores/common/arduino/libraries/common/WiFiUdp/LwIPUdp.h @@ -2,8 +2,10 @@ #pragma once -#include -#include +#if (LT_ARD_HAS_WIFI && LT_HAS_LWIP) || DOXYGEN + +#include "WiFiUdp.h" + #include class LwIPUDP : public IWiFiUDP { @@ -41,3 +43,7 @@ class LwIPUDP : public IWiFiUDP { IPAddress remoteIP(); uint16_t remotePort(); }; + +typedef LwIPUDP WiFiUDP; + +#endif diff --git a/arduino/libretuya/api/WiFiUdp.h b/cores/common/arduino/libraries/common/WiFiUdp/WiFiUdp.h similarity index 94% rename from arduino/libretuya/api/WiFiUdp.h rename to cores/common/arduino/libraries/common/WiFiUdp/WiFiUdp.h index 84d9aef..28e0180 100644 --- a/arduino/libretuya/api/WiFiUdp.h +++ b/cores/common/arduino/libraries/common/WiFiUdp/WiFiUdp.h @@ -30,3 +30,7 @@ class IWiFiUDP : public UDP { virtual IPAddress remoteIP() = 0; virtual uint16_t remotePort() = 0; }; + +#if LT_ARD_HAS_WIFI && LT_HAS_LWIP +#include "LwIPUdp.h" +#endif diff --git a/arduino/libretuya/libraries/mDNS/LwIPmDNS.cpp b/cores/common/arduino/libraries/common/mDNS/LwIPmDNS.cpp similarity index 99% rename from arduino/libretuya/libraries/mDNS/LwIPmDNS.cpp rename to cores/common/arduino/libraries/common/mDNS/LwIPmDNS.cpp index e7f6c6c..f590219 100644 --- a/arduino/libretuya/libraries/mDNS/LwIPmDNS.cpp +++ b/cores/common/arduino/libraries/common/mDNS/LwIPmDNS.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-05-23. */ -#ifdef LT_HAS_LWIP2 +#if LT_HAS_LWIP2 #include "mDNS.h" #include diff --git a/arduino/libretuya/libraries/mDNS/mDNS.cpp b/cores/common/arduino/libraries/common/mDNS/mDNS.cpp similarity index 100% rename from arduino/libretuya/libraries/mDNS/mDNS.cpp rename to cores/common/arduino/libraries/common/mDNS/mDNS.cpp diff --git a/arduino/libretuya/libraries/mDNS/mDNS.h b/cores/common/arduino/libraries/common/mDNS/mDNS.h similarity index 100% rename from arduino/libretuya/libraries/mDNS/mDNS.h rename to cores/common/arduino/libraries/common/mDNS/mDNS.h diff --git a/arduino/libretuya/libraries/HTTPClient/HTTPClient.cpp b/cores/common/arduino/libraries/ext/HTTPClient/HTTPClient.cpp similarity index 99% rename from arduino/libretuya/libraries/HTTPClient/HTTPClient.cpp rename to cores/common/arduino/libraries/ext/HTTPClient/HTTPClient.cpp index 6fd8f24..c99ea3c 100644 --- a/arduino/libretuya/libraries/HTTPClient/HTTPClient.cpp +++ b/cores/common/arduino/libraries/ext/HTTPClient/HTTPClient.cpp @@ -42,10 +42,6 @@ /// Cookie jar support #include -extern "C" { -#include "strptime.h" -} - #ifdef HTTPCLIENT_1_1_COMPATIBLE class TransportTraits { public: diff --git a/arduino/libretuya/libraries/HTTPClient/HTTPClient.h b/cores/common/arduino/libraries/ext/HTTPClient/HTTPClient.h similarity index 100% rename from arduino/libretuya/libraries/HTTPClient/HTTPClient.h rename to cores/common/arduino/libraries/ext/HTTPClient/HTTPClient.h diff --git a/arduino/libretuya/libraries/StreamString/.clang-format b/cores/common/arduino/libraries/ext/StreamString/.clang-format similarity index 100% rename from arduino/libretuya/libraries/StreamString/.clang-format rename to cores/common/arduino/libraries/ext/StreamString/.clang-format diff --git a/arduino/libretuya/libraries/StreamString/StreamString.cpp b/cores/common/arduino/libraries/ext/StreamString/StreamString.cpp similarity index 100% rename from arduino/libretuya/libraries/StreamString/StreamString.cpp rename to cores/common/arduino/libraries/ext/StreamString/StreamString.cpp diff --git a/arduino/libretuya/libraries/StreamString/StreamString.h b/cores/common/arduino/libraries/ext/StreamString/StreamString.h similarity index 100% rename from arduino/libretuya/libraries/StreamString/StreamString.h rename to cores/common/arduino/libraries/ext/StreamString/StreamString.h diff --git a/arduino/libretuya/libraries/WebServer/HTTP_Method.h b/cores/common/arduino/libraries/ext/WebServer/HTTP_Method.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/HTTP_Method.h rename to cores/common/arduino/libraries/ext/WebServer/HTTP_Method.h diff --git a/arduino/libretuya/libraries/WebServer/Parsing.cpp b/cores/common/arduino/libraries/ext/WebServer/Parsing.cpp similarity index 100% rename from arduino/libretuya/libraries/WebServer/Parsing.cpp rename to cores/common/arduino/libraries/ext/WebServer/Parsing.cpp diff --git a/arduino/libretuya/libraries/WebServer/Uri.h b/cores/common/arduino/libraries/ext/WebServer/Uri.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/Uri.h rename to cores/common/arduino/libraries/ext/WebServer/Uri.h diff --git a/arduino/libretuya/libraries/WebServer/WebServer.cpp b/cores/common/arduino/libraries/ext/WebServer/WebServer.cpp similarity index 100% rename from arduino/libretuya/libraries/WebServer/WebServer.cpp rename to cores/common/arduino/libraries/ext/WebServer/WebServer.cpp diff --git a/arduino/libretuya/libraries/WebServer/WebServer.h b/cores/common/arduino/libraries/ext/WebServer/WebServer.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/WebServer.h rename to cores/common/arduino/libraries/ext/WebServer/WebServer.h diff --git a/arduino/libretuya/libraries/WebServer/detail/RequestHandler.h b/cores/common/arduino/libraries/ext/WebServer/detail/RequestHandler.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/detail/RequestHandler.h rename to cores/common/arduino/libraries/ext/WebServer/detail/RequestHandler.h diff --git a/arduino/libretuya/libraries/WebServer/detail/RequestHandlersImpl.h b/cores/common/arduino/libraries/ext/WebServer/detail/RequestHandlersImpl.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/detail/RequestHandlersImpl.h rename to cores/common/arduino/libraries/ext/WebServer/detail/RequestHandlersImpl.h diff --git a/arduino/libretuya/libraries/WebServer/detail/mimetable.cpp b/cores/common/arduino/libraries/ext/WebServer/detail/mimetable.cpp similarity index 100% rename from arduino/libretuya/libraries/WebServer/detail/mimetable.cpp rename to cores/common/arduino/libraries/ext/WebServer/detail/mimetable.cpp diff --git a/arduino/libretuya/libraries/WebServer/detail/mimetable.h b/cores/common/arduino/libraries/ext/WebServer/detail/mimetable.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/detail/mimetable.h rename to cores/common/arduino/libraries/ext/WebServer/detail/mimetable.h diff --git a/arduino/libretuya/libraries/WebServer/uri/UriBraces.h b/cores/common/arduino/libraries/ext/WebServer/uri/UriBraces.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/uri/UriBraces.h rename to cores/common/arduino/libraries/ext/WebServer/uri/UriBraces.h diff --git a/arduino/libretuya/libraries/WebServer/uri/UriGlob.h b/cores/common/arduino/libraries/ext/WebServer/uri/UriGlob.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/uri/UriGlob.h rename to cores/common/arduino/libraries/ext/WebServer/uri/UriGlob.h diff --git a/arduino/libretuya/libraries/WebServer/uri/UriRegex.h b/cores/common/arduino/libraries/ext/WebServer/uri/UriRegex.h similarity index 100% rename from arduino/libretuya/libraries/WebServer/uri/UriRegex.h rename to cores/common/arduino/libraries/ext/WebServer/uri/UriRegex.h diff --git a/arduino/libretuya/libraries/WiFiMulti/WiFiMulti.cpp b/cores/common/arduino/libraries/ext/WiFiMulti/WiFiMulti.cpp similarity index 100% rename from arduino/libretuya/libraries/WiFiMulti/WiFiMulti.cpp rename to cores/common/arduino/libraries/ext/WiFiMulti/WiFiMulti.cpp diff --git a/arduino/libretuya/libraries/WiFiMulti/WiFiMulti.h b/cores/common/arduino/libraries/ext/WiFiMulti/WiFiMulti.h similarity index 100% rename from arduino/libretuya/libraries/WiFiMulti/WiFiMulti.h rename to cores/common/arduino/libraries/ext/WiFiMulti/WiFiMulti.h diff --git a/arduino/libretuya/libraries/base64/.clang-format b/cores/common/arduino/libraries/ext/base64/.clang-format similarity index 100% rename from arduino/libretuya/libraries/base64/.clang-format rename to cores/common/arduino/libraries/ext/base64/.clang-format diff --git a/arduino/libretuya/libraries/base64/base64.cpp b/cores/common/arduino/libraries/ext/base64/base64.cpp similarity index 100% rename from arduino/libretuya/libraries/base64/base64.cpp rename to cores/common/arduino/libraries/ext/base64/base64.cpp diff --git a/arduino/libretuya/libraries/base64/base64.h b/cores/common/arduino/libraries/ext/base64/base64.h similarity index 100% rename from arduino/libretuya/libraries/base64/base64.h rename to cores/common/arduino/libraries/ext/base64/base64.h diff --git a/arduino/libretuya/libraries/base64/libb64/AUTHORS b/cores/common/arduino/libraries/ext/base64/libb64/AUTHORS similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/AUTHORS rename to cores/common/arduino/libraries/ext/base64/libb64/AUTHORS diff --git a/arduino/libretuya/libraries/base64/libb64/LICENSE b/cores/common/arduino/libraries/ext/base64/libb64/LICENSE similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/LICENSE rename to cores/common/arduino/libraries/ext/base64/libb64/LICENSE diff --git a/arduino/libretuya/libraries/base64/libb64/cdecode.c b/cores/common/arduino/libraries/ext/base64/libb64/cdecode.c similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/cdecode.c rename to cores/common/arduino/libraries/ext/base64/libb64/cdecode.c diff --git a/arduino/libretuya/libraries/base64/libb64/cdecode.h b/cores/common/arduino/libraries/ext/base64/libb64/cdecode.h similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/cdecode.h rename to cores/common/arduino/libraries/ext/base64/libb64/cdecode.h diff --git a/arduino/libretuya/libraries/base64/libb64/cencode.c b/cores/common/arduino/libraries/ext/base64/libb64/cencode.c similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/cencode.c rename to cores/common/arduino/libraries/ext/base64/libb64/cencode.c diff --git a/arduino/libretuya/libraries/base64/libb64/cencode.h b/cores/common/arduino/libraries/ext/base64/libb64/cencode.h similarity index 100% rename from arduino/libretuya/libraries/base64/libb64/cencode.h rename to cores/common/arduino/libraries/ext/base64/libb64/cencode.h diff --git a/arduino/libretuya/libraries/cbuf/.clang-format b/cores/common/arduino/libraries/ext/cbuf/.clang-format similarity index 100% rename from arduino/libretuya/libraries/cbuf/.clang-format rename to cores/common/arduino/libraries/ext/cbuf/.clang-format diff --git a/arduino/libretuya/libraries/cbuf/cbuf.cpp b/cores/common/arduino/libraries/ext/cbuf/cbuf.cpp similarity index 100% rename from arduino/libretuya/libraries/cbuf/cbuf.cpp rename to cores/common/arduino/libraries/ext/cbuf/cbuf.cpp diff --git a/arduino/libretuya/libraries/cbuf/cbuf.h b/cores/common/arduino/libraries/ext/cbuf/cbuf.h similarity index 100% rename from arduino/libretuya/libraries/cbuf/cbuf.h rename to cores/common/arduino/libraries/ext/cbuf/cbuf.h diff --git a/cores/common/arduino/libraries/inline/.clang-format b/cores/common/arduino/libraries/inline/.clang-format new file mode 100644 index 0000000..b573581 --- /dev/null +++ b/cores/common/arduino/libraries/inline/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: InheritParentConfig +AllowShortFunctionsOnASingleLine: Inline diff --git a/cores/common/arduino/libraries/inline/ESP/ESP.h b/cores/common/arduino/libraries/inline/ESP/ESP.h new file mode 100644 index 0000000..b36820a --- /dev/null +++ b/cores/common/arduino/libraries/inline/ESP/ESP.h @@ -0,0 +1,121 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-20.() */ + +#include + +#ifdef __cplusplus + +/** + * @brief ESP Arduino Core compatibility class. + * + * This class only consists of inline functions, which + * wrap the LibreTiny C API (lt_api.h). Refer to the docs of the C API + * for more information. + * + * The class is accessible using the `ESP` global object. + */ +class EspClass { + public: + /** @copydoc lt_wdt_enable() */ + inline void wdtEnable(uint32_t timeout_ms = 0) { lt_wdt_enable(timeout_ms); } + + /** @copydoc lt_wdt_disable() */ + inline void wdtDisable() { lt_wdt_disable(); } + + /** @copydoc lt_wdt_feed() */ + inline void wdtFeed() { lt_wdt_feed(); } + + /** @copydoc lt_reboot() */ + inline void reset() { lt_reboot(); } + + /** @copydoc lt_reboot() */ + inline void restart() { lt_reboot(); } + + /** @copydoc lt_reboot_download_mode() */ + inline void rebootIntoUartDownloadMode() { lt_reboot_download_mode(); } + + inline uint16_t getVcc() { return 3300; } + + /** @copydoc lt_cpu_get_mac_id() */ + inline uint32_t getChipId() { return lt_cpu_get_mac_id(); } + + /** @copydoc lt_heap_get_free() */ + inline uint32_t getFreeHeap() { return lt_heap_get_free(); } + + /** @copydoc lt_heap_get_max_alloc() */ + inline uint16_t getMaxFreeBlockSize() { return lt_heap_get_max_alloc(); } + + /** @copydoc LT_VERSION_STR() */ + inline const char *getSdkVersion() { return LT_VERSION_STR; } + + /** @copydoc LT_VERSION_STR() */ + inline String getCoreVersion() { return LT_VERSION_STR; } + + /** @copydoc LT_BANNER_STR() */ + inline String getFullVersion() { return LT_BANNER_STR; } + + inline uint8_t getBootVersion() { return 0; } + + inline uint8_t getBootMode() { return 0; } + + /** @copydoc lt_cpu_get_freq_mhz() */ + inline uint8_t getCpuFreqMHz() { return lt_cpu_get_freq_mhz(); } + + /** @copydoc lt_flash_get_id() */ + inline uint32_t getFlashChipId() { + lt_flash_id_t id = lt_flash_get_id(); + return id.manufacturer_id << 16 | id.chip_id << 7 | id.chip_size_id; + } + + /** @copydoc lt_flash_get_id() */ + inline uint8_t getFlashChipVendorId() { return lt_flash_get_id().manufacturer_id; } + + /** @copydoc lt_flash_get_size() */ + inline uint32_t getFlashChipRealSize() { return lt_flash_get_size(); } + + /** @copydoc lt_flash_get_size() */ + inline uint32_t getFlashChipSize() { return lt_flash_get_size(); } + + inline uint32_t getFlashChipMode() { return 0xFF; } + + /** @copydoc lt_flash_get_size() */ + inline uint32_t getFlashChipSizeByChipId() { return lt_flash_get_size(); } + + /** @copydoc lt_flash_erase_block() */ + inline bool flashEraseSector(uint32_t sector) { return lt_flash_erase_block(sector); } + + /** @copydoc lt_flash_write() */ + inline bool flashWrite(uint32_t address, const uint8_t *data, size_t size) { + return lt_flash_write(address, data, size) == size; + } + + /** @copydoc lt_flash_read() */ + inline bool flashRead(uint32_t address, uint8_t *data, size_t size) { + return lt_flash_read(address, data, size) == size; + } + + /** @copydoc lt_get_reboot_reason_name() */ + inline String getResetReason() { return lt_get_reboot_reason_name(lt_get_reboot_reason()); } + + /** @copydoc lt_get_reboot_reason_name() */ + inline String getResetInfo() { return lt_get_reboot_reason_name(lt_get_reboot_reason()); } + + /** @copydoc lt_rand_bytes() */ + inline uint8_t *random(uint8_t *resultArray, const size_t outputSizeBytes) { + lt_rand_bytes(resultArray, (size_t)outputSizeBytes); + return resultArray; + } + + /** @copydoc lt_rand_bytes() */ + inline uint32_t random() { + uint32_t i; + lt_rand_bytes((uint8_t *)&i, 4); + return i; + } + + /** @copydoc lt_cpu_get_cycle_count() */ + inline uint32_t getCycleCount() { return lt_cpu_get_cycle_count(); } +}; + +extern EspClass ESP; + +#endif diff --git a/cores/common/arduino/libraries/inline/Flash/Flash.h b/cores/common/arduino/libraries/inline/Flash/Flash.h new file mode 100644 index 0000000..248e45d --- /dev/null +++ b/cores/common/arduino/libraries/inline/Flash/Flash.h @@ -0,0 +1,38 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-04-24. */ + +#pragma once + +#include + +#ifdef __cplusplus + +class FlashClass { + public: + /** @copydoc lt_flash_get_id() */ + inline FlashId getChipId() { return lt_flash_get_id(); } + + /** @copydoc lt_flash_get_size() */ + inline uint32_t getSize() { return lt_flash_get_size(); } + + /** @copydoc lt_flash_erase_block() */ + inline bool eraseSector(uint32_t offset) { + // + return lt_flash_erase_block(offset); + } + + /** @copydoc lt_flash_read() */ + inline bool readBlock(uint32_t offset, uint8_t *data, size_t length) { + // + return lt_flash_read(offset, data, length) == length; + } + + /** @copydoc lt_flash_write() */ + inline bool writeBlock(uint32_t offset, const uint8_t *data, size_t length) { + // + return lt_flash_write(offset, data, length) == length; + } +}; + +extern FlashClass Flash; + +#endif diff --git a/cores/common/arduino/libraries/inline/LT/LT.h b/cores/common/arduino/libraries/inline/LT/LT.h new file mode 100644 index 0000000..950117a --- /dev/null +++ b/cores/common/arduino/libraries/inline/LT/LT.h @@ -0,0 +1,114 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-06. */ + +#pragma once + +#include +#include +#include +#include + +#ifdef __cplusplus + +#define ChipFamily lt_cpu_family_t +#define ChipType lt_cpu_model_t +#define ResetReason lt_reboot_reason_t +#define FlashId lt_flash_id_t + +/** + * @brief Main LibreTiny API class. + * + * Since v1.0.0, this class only consists of inline functions, which + * wrap the LibreTiny C API (lt_api.h). Refer to the docs of the C API + * for more information. + * + * The class is accessible using the `LT` global object. + */ +class LibreTiny { + public: /* lt_cpu.h */ + /** @copydoc lt_cpu_get_family() */ + inline ChipFamily getChipFamily() { return lt_cpu_get_family(); } + + /** @copydoc lt_cpu_get_family_name() */ + inline const char *getChipFamilyName() { return lt_cpu_get_family_name(); } + + /** @copydoc lt_cpu_get_model() */ + inline ChipType getChipType() { return lt_cpu_get_model(); } + + /** @copydoc lt_cpu_get_model_name() */ + inline const char *getChipModel() { return lt_cpu_get_model_name(); } + + /** @copydoc lt_cpu_get_mac_id() */ + inline uint32_t getChipId() { return lt_cpu_get_mac_id(); } + + /** @copydoc lt_cpu_get_core_count() */ + inline uint8_t getChipCores() { return lt_cpu_get_core_count(); } + + /** @copydoc lt_cpu_get_core_type() */ + inline const char *getChipCoreType() { return lt_cpu_get_core_type(); } + + /** @copydoc lt_cpu_get_freq() */ + inline uint32_t getCpuFreq() { return lt_cpu_get_freq(); } + + /** @copydoc lt_cpu_get_freq_mhz() */ + inline uint32_t getCpuFreqMHz() { return lt_cpu_get_freq_mhz(); } + + /** @copydoc lt_cpu_get_cycle_count() */ + inline uint32_t getCycleCount() { return lt_cpu_get_cycle_count(); } + + public: /* lt_device.h */ + /** @copydoc lt_get_version() */ + inline const char *getVersion() { return lt_get_version(); } + + /** @copydoc lt_get_board_code() */ + inline const char *getBoard() { return lt_get_board_code(); } + + /** @copydoc lt_get_device_name() */ + inline const char *getDeviceName() { return lt_get_device_name(); } + + /** @copydoc lt_reboot() */ + inline void restart() { lt_reboot(); } + + /** @copydoc lt_reboot_download_mode() */ + inline void restartDownloadMode() { lt_reboot_download_mode(); } + + /** @copydoc lt_get_reboot_reason() */ + inline ResetReason getResetReason() { return lt_get_reboot_reason(); } + + /** @copydoc lt_get_reboot_reason_name() */ + inline const char *getResetReasonName(ResetReason reason = lt_get_reboot_reason()) { + return lt_get_reboot_reason_name(reason); + } + + /** @copydoc lt_gpio_recover(); */ + inline void gpioRecover() { lt_gpio_recover(); } + + public: /* lt_flash.h */ + /** @copydoc lt_flash_get_id() */ + inline FlashId getFlashChipId() { return lt_flash_get_id(); } + + /** @copydoc lt_flash_get_size() */ + inline uint32_t getFlashChipSize() { return lt_flash_get_size(); } + + public: /* lt_mem.h */ + /** @copydoc lt_ram_get_size() */ + inline uint32_t getRamSize() { return lt_ram_get_size(); } + + /** @copydoc lt_heap_get_size() */ + inline uint32_t getHeapSize() { return lt_heap_get_size(); } + + /** @copydoc lt_heap_get_free() */ + inline uint32_t getFreeHeap() { return lt_heap_get_free(); } + + /** @copydoc lt_heap_get_min_free() */ + inline uint32_t getMinFreeHeap() { return lt_heap_get_min_free(); } + + /** @copydoc lt_heap_get_max_alloc() */ + inline uint32_t getMaxAllocHeap() { return lt_heap_get_max_alloc(); } + + /** @copydoc lt_heap_get_max_alloc() */ + inline uint32_t getMaxFreeBlockSize() { return lt_heap_get_max_alloc(); } +}; + +extern LibreTiny LT; + +#endif diff --git a/cores/common/arduino/libraries/inline/OTA/OTA.h b/cores/common/arduino/libraries/inline/OTA/OTA.h new file mode 100644 index 0000000..e6bb234 --- /dev/null +++ b/cores/common/arduino/libraries/inline/OTA/OTA.h @@ -0,0 +1,44 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-10. */ + +#pragma once + +#include + +#ifdef __cplusplus + +/** + * @brief Over-the-Air updates helper class. + * + * This class only consists of inline functions, which + * wrap the LibreTiny C API (lt_api.h). Refer to the docs of the C API + * for more information. + * + * The class is accessible using the `OTA` global object. + */ +class LibreTinyOTA { + public: /* lt_ota.h */ + /** @copydoc lt_ota_get_type() */ + inline lt_ota_type_t getType() { return lt_ota_get_type(); } + + /** @copydoc lt_ota_is_valid() */ + inline bool isValid(uint8_t index) { return lt_ota_is_valid(index); } + + /** @copydoc lt_ota_can_rollback() */ + inline bool canRollback() { return lt_ota_can_rollback(); } + + /** @copydoc lt_ota_dual_get_current() */ + inline uint8_t getCurrentIndex() { return lt_ota_dual_get_current(); } + + /** @copydoc lt_ota_dual_get_stored() */ + inline uint8_t getStoredIndex() { return lt_ota_dual_get_stored(); } + + /** @copydoc lt_ota_get_uf2_scheme() */ + inline uf2_ota_scheme_t getUF2Scheme() { return lt_ota_get_uf2_scheme(); } + + /** @copydoc lt_ota_switch() */ + inline bool switchImage(bool revert = false) { return lt_ota_switch(revert); } +}; + +extern LibreTinyOTA OTA; + +#endif diff --git a/cores/common/arduino/libraries/inline/Singletons.cpp b/cores/common/arduino/libraries/inline/Singletons.cpp new file mode 100644 index 0000000..1d0d2d6 --- /dev/null +++ b/cores/common/arduino/libraries/inline/Singletons.cpp @@ -0,0 +1,11 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-10. */ + +#include + +#include + +LibreTiny LT; +LibreTinyOTA OTA; +LibreTinyWDT WDT; +EspClass ESP; +FlashClass Flash; diff --git a/cores/common/arduino/libraries/inline/WDT/WDT.h b/cores/common/arduino/libraries/inline/WDT/WDT.h new file mode 100644 index 0000000..0cc45e0 --- /dev/null +++ b/cores/common/arduino/libraries/inline/WDT/WDT.h @@ -0,0 +1,32 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-10. */ + +#pragma once + +#include + +#ifdef __cplusplus + +/** + * @brief Watchdog control class. + * + * This class only consists of inline functions, which + * wrap the LibreTiny C API (lt_api.h). Refer to the docs of the C API + * for more information. + * + * The class is accessible using the `WDT` global object. + */ +class LibreTinyWDT { + public: /* lt_wdt.h */ + /** @copydoc lt_wdt_enable() */ + inline bool enable(uint32_t timeout = 10000) { return lt_wdt_enable(timeout); } + + /** @copydoc lt_wdt_disable() */ + inline void disable() { lt_wdt_disable(); } + + /** @copydoc lt_wdt_feed() */ + inline void feed() { lt_wdt_feed(); } +}; + +extern LibreTinyWDT WDT; + +#endif diff --git a/cores/common/arduino/src/Arduino.h b/cores/common/arduino/src/Arduino.h new file mode 100644 index 0000000..dec3c7e --- /dev/null +++ b/cores/common/arduino/src/Arduino.h @@ -0,0 +1,58 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-14. */ + +#pragma once + +// LibreTiny C API (with C standard libraries) +#include + +// Additional C libraries +#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 + +// Arduino Core and LT class +#include +#ifdef __cplusplus +#include +#endif + +// Include family-specific code +#include + +// Additional Wiring headers +#include "wiring_compat.h" +#include "wiring_custom.h" + +// FreeRTOS kernel +#include +#include + +// Define available serial ports +#if defined(__cplusplus) && LT_ARD_HAS_SERIAL +#include + +#if HAS_SERIAL0 +extern SerialClass Serial0; +#endif +#if HAS_SERIAL1 +extern SerialClass Serial1; +#endif +#if HAS_SERIAL2 +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/arduino/libretuya/api/Events.cpp b/cores/common/arduino/src/Events.cpp similarity index 100% rename from arduino/libretuya/api/Events.cpp rename to cores/common/arduino/src/Events.cpp diff --git a/arduino/libretuya/api/Events.h b/cores/common/arduino/src/Events.h similarity index 99% rename from arduino/libretuya/api/Events.h rename to cores/common/arduino/src/Events.h index dc128e4..0966039 100644 --- a/arduino/libretuya/api/Events.h +++ b/cores/common/arduino/src/Events.h @@ -23,7 +23,7 @@ #pragma once #include -#include +#include #include typedef enum { diff --git a/arduino/libretuya/api/Wire.h b/cores/common/arduino/src/HardwareI2C.h similarity index 97% rename from arduino/libretuya/api/Wire.h rename to cores/common/arduino/src/HardwareI2C.h index eded4cf..9c0479d 100644 --- a/arduino/libretuya/api/Wire.h +++ b/cores/common/arduino/src/HardwareI2C.h @@ -2,7 +2,7 @@ #include -class ITwoWire : public Stream { +class HardwareI2C : public Stream { protected: int8_t _sda = -1; int8_t _scl = -1; diff --git a/arduino/libretuya/common/WMath.cpp b/cores/common/arduino/src/common/WMath.cpp similarity index 100% rename from arduino/libretuya/common/WMath.cpp rename to cores/common/arduino/src/common/WMath.cpp diff --git a/arduino/libretuya/common/abi.cpp b/cores/common/arduino/src/common/abi.cpp similarity index 100% rename from arduino/libretuya/common/abi.cpp rename to cores/common/arduino/src/common/abi.cpp diff --git a/arduino/libretuya/common/dtostrf.c b/cores/common/arduino/src/common/dtostrf.c similarity index 100% rename from arduino/libretuya/common/dtostrf.c rename to cores/common/arduino/src/common/dtostrf.c diff --git a/arduino/libretuya/common/hooks.c b/cores/common/arduino/src/common/hooks.c similarity index 100% rename from arduino/libretuya/common/hooks.c rename to cores/common/arduino/src/common/hooks.c diff --git a/arduino/libretuya/common/serial_event.cpp b/cores/common/arduino/src/common/serial_event.cpp similarity index 100% rename from arduino/libretuya/common/serial_event.cpp rename to cores/common/arduino/src/common/serial_event.cpp diff --git a/arduino/libretuya/common/wiring_shift.c b/cores/common/arduino/src/common/wiring_shift.c similarity index 100% rename from arduino/libretuya/common/wiring_shift.c rename to cores/common/arduino/src/common/wiring_shift.c diff --git a/arduino/libretuya/libraries/mDNS/ESPmDNS.h b/cores/common/arduino/src/compat/ESPmDNS.h similarity index 100% rename from arduino/libretuya/libraries/mDNS/ESPmDNS.h rename to cores/common/arduino/src/compat/ESPmDNS.h diff --git a/arduino/libretuya/compat/FS.h b/cores/common/arduino/src/compat/FS.h similarity index 100% rename from arduino/libretuya/compat/FS.h rename to cores/common/arduino/src/compat/FS.h diff --git a/arduino/libretuya/compat/FSImpl.h b/cores/common/arduino/src/compat/FSImpl.h similarity index 100% rename from arduino/libretuya/compat/FSImpl.h rename to cores/common/arduino/src/compat/FSImpl.h diff --git a/arduino/libretuya/compat/WiFiAP.h b/cores/common/arduino/src/compat/WiFiAP.h similarity index 100% rename from arduino/libretuya/compat/WiFiAP.h rename to cores/common/arduino/src/compat/WiFiAP.h diff --git a/arduino/libretuya/compat/md5.h b/cores/common/arduino/src/compat/md5.h similarity index 100% rename from arduino/libretuya/compat/md5.h rename to cores/common/arduino/src/compat/md5.h diff --git a/arduino/libretuya/compat/pgmspace.h b/cores/common/arduino/src/compat/pgmspace.h similarity index 100% rename from arduino/libretuya/compat/pgmspace.h rename to cores/common/arduino/src/compat/pgmspace.h diff --git a/arduino/libretuya/compat/vfs_api.h b/cores/common/arduino/src/compat/vfs_api.h similarity index 100% rename from arduino/libretuya/compat/vfs_api.h rename to cores/common/arduino/src/compat/vfs_api.h diff --git a/cores/common/arduino/src/main.c b/cores/common/arduino/src/main.c new file mode 100644 index 0000000..80f72eb --- /dev/null +++ b/cores/common/arduino/src/main.c @@ -0,0 +1,27 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#include + +int main() { + // initialize Arduino framework + lt_init_arduino(); + // 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(); + yield(); + } +} diff --git a/arduino/libretuya/posix/time.c b/cores/common/arduino/src/posix/time.c similarity index 100% rename from arduino/libretuya/posix/time.c rename to cores/common/arduino/src/posix/time.c diff --git a/cores/common/arduino/src/wiring_compat.cpp b/cores/common/arduino/src/wiring_compat.cpp new file mode 100644 index 0000000..72549b3 --- /dev/null +++ b/cores/common/arduino/src/wiring_compat.cpp @@ -0,0 +1,9 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-04. */ + +#include "wiring_compat.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); +} diff --git a/arduino/libretuya/core/LibreTuyaCompat.h b/cores/common/arduino/src/wiring_compat.h similarity index 60% rename from arduino/libretuya/core/LibreTuyaCompat.h rename to cores/common/arduino/src/wiring_compat.h index 9c5f469..811c6de 100644 --- a/arduino/libretuya/core/LibreTuyaCompat.h +++ b/cores/common/arduino/src/wiring_compat.h @@ -4,10 +4,9 @@ #include -#if LT_HAS_FREERTOS -#include -#include -#endif +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus // Definitions for error constants. #define esp_err_t int @@ -22,21 +21,22 @@ #define attachInterruptArg attachInterruptParam #define voidFuncPtrArg voidFuncPtrParam +// Additional Arduino compatibility macros +#define round(x) ((x) >= 0 ? (long)((x) + 0.5) : (long)((x)-0.5)) +#define digitalPinToInterrupt(pin) (pin) + // FreeRTOS utilities -#if LT_HAS_FREERTOS -// if xCoreID < 0 or CPU is unicore, it will use xTaskCreate, else xTaskCreatePinnedToCore -// allows to easily handle all possible situations without repetitive code -BaseType_t xTaskCreateUniversal( - TaskFunction_t pxTaskCode, - const char *const pcName, - const uint32_t usStackDepth, - void *const pvParameters, - UBaseType_t uxPriority, - TaskHandle_t *const pxCreatedTask, - const BaseType_t xCoreID -); +#define xTaskCreateUniversal(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask, xCoreID) \ + xTaskCreate(pxTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask) #define xTaskCreatePinnedToCore xTaskCreateUniversal -#endif // Default values from sdkconfig.h #define CONFIG_LWIP_MAX_ACTIVE_TCP 16 + +#ifdef __cplusplus +String ipToString(const IPAddress &ip); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/arduino/libretuya/core/LibreTuyaCustom.c b/cores/common/arduino/src/wiring_custom.c similarity index 63% rename from arduino/libretuya/core/LibreTuyaCustom.c rename to cores/common/arduino/src/wiring_custom.c index 0fe5738..a002ea1 100644 --- a/arduino/libretuya/core/LibreTuyaCustom.c +++ b/cores/common/arduino/src/wiring_custom.c @@ -1,19 +1,34 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-20. */ -#include "LibreTuyaCustom.h" +#include "wiring_custom.h" + +#if LT_HAS_FREERTOS +#include +#endif int _analogReadResolution = 10; // 0-1023 int _analogWriteResolution = 8; // 0-255 int _analogWritePeriod = 20000; // 50 Hz +static unsigned long periodicTasks[] = {0, 0}; + /** - * @brief Check if pin is invalid (too low or too high). + * @brief Run periodic tasks, like printing free heap or checking millis() overflow. + * + * This is called during delaying operations, like yield() or delay(). */ -bool pinInvalid(pin_size_t pinNumber) { -#ifdef PINS_COUNT - return pinNumber < 0 || pinNumber >= PINS_COUNT; -#else - return false; +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 } @@ -22,9 +37,38 @@ bool pinInvalid(pin_size_t pinNumber) { * Returns NULL if pin number is invalid. */ PinInfo *pinInfo(pin_size_t pinNumber) { - if (pinInvalid(pinNumber)) + if (pinNumber < 0 || pinNumber > PINS_GPIO_MAX) return NULL; - return &(pinTable[pinNumber]); + return lt_arduino_pin_gpio_map[pinNumber]; +} + +/** + * @brief Get PinInfo struct for the specified index. + * Returns NULL if pin index is invalid. + */ +PinInfo *pinByIndex(uint32_t index) { + if (index < 0 || index >= PINS_COUNT) + return NULL; + return &(lt_arduino_pin_info_list[index]); +} + +/** + * @brief Find PinInfo struct by GPIO number. + * Returns NULL if not found. + */ +PinInfo *pinByGpio(uint32_t gpio) { + for (uint32_t i = 0; i < PINS_COUNT; i++) { + if (lt_arduino_pin_info_list[i].gpio == gpio) + return &(lt_arduino_pin_info_list[i]); + } + return NULL; +} + +/** + * @brief Get index of PinInfo in the global pin info table. + */ +uint32_t pinIndex(PinInfo *pin) { + return pin - lt_arduino_pin_info_list; } /** diff --git a/arduino/libretuya/core/LibreTuyaCustom.h b/cores/common/arduino/src/wiring_custom.h similarity index 79% rename from arduino/libretuya/core/LibreTuyaCustom.h rename to cores/common/arduino/src/wiring_custom.h index 3c67122..4dd43f1 100644 --- a/arduino/libretuya/core/LibreTuyaCustom.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) @@ -60,12 +40,25 @@ typedef struct { uint32_t mode; } PinInfo; -extern PinInfo pinTable[]; +extern PinInfo lt_arduino_pin_info_list[PINS_COUNT]; +extern PinInfo *lt_arduino_pin_gpio_map[PINS_GPIO_MAX + 1]; // Custom Wiring methods -bool pinInvalid(pin_size_t pinNumber); +/** + * @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. + */ +bool startMainTask(void); + +void mainTask(const void *arg); // implemented in main.cpp +void runPeriodicTasks(); // implemented in wiring_custom.c + PinInfo *pinInfo(pin_size_t pinNumber); +PinInfo *pinByIndex(uint32_t index); +PinInfo *pinByGpio(uint32_t gpio); +uint32_t pinIndex(PinInfo *pin); bool pinSupported(PinInfo *pin, uint32_t mask); bool pinEnabled(PinInfo *pin, uint32_t mask); bool pinIsOutput(PinInfo *pin); diff --git a/cores/common/base/api/lt_cpu.h b/cores/common/base/api/lt_cpu.h new file mode 100644 index 0000000..7feb523 --- /dev/null +++ b/cores/common/base/api/lt_cpu.h @@ -0,0 +1,67 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include + +/** + * @brief Get CPU family ID (as lt_cpu_family_t enum member). + */ +lt_cpu_family_t lt_cpu_get_family(); + +/** + * @brief Get CPU family name as string. + */ +const char *lt_cpu_get_family_name(); + +/** + * @brief Get CPU model ID (as lt_cpu_model_t enum member). + */ +lt_cpu_model_t lt_cpu_get_model(); + +/** + * @brief Get CPU model name as string (uppercase). + */ +const char *lt_cpu_get_model_name(); + +/** + * @brief Get CPU model name as string (lowercase). + */ +const char *lt_cpu_get_model_code(); + +/** + * @brief Get CPU unique ID. This may be based on MAC, eFuse, etc. (family-specific). + * Note: the number is 24-bit (with the MSB being zero). + */ +uint32_t lt_cpu_get_unique_id(); + +/** + * @brief Get CPU ID based on the last three octets of MAC address. + * Note: the number is 24-bit (with the MSB being zero). + */ +uint32_t lt_cpu_get_mac_id(); + +/** + * @brief Get CPU core count. + */ +uint8_t lt_cpu_get_core_count(); + +/** + * @brief Get CPU core type name as string. + */ +const char *lt_cpu_get_core_type(); + +/** + * @brief Get CPU frequency in Hz. + */ +uint32_t lt_cpu_get_freq(); + +/** + * @brief Get CPU frequency in MHz. + */ +uint32_t lt_cpu_get_freq_mhz(); + +/** + * @brief Get CPU cycle count. + */ +uint32_t lt_cpu_get_cycle_count(); diff --git a/cores/common/base/api/lt_device.h b/cores/common/base/api/lt_device.h new file mode 100644 index 0000000..d57560e --- /dev/null +++ b/cores/common/base/api/lt_device.h @@ -0,0 +1,58 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include + +/** + * @brief Get LibreTiny version string. + */ +const char *lt_get_version(); + +/** + * @brief Get board code. + */ +const char *lt_get_board_code(); + +/** + * @brief Get device friendly name in format "LT--". + * Can be used as hostname. + */ +const char *lt_get_device_name(); + +/** + * @brief Reboot the CPU. + */ +void lt_reboot(); + +/** + * @brief Reboot the CPU with a watchdog timeout (if possible). + * + * @return whether WDT reboot is possible + */ +bool lt_reboot_wdt(); + +/** + * @brief Reboot the CPU and stay in download mode (if possible). + * + * @return whether download-mode reboot is possible + */ +bool lt_reboot_download_mode(); + +/** + * @brief Get the reason of last chip reboot. + */ +lt_reboot_reason_t lt_get_reboot_reason(); + +/** + * @brief Get a textual representation of a reboot reason. + * + * @param reason value to convert to text, pass 0 to read from lt_reboot_get_reason() + */ +const char *lt_get_reboot_reason_name(lt_reboot_reason_t reason); + +/** + * @brief Reconfigure GPIO pins used for debugging + * (SWD/JTAG), so that they can be used as normal I/O. + */ +void lt_gpio_recover(); diff --git a/cores/common/base/api/lt_flash.h b/cores/common/base/api/lt_flash.h new file mode 100644 index 0000000..549d6cb --- /dev/null +++ b/cores/common/base/api/lt_flash.h @@ -0,0 +1,55 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include + +/** + * @brief Read flash chip ID and return a lt_flash_id_t struct. + */ +lt_flash_id_t lt_flash_get_id(); + +/** + * @brief Get flash chip total size. + * + * The default implementation uses the least significant + * byte of the chip ID to determine the size. + */ +uint32_t lt_flash_get_size(); + +/** + * @brief Erase flash area. Flash can only be erased in blocks (usually 4 KiB). + * + * @param offset starting offset to erase (in bytes); must be multiple of the flash chip's block size + * @param length length of data to erase (in bytes); will be rounded up to block size + * @return whether erasing was successful + */ +bool lt_flash_erase(uint32_t offset, size_t length); + +/** + * @brief Erase a single block of flash (usually 4 KiB). + * + * @param offset offset of the block (in bytes); must be multiple of the flash chip's block size + * @return whether erasing was successful + */ +bool lt_flash_erase_block(uint32_t offset); + +/** + * @brief Read data from the flash. + * + * @param offset starting offset (in bytes) + * @param data pointer to where to store the data + * @param length length of data to read + * @return length of data successfully read (should equal 'length') + */ +uint32_t lt_flash_read(uint32_t offset, uint8_t *data, size_t length); + +/** + * @brief Write data to the flash. + * + * @param offset starting offset (in bytes) + * @param data pointer to data to write + * @param length length of data to write + * @return length of data successfully written (should equal 'length') + */ +uint32_t lt_flash_write(uint32_t offset, const uint8_t *data, size_t length); diff --git a/cores/common/base/api/lt_init.h b/cores/common/base/api/lt_init.h new file mode 100644 index 0000000..0782779 --- /dev/null +++ b/cores/common/base/api/lt_init.h @@ -0,0 +1,26 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#pragma once + +#include + +/** + * @brief Initialize the family core (optional). + * This method is family-specific; the family core can do whatever it wants to. + * This method is empty if not implemented, and shouldn't be called manually. + */ +void lt_init_family() __attribute__((weak)); + +/** + * @brief Initialize the board (variant). + * This method is empty if not implemented (which is usually the case), + * and shouldn't be called manually. + */ +void lt_init_variant() __attribute__((weak)); + +/** + * @brief Initialize the family's Arduino core (optional). + * This method is family-specific; the family core can do whatever it wants to. + * This method is empty if not implemented, and shouldn't be called manually. + */ +void lt_init_arduino() __attribute__((weak)); diff --git a/cores/common/base/api/lt_mem.h b/cores/common/base/api/lt_mem.h new file mode 100644 index 0000000..b198382 --- /dev/null +++ b/cores/common/base/api/lt_mem.h @@ -0,0 +1,30 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include + +/** + * @brief Get total RAM size. + */ +uint32_t lt_ram_get_size(); + +/** + * @brief Get total heap size. + */ +uint32_t lt_heap_get_size(); + +/** + * @brief Get free heap size. + */ +uint32_t lt_heap_get_free(); + +/** + * @brief Get lowest level of free heap memory. + */ +uint32_t lt_heap_get_min_free(); + +/** + * @brief Get largest block of heap that can be allocated at once. + */ +uint32_t lt_heap_get_max_alloc(); diff --git a/cores/common/base/api/lt_ota.h b/cores/common/base/api/lt_ota.h new file mode 100644 index 0000000..ef0ffca --- /dev/null +++ b/cores/common/base/api/lt_ota.h @@ -0,0 +1,60 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include +#include + +/** + * @brief Get OTA type of the device's chip. + */ +lt_ota_type_t lt_ota_get_type(); + +/** + * @brief Check if the specified OTA image is valid. + * + * @param index OTA index to check; 0 for single-OTA chips, 1 or 2 for dual-OTA chips + * @return true if index is valid for the chip's OTA type, and there is a valid image; false otherwise + */ +bool lt_ota_is_valid(uint8_t index); + +/** + * @brief Check if OTA rollback is possible (switching the stored index to another partition). + * + * Note that this is not the same as "switching" OTA with revert=true. + * + * @return true if 2nd image is valid and the chip is dual-OTA; false otherwise + */ +bool lt_ota_can_rollback(); + +/** + * @brief Get the currently running firmware's OTA index. + * + * @return OTA index if dual-OTA is supported, 0 otherwise + */ +uint8_t lt_ota_dual_get_current(); + +/** + * @brief Read the currently active OTA index, i.e. the one that will boot upon restart. + * + * @return OTA index if dual-OTA is supported, 0 otherwise + */ +uint8_t lt_ota_dual_get_stored(); + +/** + * @brief Check which UF2 OTA scheme should be used for applying firmware updates. + * + * @return OTA scheme of the target partition + */ +uf2_ota_scheme_t lt_ota_get_uf2_scheme(); + +/** + * @brief Try to switch OTA index to the other image. For single-OTA chips, only check if the upgrade image is valid. + * + * This can be used to "activate" the upgrade after flashing. + * + * @param revert switch if (and only if) the other image is already marked as active (i.e. + * switch back to the running image) + * @return false if the second image (or upgrade image) is not valid; false if writing failed; true otherwise + */ +bool lt_ota_switch(bool revert); diff --git a/cores/common/base/api/lt_utils.h b/cores/common/base/api/lt_utils.h new file mode 100644 index 0000000..be13c95 --- /dev/null +++ b/cores/common/base/api/lt_utils.h @@ -0,0 +1,47 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#pragma once + +#include + +// 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; \ + }) + +/** + * @brief Generate random bytes using rand(). + * + * @param buf destination pointer + * @param len how many bytes to generate + */ +void lt_rand_bytes(uint8_t *buf, size_t len); + +/** + * @brief Print data pointed to by buf in hexdump-like format (hex+ASCII). + * + * @param buf source pointer + * @param len how many bytes to print + * @param offset increment printed offset by this value + * @param width how many bytes on a line + */ +void hexdump( + const uint8_t *buf, + size_t len, +#ifdef __cplusplus + uint32_t offset = 0, + uint8_t width = 16 +#else + uint32_t offset, + uint8_t width +#endif +); diff --git a/cores/common/base/api/lt_wdt.h b/cores/common/base/api/lt_wdt.h new file mode 100644 index 0000000..af48fd4 --- /dev/null +++ b/cores/common/base/api/lt_wdt.h @@ -0,0 +1,23 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +#include + +/** + * @brief Enable the hardware watchdog. + * + * @param timeout watchdog timeout, milliseconds + * @return whether the chip has a hardware watchdog + */ +bool lt_wdt_enable(uint32_t timeout); + +/** + * @brief Disable the hardware watchdog. + */ +void lt_wdt_disable(); + +/** + * @brief Feed/reset the hardware watchdog timer. + */ +void lt_wdt_feed(); diff --git a/platform/common/fixups/lib_inc/certs.h b/cores/common/base/compat/certs.h similarity index 100% rename from platform/common/fixups/lib_inc/certs.h rename to cores/common/base/compat/certs.h diff --git a/platform/common/fixups/lib_inc/err.h b/cores/common/base/compat/err.h similarity index 100% rename from platform/common/fixups/lib_inc/err.h rename to cores/common/base/compat/err.h diff --git a/platform/realtek-ambz/fixups/lwip/lwip_timers.h b/cores/common/base/compat/lwip/lwip_timers.h similarity index 100% rename from platform/realtek-ambz/fixups/lwip/lwip_timers.h rename to cores/common/base/compat/lwip/lwip_timers.h diff --git a/platform/common/fixups/lib_inc/netdb.h b/cores/common/base/compat/netdb.h similarity index 100% rename from platform/common/fixups/lib_inc/netdb.h rename to cores/common/base/compat/netdb.h diff --git a/platform/common/fixups/lib_inc/netif.h b/cores/common/base/compat/netif.h similarity index 100% rename from platform/common/fixups/lib_inc/netif.h rename to cores/common/base/compat/netif.h diff --git a/platform/common/fixups/lib_inc/sockets.h b/cores/common/base/compat/sockets.h similarity index 100% rename from platform/common/fixups/lib_inc/sockets.h rename to cores/common/base/compat/sockets.h diff --git a/platform/common/fixups/lib_inc/sys.h b/cores/common/base/compat/sys.h similarity index 100% rename from platform/common/fixups/lib_inc/sys.h rename to cores/common/base/compat/sys.h diff --git a/platform/common/fixups/lib_inc/tcpip.h b/cores/common/base/compat/tcpip.h similarity index 100% rename from platform/common/fixups/lib_inc/tcpip.h rename to cores/common/base/compat/tcpip.h diff --git a/platform/common/fixups/lib_inc/udp.h b/cores/common/base/compat/udp.h similarity index 93% rename from platform/common/fixups/lib_inc/udp.h rename to cores/common/base/compat/udp.h index 70524e9..280996b 100644 --- a/platform/common/fixups/lib_inc/udp.h +++ b/cores/common/base/compat/udp.h @@ -7,4 +7,5 @@ // this is included only by wifi_simple_config.c // which uses lwip_ntohl without parentheses // so the #define from lwip/def.h doesn't work +#undef lwip_ntohl #define lwip_ntohl lwip_htonl diff --git a/arduino/libretuya/port/flashdb/fal_cfg.h b/cores/common/base/config/fal_cfg.h similarity index 87% rename from arduino/libretuya/port/flashdb/fal_cfg.h rename to cores/common/base/config/fal_cfg.h index d5bc0f0..43775bc 100644 --- a/arduino/libretuya/port/flashdb/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,7 @@ extern const struct fal_flash_dev flash0; #include /** - * @brief Root partition table, representing the entire flash. + * @brief "Root" partition entry, representing the entire flash. + * Declared and initialized in lt_main.c. */ extern fal_partition_t fal_root_part; diff --git a/arduino/libretuya/port/flashdb/fdb_cfg.h b/cores/common/base/config/fdb_cfg.h similarity index 97% rename from arduino/libretuya/port/flashdb/fdb_cfg.h rename to cores/common/base/config/fdb_cfg.h index a967900..680428a 100644 --- a/arduino/libretuya/port/flashdb/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/platform/common/config/lwipopts.h b/cores/common/base/config/lwipopts.h similarity index 56% rename from platform/common/config/lwipopts.h rename to cores/common/base/config/lwipopts.h index 6bd6a5c..833df85 100644 --- a/platform/common/config/lwipopts.h +++ b/cores/common/base/config/lwipopts.h @@ -1,5 +1,7 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-08-26. */ +#pragma once + #define LWIP_TIMEVAL_PRIVATE 0 #define LWIP_NETIF_HOSTNAME 1 // to support hostname changing #define LWIP_SO_RCVBUF 1 // for ioctl(FIONREAD) @@ -9,6 +11,8 @@ #include_next "lwipopts.h" +#include + // set lwIP debugging options according to LT config #if LT_DEBUG_LWIP #undef LWIP_DEBUG @@ -64,24 +68,25 @@ #undef IP6_DEBUG #undef MDNS_DEBUG +#undef LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS +#undef LWIP_PROVIDE_ERRNO /** Set this to 1 to support DNS names (or IP address strings) to set sntp servers * One server address/name can be defined as default if SNTP_SERVER_DNS == 1: * \#define SNTP_SERVER_ADDRESS "pool.ntp.org" */ -#define SNTP_SERVER_DNS 1 +#define SNTP_SERVER_DNS 1 -#define SNTP_SET_SYSTEM_TIME_US(sec, us) \ - do { \ - struct timeval tv = { .tv_sec = sec, .tv_usec = us }; \ - settimeofday(&tv, NULL); \ - } while (0); - -#define SNTP_GET_SYSTEM_TIME(sec, us) \ - do { \ - struct timeval tv = { .tv_sec = 0, .tv_usec = 0 }; \ - gettimeofday(&tv, NULL); \ - (sec) = tv.tv_sec; \ - (us) = tv.tv_usec; \ - } while (0); +#define SNTP_SET_SYSTEM_TIME_US(sec, us) \ + do { \ + struct timeval tv = {.tv_sec = sec, .tv_usec = us}; \ + settimeofday(&tv, NULL); \ + } while (0); +#define SNTP_GET_SYSTEM_TIME(sec, us) \ + do { \ + struct timeval tv = {.tv_sec = 0, .tv_usec = 0}; \ + gettimeofday(&tv, NULL); \ + (sec) = tv.tv_sec; \ + (us) = tv.tv_usec; \ + } while (0); diff --git a/arduino/libretuya/port/printf/printf_config.h b/cores/common/base/config/printf_config.h similarity index 84% rename from arduino/libretuya/port/printf/printf_config.h rename to cores/common/base/config/printf_config.h index e89a456..2588c06 100644 --- a/arduino/libretuya/port/printf/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 @@ -64,7 +68,25 @@ void putchar_p(char c, unsigned long port); #endif // LT_UART_SILENT_ENABLED && !LT_UART_SILENT_ALL -#if LT_UART_SILENT_ALL +#if !LT_UART_SILENT_ENABLED + +#define WRAP_PRINTF(name) \ + WRAP_DISABLE_DECL(name) \ + int __wrap_##name(const char *format, ...) { \ + va_list va; \ + va_start(va, format); \ + const int ret = vprintf(format, va); \ + va_end(va); \ + return ret; \ + } + +#define WRAP_VPRINTF(name) \ + WRAP_DISABLE_DECL(name) \ + int __wrap_##name(const char *format, va_list arg) { \ + return vprintf(format, arg); \ + } + +#elif LT_UART_SILENT_ALL #define WRAP_PRINTF(name) \ WRAP_DISABLE_DECL(name) \ @@ -78,7 +100,7 @@ void putchar_p(char c, unsigned long port); return 0; \ } -#else // !LT_UART_SILENT_ALL +#else // !LT_UART_SILENT_ENABLED || !LT_UART_SILENT_ALL #define WRAP_PRINTF(name) \ WRAP_DISABLE_DECL(name) \ @@ -98,7 +120,7 @@ void putchar_p(char c, unsigned long port); return vprintf(format, arg); \ } -#endif // !LT_UART_SILENT_ALL +#endif // !LT_UART_SILENT_ENABLED || !LT_UART_SILENT_ALL #define WRAP_SPRINTF(name) \ int __wrap_##name(char *s, const char *format, ...) { \ @@ -127,3 +149,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/platform/common/fixups/errno.h b/cores/common/base/fixups/errno.h similarity index 100% rename from platform/common/fixups/errno.h rename to cores/common/base/fixups/errno.h diff --git a/platform/common/fixups/lwip/errno.h b/cores/common/base/fixups/lwip/errno.h similarity index 100% rename from platform/common/fixups/lwip/errno.h rename to cores/common/base/fixups/lwip/errno.h diff --git a/cores/common/base/fixups/malloc.c b/cores/common/base/fixups/malloc.c new file mode 100644 index 0000000..7819ac9 --- /dev/null +++ b/cores/common/base/fixups/malloc.c @@ -0,0 +1,60 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +// Generic implementation of malloc() family wrappers for FreeRTOS + +#if LT_HAS_FREERTOS + +#include +#include +#include + +#include + +// no such thing in FreeRTOS, but present on most vendor SDKs +extern void *LT_REALLOC_FUNC(void *pv, size_t xWantedSize); + +void *__wrap_malloc(size_t size) { + return pvPortMalloc(size); +} + +void *__wrap_calloc(size_t num, size_t size) { + void *ptr; + if (num == 0 || size == 0) + num = size = 1; + ptr = pvPortMalloc(num * size); + if (ptr) + memset(ptr, 0, num * size); + return ptr; +} + +void *__wrap_realloc(void *ptr, size_t new_size) { +#if LT_REMALLOC + void *nptr = pvPortMalloc(new_size); + if (nptr) { + memcpy(nptr, ptr, new_size); + vPortFree(ptr); + } + return nptr; +#else + return LT_REALLOC_FUNC(ptr, new_size); +#endif +} + +void __wrap_free(void *ptr) { + vPortFree(ptr); +} + +__attribute__((alias("__wrap_malloc"))) void *__wrap__malloc_r(void *reent, size_t size); +__attribute__((alias("__wrap_calloc"))) void *__wrap__calloc_r(void *reent, size_t num, size_t size); +__attribute__((alias("__wrap_realloc"))) void *__wrap__realloc_r(void *reent, void *ptr, size_t new_size); +__attribute__((alias("__wrap_free"))) void __wrap__free_r(void *reent, void *ptr); + +#endif + +// Additionally, define zalloc() as a shorthand to calloc() - some implementation use it + +void *__wrap_zalloc(size_t size) { + return __wrap_calloc(1, size); +} + +__attribute__((alias("__wrap_zalloc"), weak)) void *zalloc(size_t size); diff --git a/cores/common/base/libretiny.h b/cores/common/base/libretiny.h new file mode 100644 index 0000000..22a133a --- /dev/null +++ b/cores/common/base/libretiny.h @@ -0,0 +1,49 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-04-28. */ + +#pragma once + +// C standard libraries +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// LibreTiny version macros +#ifndef LT_VERSION +#define LT_VERSION 1.0.0 +#endif +#ifndef LT_BOARD +#define LT_BOARD unknown +#endif +#define STRINGIFY(x) #x +#define STRINGIFY_MACRO(x) STRINGIFY(x) +#define LT_VERSION_STR STRINGIFY_MACRO(LT_VERSION) +#define LT_BOARD_STR STRINGIFY_MACRO(LT_BOARD) +#define GCC_VERSION_STR \ + STRINGIFY_MACRO(__GNUC__) "." STRINGIFY_MACRO(__GNUC_MINOR__) "." STRINGIFY_MACRO(__GNUC_PATCHLEVEL__) +#define LT_BANNER_STR \ + "LibreTiny v" LT_VERSION_STR " on " LT_BOARD_STR ", compiled at " __DATE__ " " __TIME__ ", GCC " GCC_VERSION_STR \ + " (-O" STRINGIFY_MACRO(__OPTIMIZE_LEVEL__) ")" + +// Functional macros +#define LT_BANNER() LT_LOG(LT_LEVEL_INFO, __FUNCTION__, __LINE__, LT_BANNER_STR) + +// Types & macros +#include "lt_config.h" // platform configuration options +#include "lt_types.h" // types & enums +// Family-specific macros +#include +// Board variant (pin definitions) +#include LT_VARIANT_H +// APIs +#include "lt_api.h" // main API function definitions +#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_api.c b/cores/common/base/lt_api.c new file mode 100644 index 0000000..7259fd0 --- /dev/null +++ b/cores/common/base/lt_api.c @@ -0,0 +1,270 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-04-29. */ + +#include "lt_api.h" + +#include + +#if LT_HAS_FREERTOS +#include +#include +#endif + +/* _____ _____ _ _ + / ____| __ \| | | | + | | | |__) | | | | + | | | ___/| | | | + | |____| | | |__| | + \_____|_| \____*/ +lt_cpu_family_t lt_cpu_get_family() { + return FAMILY; +} + +const char *lt_cpu_get_family_name() { + return STRINGIFY_MACRO(FAMILY) + 2; +} + +__attribute__((weak)) lt_cpu_model_t lt_cpu_get_model() { + return MCU; +} + +const char *lt_cpu_get_model_name() { + return STRINGIFY_MACRO(MCU); +} + +const char *lt_cpu_get_model_code() { + return STRINGIFY_MACRO(MCULC); +} + +__attribute__((weak)) uint8_t lt_cpu_get_core_count() { + return 1; +} + +#if LT_HAS_FREERTOS +__attribute__((weak)) uint32_t lt_cpu_get_freq() { + return configCPU_CLOCK_HZ; +} +#endif + +uint32_t lt_cpu_get_freq_mhz() { + return lt_cpu_get_freq() / 1000000; +} + +#if LT_HAS_FREERTOS +__attribute__((weak)) uint32_t lt_cpu_get_cycle_count() { + return xTaskGetTickCount() * (configCPU_CLOCK_HZ / configTICK_RATE_HZ); +} +#endif + +/*_____ _ + | __ \ (_) + | | | | _____ ___ ___ ___ + | | | |/ _ \ \ / / |/ __/ _ \ + | |__| | __/\ V /| | (_| __/ + |_____/ \___| \_/ |_|\___\__*/ +static char *device_name = NULL; + +const char *lt_get_version() { + return LT_VERSION_STR; +} + +const char *lt_get_board_code() { + return LT_BOARD_STR; +} + +const char *lt_get_device_name() { + if (device_name) + return device_name; + uint32_t chip_id = lt_cpu_get_mac_id(); + uint8_t *id = (uint8_t *)&chip_id; + + const char *model = lt_cpu_get_model_code(); + uint8_t model_len = strlen(model); + device_name = (char *)malloc(3 + model_len + 1 + 6 + 1); + + sprintf(device_name, "LT-%s-%02x%02x%02x", model, id[0], id[1], id[2]); + return device_name; +} + +__attribute__((weak)) bool lt_reboot_wdt() { + if (!lt_wdt_enable(1L)) + return false; + while (1) {} +} + +__attribute__((weak)) bool lt_reboot_download_mode() { + return false; +} + +const char *lt_get_reboot_reason_name(lt_reboot_reason_t reason) { + if (!reason) + reason = lt_get_reboot_reason(); + switch (reason) { + case RESET_REASON_POWER: + return "Power-On"; + case RESET_REASON_BROWNOUT: + return "Brownout"; + case RESET_REASON_HARDWARE: + return "HW Reboot"; + case RESET_REASON_SOFTWARE: + return "SW Reboot"; + case RESET_REASON_WATCHDOG: + return "WDT Reset"; + case RESET_REASON_CRASH: + return "Crash"; + case RESET_REASON_SLEEP: + return "Sleep Wakeup"; + default: + return "Unknown"; + } +} + +__attribute__((weak)) void lt_gpio_recover() { + // nop by default +} + +/*______ _ _ + | ____| | | | + | |__ | | __ _ ___| |__ + | __| | |/ _` / __| '_ \ + | | | | (_| \__ \ | | | + |_| |_|\__,_|___/_| |*/ +__attribute__((weak)) uint32_t lt_flash_get_size() { + lt_flash_id_t id = lt_flash_get_id(); + if (id.chip_size_id >= 0x14 && id.chip_size_id <= 0x19) { + return (1 << id.chip_size_id); + } +#ifdef FLASH_LENGTH + return FLASH_LENGTH; +#else + return 0; +#endif +} + +bool lt_flash_erase(uint32_t offset, size_t length) { + return fal_partition_erase(fal_root_part, offset, length) >= 0; +} + +bool lt_flash_erase_block(uint32_t offset) { + return fal_partition_erase(fal_root_part, offset, 1) >= 0; +} + +uint32_t lt_flash_read(uint32_t offset, uint8_t *data, size_t length) { + int ret = fal_partition_read(fal_root_part, offset, data, length); + if (ret == -1) + return 0; + return ret; +} + +uint32_t lt_flash_write(uint32_t offset, const uint8_t *data, size_t length) { + int ret = fal_partition_write(fal_root_part, offset, data, length); + if (ret == -1) + return 0; + return ret; +} + +/*__ __ + | \/ | + | \ / | ___ _ __ ___ ___ _ __ _ _ + | |\/| |/ _ \ '_ ` _ \ / _ \| '__| | | | + | | | | __/ | | | | | (_) | | | |_| | + |_| |_|\___|_| |_| |_|\___/|_| \__, | + __/ | + |__*/ +#if LT_HAS_FREERTOS +__attribute__((weak)) uint32_t lt_heap_get_size() { + return configTOTAL_HEAP_SIZE; +} + +__attribute__((weak)) uint32_t lt_heap_get_free() { + return xPortGetFreeHeapSize(); +} + +__attribute__((weak)) uint32_t lt_heap_get_min_free() { + return xPortGetMinimumEverFreeHeapSize(); +} +#endif + +__attribute__((weak)) uint32_t lt_heap_get_max_alloc() { + return 0; +} + +/* ____ _______ + / __ \__ __|/\ + | | | | | | / \ + | | | | | | / /\ \ + | |__| | | |/ ____ \ + \____/ |_/_/ \*/ +bool lt_ota_can_rollback() { + if (lt_ota_get_type() != OTA_TYPE_DUAL) + return false; + uint8_t current = lt_ota_dual_get_current(); + return lt_ota_is_valid(current ^ 0b11); +} + +uf2_ota_scheme_t lt_ota_get_uf2_scheme() { + if (lt_ota_get_type() == OTA_TYPE_SINGLE) + return UF2_SCHEME_DEVICE_SINGLE; + uint8_t current = lt_ota_dual_get_current(); + // UF2_SCHEME_DEVICE_DUAL_1 or UF2_SCHEME_DEVICE_DUAL_2 + return (uf2_ota_scheme_t)(current ^ 0b11); +} + +/*_ _ _ _ _ + | | | | | (_) | + | | | | |_ _| |___ + | | | | __| | / __| + | |__| | |_| | \__ \ + \____/ \__|_|_|__*/ +void lt_rand_bytes(uint8_t *buf, size_t len) { + int *data = (int *)buf; + size_t i; + for (i = 0; len >= sizeof(int); len -= sizeof(int)) { + data[i++] = rand(); + } + if (len) { + int rem = rand(); + unsigned char *pRem = (unsigned char *)&rem; + memcpy(buf + i * sizeof(int), pRem, len); + } +} + +void hexdump(const uint8_t *buf, size_t len, uint32_t offset, uint8_t width) { + uint16_t pos = 0; + while (pos < len) { + // print hex offset + printf("%06lx ", offset + pos); + // calculate current line width + uint8_t lineWidth = MIN(width, len - pos); + // print hexadecimal representation + for (uint8_t i = 0; i < lineWidth; i++) { + if (i % 8 == 0) { + printf(" "); + } + printf("%02x ", buf[pos + i]); + } + // print ascii representation + printf(" |"); + for (uint8_t i = 0; i < lineWidth; i++) { + char c = buf[pos + i]; + putchar((c >= 0x20 && c <= 0x7f) ? c : '.'); + } + puts("|\r"); + pos += lineWidth; + } +} + +/*_ __ _ _ _ + \ \ / / | | | | | | + \ \ /\ / /_ _| |_ ___| |__ __| | ___ __ _ + \ \/ \/ / _` | __/ __| '_ \ / _` |/ _ \ / _` | + \ /\ / (_| | || (__| | | | (_| | (_) | (_| | + \/ \/ \__,_|\__\___|_| |_|\__,_|\___/ \__, | + __/ | + |___*/ +__attribute__((weak)) bool lt_wdt_enable(uint32_t timeout) { + return false; +} + +__attribute__((weak)) void lt_wdt_disable() {} + +__attribute__((weak)) void lt_wdt_feed() {} diff --git a/cores/common/base/lt_api.h b/cores/common/base/lt_api.h new file mode 100644 index 0000000..8564dbd --- /dev/null +++ b/cores/common/base/lt_api.h @@ -0,0 +1,24 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-09. */ + +#pragma once + +// This file collects all LibreTiny C API includes. +// The functions are implemented in lt_api.c, which is located +// in the common core, and in the family cores. + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +#include "api/lt_cpu.h" +#include "api/lt_device.h" +#include "api/lt_flash.h" +#include "api/lt_init.h" +#include "api/lt_mem.h" +#include "api/lt_ota.h" +#include "api/lt_utils.h" +#include "api/lt_wdt.h" + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/arduino/libretuya/core/LibreTuyaConfig.h b/cores/common/base/lt_config.h similarity index 100% rename from arduino/libretuya/core/LibreTuyaConfig.h rename to cores/common/base/lt_config.h diff --git a/arduino/libretuya/core/lt_logger.c b/cores/common/base/lt_logger.c similarity index 84% rename from arduino/libretuya/core/lt_logger.c rename to cores/common/base/lt_logger.c index f3feac5..bec2361 100644 --- a/arduino/libretuya/core/lt_logger.c +++ b/cores/common/base/lt_logger.c @@ -1,11 +1,16 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-04-28. */ #include "lt_logger.h" +#include -#include +#if LT_HAS_PRINTF #include +#include +#else +#include +#endif -#if LT_LOGGER_TASK && LT_HAS_FREERTOS +#if (LT_LOGGER_TIMESTAMP || LT_LOGGER_TASK) && LT_HAS_FREERTOS #include #include #endif @@ -42,7 +47,9 @@ static const uint8_t colors[] = { }; #endif +#if LIBRETINY_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 +61,13 @@ void lt_log(const uint8_t level, const char *format, ...) { return; #if LT_LOGGER_TIMESTAMP +#if LIBRETINY_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 +90,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 +145,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/arduino/libretuya/core/lt_logger.h b/cores/common/base/lt_logger.h similarity index 98% rename from arduino/libretuya/core/lt_logger.h rename to cores/common/base/lt_logger.h index 816f6f2..0af8f5f 100644 --- a/arduino/libretuya/core/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__) @@ -90,7 +93,7 @@ void lt_log_disable(); #define LT_FM(...) #endif -#if LT_LOG_HEAP +#if LT_LOG_HEAP && LT_HAS_FREERTOS #define LT_HEAP_I() LT_I("Free heap: %u", LT_HEAP_FUNC()); #else #define LT_HEAP_I() @@ -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 new file mode 100644 index 0000000..92a4bd0 --- /dev/null +++ b/cores/common/base/lt_main.c @@ -0,0 +1,31 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-06-19. */ + +#include + +#include + +fal_partition_t fal_root_part = NULL; + +// Initialize C library +void __libc_init_array(void); +// Main app entrypoint +int main(void); + +int lt_main(void) { + // early initialize the family and variant + lt_init_family(); + lt_init_variant(); + // print a startup banner + LT_BANNER(); + // initialize C library + __libc_init_array(); + // inform about the reset reason + LT_I("Reset reason: %u", lt_get_reboot_reason()); + // initialize FAL + fal_init(); + // provide root partition + fal_root_part = (fal_partition_t)fal_partition_find("root"); + + // run the application + return main(); +} diff --git a/arduino/libretuya/posix/lt_posix_api.h b/cores/common/base/lt_posix_api.h similarity index 72% rename from arduino/libretuya/posix/lt_posix_api.h rename to cores/common/base/lt_posix_api.h index c27d2f4..e703029 100644 --- a/arduino/libretuya/posix/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..6d4e623 --- /dev/null +++ b/cores/common/base/lt_types.h @@ -0,0 +1,79 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-05-28. */ + +#pragma once + +#include + +#define CPU_MODEL(family, chip_id) (((family >> 24) << 8) | chip_id) +#define CPU_MODEL_ENUM(family, chip_id) (lt_cpu_model_t) CPU_MODEL(family, chip_id) + +#define RESET_REASON_UNKNOWN REBOOT_REASON_UNKNOWN +#define RESET_REASON_POWER REBOOT_REASON_POWER +#define RESET_REASON_BROWNOUT REBOOT_REASON_BROWNOUT +#define RESET_REASON_HARDWARE REBOOT_REASON_HARDWARE +#define RESET_REASON_SOFTWARE REBOOT_REASON_SOFTWARE +#define RESET_REASON_WATCHDOG REBOOT_REASON_WATCHDOG +#define RESET_REASON_CRASH REBOOT_REASON_CRASH +#define RESET_REASON_SLEEP REBOOT_REASON_SLEEP +#define RESET_REASON_MAX REBOOT_REASON_MAX + +typedef enum { + F_RTL8710A = 0x9FFFD543, // Realtek Ameba1 + F_RTL8710B = 0x22E0D6FC, // Realtek AmebaZ (realtek-ambz) + F_RTL8720C = 0xE08F7564, // Realtek AmebaZ2 + F_RTL8720D = 0x3379CFE2, // Realtek AmebaD + F_BK7231U = 0x675A40B0, // Beken 7231U/7231T + F_BK7231N = 0x7B3EF230, // Beken 7231N + F_BK7251 = 0x6A82CC42, // Beken 7251/7252 + F_BL60X = 0xDE1270B7, // Boufallo 602 +} lt_cpu_family_t; + +typedef enum { + // Realtek AmebaZ + // IDs copied from rtl8710b_efuse.h + RTL8710BL = CPU_MODEL(F_RTL8710B, 0xE0), // ??? + RTL8710BN = CPU_MODEL(F_RTL8710B, 0xFF), // CHIPID_8710BN / QFN32 + RTL8710BU = CPU_MODEL(F_RTL8710B, 0xFE), // CHIPID_8710BU / QFN48 + RTL8710BX = CPU_MODEL(F_RTL8710B, 0xF6), // found on an actual RTL8710BX + RTL8710L0 = CPU_MODEL(F_RTL8710B, 0xFB), // CHIPID_8710BN_L0 / QFN32 + RTL8711BN = CPU_MODEL(F_RTL8710B, 0xFD), // CHIPID_8711BN / QFN48 + RTL8711BU = CPU_MODEL(F_RTL8710B, 0xFC), // CHIPID_8711BG / QFN68 + // Beken 72XX + BK7231T = CPU_MODEL(F_BK7231U, 0x1A), // *SCTRL_CHIP_ID = 0x7231a + BK7231N = CPU_MODEL(F_BK7231N, 0x1C), // *SCTRL_CHIP_ID = 0x7231c + BL2028N = CPU_MODEL(F_BK7231N, 0x1C), // *SCTRL_CHIP_ID = 0x7231c + BK7252 = CPU_MODEL(F_BK7251, 0x00), // TODO +} lt_cpu_model_t; + +/** + * @brief Reset reason enumeration. + */ +typedef enum { + REBOOT_REASON_UNKNOWN = 1, + REBOOT_REASON_POWER = 2, + REBOOT_REASON_BROWNOUT = 3, + REBOOT_REASON_HARDWARE = 4, + REBOOT_REASON_SOFTWARE = 5, + REBOOT_REASON_WATCHDOG = 6, + REBOOT_REASON_CRASH = 7, + REBOOT_REASON_SLEEP = 8, + REBOOT_REASON_MAX = 9, +} lt_reboot_reason_t; + +/** + * @brief Flash chip ID structure. + */ +typedef struct { + uint8_t manufacturer_id; + uint8_t chip_id; + uint8_t chip_size_id; +} lt_flash_id_t; + +/** + * @brief Chip's OTA type enumeration. + */ +typedef enum { + OTA_TYPE_SINGLE = 0, + OTA_TYPE_DUAL = 1, + OTA_TYPE_FILE = 2, +} lt_ota_type_t; diff --git a/arduino/libretuya/posix/.clang-format b/cores/common/base/posix/.clang-format similarity index 100% rename from arduino/libretuya/posix/.clang-format rename to cores/common/base/posix/.clang-format diff --git a/arduino/libretuya/common/itoa.c b/cores/common/base/posix/itoa.c similarity index 100% rename from arduino/libretuya/common/itoa.c rename to cores/common/base/posix/itoa.c diff --git a/arduino/libretuya/posix/strcasecmp.c b/cores/common/base/posix/strcasecmp.c similarity index 100% rename from arduino/libretuya/posix/strcasecmp.c rename to cores/common/base/posix/strcasecmp.c diff --git a/arduino/libretuya/posix/strdup.c b/cores/common/base/posix/strdup.c similarity index 86% rename from arduino/libretuya/posix/strdup.c rename to cores/common/base/posix/strdup.c index 160d396..db16569 100644 --- a/arduino/libretuya/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/arduino/libretuya/libraries/HTTPClient/strptime/strptime.c b/cores/common/base/posix/strptime.c similarity index 100% rename from arduino/libretuya/libraries/HTTPClient/strptime/strptime.c rename to cores/common/base/posix/strptime.c diff --git a/arduino/libretuya/port/printf/putchar.c b/cores/common/base/wraps/putchar.c similarity index 100% rename from arduino/libretuya/port/printf/putchar.c rename to cores/common/base/wraps/putchar.c diff --git a/arduino/libretuya/port/printf/puts.c b/cores/common/base/wraps/puts.c similarity index 100% rename from arduino/libretuya/port/printf/puts.c rename to cores/common/base/wraps/puts.c diff --git a/arduino/realtek-ambz/cores/arduino/SerialClass.cpp b/cores/realtek-amb/arduino/libraries/Serial/Serial.cpp similarity index 64% rename from arduino/realtek-ambz/cores/arduino/SerialClass.cpp rename to cores/realtek-amb/arduino/libraries/Serial/Serial.cpp index 62c265a..c387d47 100644 --- a/arduino/realtek-ambz/cores/arduino/SerialClass.cpp +++ b/cores/realtek-amb/arduino/libraries/Serial/Serial.cpp @@ -1,18 +1,21 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-07-03. */ -#include "SerialClass.h" +#include "Serial.h" -#ifdef PIN_SERIAL0_TX +#include +#include + +#if HAS_SERIAL0 SerialClass Serial0(UART0_DEV, UART0_IRQ, PIN_SERIAL0_RX, PIN_SERIAL0_TX); #endif -#ifdef PIN_SERIAL1_TX +#if HAS_SERIAL1 SerialClass Serial1(UART1_DEV, UART1_IRQ, PIN_SERIAL1_RX, PIN_SERIAL1_TX); #endif -#ifdef PIN_SERIAL2_TX +#if HAS_SERIAL2 SerialClass Serial2(UART2_DEV, UART_LOG_IRQ, PIN_SERIAL2_RX, PIN_SERIAL2_TX); #endif -SerialClass::SerialClass(UART_TypeDef *uart, IRQn irq, pin_size_t rx, pin_size_t tx) { +SerialClass::SerialClass(void *uart, uint8_t irq, pin_size_t rx, pin_size_t tx) { data.uart = uart; data.buf = NULL; this->irq = irq; @@ -20,18 +23,49 @@ SerialClass::SerialClass(UART_TypeDef *uart, IRQn irq, pin_size_t rx, pin_size_t this->tx = tx; } -static uint32_t callback(void *param) { - SerialData *data = (SerialData *)param; +#if LT_AUTO_DOWNLOAD_REBOOT +static uint8_t adrState = 0; - uint32_t intcr = data->uart->DLH_INTCR; - data->uart->DLH_INTCR = 0; +// clang-format off +// Family ID, big-endian +static const uint8_t adrCmd[] = { + 0x55, 0xAA, + (FAMILY >> 24) & 0xFF, + (FAMILY >> 16) & 0xFF, + (FAMILY >> 8) & 0xFF, + (FAMILY >> 0) & 0xFF +}; + +// clang-format on + +static void adrParse(uint8_t c) { + adrState = (adrState + 1) * (c == adrCmd[adrState]); + if (adrState == 6) { + LT_I("Auto download mode: rebooting"); + LT.restartDownloadMode(); + } +} +#endif + +static uint32_t callback(void *param) { + SerialData *data = (SerialData *)param; + UART_TypeDef *uart = (UART_TypeDef *)data->uart; + + uint32_t intcr = uart->DLH_INTCR; + uart->DLH_INTCR = 0; uint8_t c; - UART_CharGet(data->uart, &c); - if (c) + while (UART_Readable(uart)) { + UART_CharGet(uart, &c); +#if LT_AUTO_DOWNLOAD_REBOOT && defined(PIN_SERIAL2_RX) + // parse UART protocol commands on UART2 + if (uart == UART2_DEV) + adrParse(c); +#endif data->buf->store_char(c); + } - data->uart->DLH_INTCR = intcr; + uart->DLH_INTCR = intcr; return 0; } @@ -64,8 +98,8 @@ void SerialClass::begin(unsigned long baudrate, uint16_t config) { cfg.Parity = parity; cfg.ParityType = parityType; cfg.StopBit = stopBits; - UART_Init(data.uart, &cfg); - UART_SetBaud(data.uart, baudrate); + UART_Init((UART_TypeDef *)data.uart, &cfg); + UART_SetBaud((UART_TypeDef *)data.uart, baudrate); if (data.buf) { data.buf->clear(); @@ -102,11 +136,11 @@ int SerialClass::read() { } void SerialClass::flush() { - UART_WaitBusy(data.uart, 10); + UART_WaitBusy((UART_TypeDef *)data.uart, 10); } size_t SerialClass::write(uint8_t c) { - while (UART_Writable(data.uart) == 0) {} - UART_CharPut(data.uart, c); + while (UART_Writable((UART_TypeDef *)data.uart) == 0) {} + UART_CharPut((UART_TypeDef *)data.uart, c); return 1; } diff --git a/arduino/realtek-ambz/cores/arduino/SerialClass.h b/cores/realtek-amb/arduino/libraries/Serial/Serial.h similarity index 80% rename from arduino/realtek-ambz/cores/arduino/SerialClass.h rename to cores/realtek-amb/arduino/libraries/Serial/Serial.h index e159f04..aa0a78b 100644 --- a/arduino/realtek-ambz/cores/arduino/SerialClass.h +++ b/cores/realtek-amb/arduino/libraries/Serial/Serial.h @@ -2,14 +2,14 @@ #pragma once -#include +#include #include #include using namespace arduino; typedef struct { - UART_TypeDef *uart; + void *uart; // UART_TypeDef RingBuffer *buf; } SerialData; @@ -17,12 +17,12 @@ class SerialClass : public HardwareSerial { private: // data accessible to IRQ handler SerialData data; - IRQn irq; + uint8_t irq; // IRQn pin_size_t rx; pin_size_t tx; public: - SerialClass(UART_TypeDef *uart, IRQn irq, pin_size_t rx, pin_size_t tx); + SerialClass(void *uart, uint8_t irq, pin_size_t rx, pin_size_t tx); inline void begin(unsigned long baudrate) { begin(baudrate, SERIAL_8N1); @@ -42,5 +42,3 @@ class SerialClass : public HardwareSerial { using Print::write; }; - -#define HAS_SERIAL_CLASS 1 diff --git a/arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.cpp b/cores/realtek-amb/arduino/libraries/SoftwareSerial/SoftwareSerial.cpp similarity index 95% rename from arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.cpp rename to cores/realtek-amb/arduino/libraries/SoftwareSerial/SoftwareSerial.cpp index 75cc4d4..ebd7f0f 100644 --- a/arduino/realtek-ambz/libraries/SoftwareSerial/SoftwareSerial.cpp +++ b/cores/realtek-amb/arduino/libraries/SoftwareSerial/SoftwareSerial.cpp @@ -1,12 +1,7 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-07-03. */ -#include "SoftwareSerial.h" - -extern "C" { - -#include - -} // extern "C" +#include +#include #define TIMER_MAX 3 #define OBJ ((gtimer_t *)this->param) diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFi.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFi.cpp similarity index 51% rename from arduino/realtek-ambz/libraries/WiFi/WiFi.cpp rename to cores/realtek-amb/arduino/libraries/WiFi/WiFi.cpp index cc9f75b..8a9514e 100644 --- a/arduino/realtek-ambz/libraries/WiFi/WiFi.cpp +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFi.cpp @@ -1,35 +1,19 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" -rtw_network_info_t wifi = {0}; -rtw_ap_info_t ap = {0}; rtw_wifi_setting_t wifi_setting; -unsigned char sta_password[65] = {0}; -unsigned char ap_password[65] = {0}; - -void reset_wifi_struct(void) { - memset(wifi.ssid.val, 0, sizeof(wifi.ssid.val)); - memset(wifi.bssid.octet, 0, ETH_ALEN); - memset(sta_password, 0, sizeof(sta_password)); - memset(ap_password, 0, sizeof(ap_password)); - wifi.ssid.len = 0; - wifi.password = NULL; - wifi.password_len = 0; - wifi.key_id = -1; - memset(ap.ssid.val, 0, sizeof(ap.ssid.val)); - ap.ssid.len = 0; - ap.password = NULL; - ap.password_len = 0; - ap.channel = 1; -} WiFiClass::WiFiClass() { - data.scanSem = xSemaphoreCreateBinary(); + data = (WiFiData *)calloc(1, sizeof(WiFiData)); + + DATA->scanSem = xSemaphoreCreateBinary(); } WiFiClass::~WiFiClass() { - vSemaphoreDelete(data.scanSem); + vSemaphoreDelete(DATA->scanSem); + free(data); + data = NULL; } WiFiAuthMode securityTypeToAuthMode(uint8_t type) { diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiAP.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFiAP.cpp similarity index 64% rename from arduino/realtek-ambz/libraries/WiFi/WiFiAP.cpp rename to cores/realtek-amb/arduino/libraries/WiFi/WiFiAP.cpp index afba60b..871d60a 100644 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiAP.cpp +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiAP.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" typedef struct { int count; @@ -14,22 +14,23 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo return WL_CONNECT_FAILED; LT_HEAP_I(); - vTaskDelay(20); - strcpy((char *)ap.ssid.val, ssid); - ap.ssid.len = strlen(ssid); - ap.channel = channel; + WiFiNetworkInfo &info = DATA->ap; + if (info.ssid != ssid) + // free network info, if not called from restoreAPConfig() + resetNetworkInfo(info); - ap.security_type = RTW_SECURITY_OPEN; - ap.password = NULL; - ap.password_len = 0; + if (info.ssid != ssid) + info.ssid = strdup(ssid); + info.ssidHidden = ssidHidden; + info.channel = channel; + info.auth = RTW_SECURITY_OPEN; if (passphrase) { - strcpy((char *)ap_password, passphrase); - ap.security_type = RTW_SECURITY_WPA2_AES_PSK; - ap.password = ap_password; - ap.password_len = strlen(passphrase); + if (info.password != passphrase) + info.password = strdup(passphrase); + info.auth = RTW_SECURITY_WPA2_AES_PSK; } dhcps_deinit(); @@ -39,26 +40,24 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo int ret; if (!ssidHidden) { ret = wifi_start_ap( - (char *)ap.ssid.val, - ap.security_type, - (char *)ap.password, - ap.ssid.len, - ap.password_len, - ap.channel + info.ssid, + (rtw_security_t)info.auth, + info.password, + strlen(info.ssid), + strlen(info.password), + info.channel ); } else { ret = wifi_start_ap_with_hidden_ssid( - (char *)ap.ssid.val, - ap.security_type, - (char *)ap.password, - ap.ssid.len, - ap.password_len, - ap.channel + info.ssid, + (rtw_security_t)info.auth, + info.password, + strlen(info.ssid), + strlen(info.password), + info.channel ); } - wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_AP_START, -2); - if (ret < 0) { LT_EM(WIFI, "SoftAP failed; ret=%d", ret); return false; @@ -72,7 +71,7 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo while (1) { if (wext_get_ssid(ifname, essid) > 0) { - if (strcmp((const char *)essid, (const char *)ap.ssid.val) == 0) + if (strcmp((const char *)essid, info.ssid) == 0) break; } @@ -83,27 +82,28 @@ bool WiFiClass::softAP(const char *ssid, const char *passphrase, int channel, bo timeout--; } + wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_AP_START, -2); + dhcps_init(ifs); + dns_server_deinit(); return true; } bool WiFiClass::softAPConfig(IPAddress localIP, IPAddress gateway, IPAddress subnet) { if (!enableAP(true)) return false; - struct netif *ifs = NETIF_RTW_AP; + WiFiNetworkInfo &info = DATA->ap; + struct netif *ifs = NETIF_RTW_AP; struct ip_addr ipaddr, netmask, gw; - ipaddr.addr = localIP; - netmask.addr = subnet; - gw.addr = gateway; + ipaddr.addr = info.localIP = localIP; + netmask.addr = info.subnet = subnet; + gw.addr = info.gateway = gateway; netif_set_addr(ifs, &ipaddr, &netmask, &gw); return true; } bool WiFiClass::softAPdisconnect(bool wifiOff) { - // TODO implement wifi_restart_ap - if (wifiOff) - return enableAP(false); - return true; + return enableAP(false); } uint8_t WiFiClass::softAPgetStationNum() { @@ -115,11 +115,11 @@ uint8_t WiFiClass::softAPgetStationNum() { } IPAddress WiFiClass::softAPIP() { - return LwIP_GetIP(NETIF_RTW_AP); + return netif_ip_addr4(NETIF_RTW_AP)->addr; } IPAddress WiFiClass::softAPSubnetMask() { - return LwIP_GetMASK(NETIF_RTW_AP); + return netif_ip_netmask4(NETIF_RTW_AP)->addr; } const char *WiFiClass::softAPgetHostname() { @@ -132,19 +132,17 @@ bool WiFiClass::softAPsetHostname(const char *hostname) { } uint8_t *WiFiClass::softAPmacAddress(uint8_t *mac) { - uint8_t *macLocal = LwIP_GetMAC(NETIF_RTW_AP); - memcpy(mac, macLocal, ETH_ALEN); - free(macLocal); + memcpy(mac, NETIF_RTW_AP->hwaddr, ETH_ALEN); return mac; } String WiFiClass::softAPmacAddress(void) { uint8_t mac[ETH_ALEN]; - macAddress(mac); + softAPmacAddress(mac); return macToString(mac); } const String WiFiClass::softAPSSID(void) { - wifi_get_setting(NETNAME_AP, &wifi_setting); + wext_get_ssid(NETNAME_AP, wifi_setting.ssid); return (char *)wifi_setting.ssid; } diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiEvents.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFiEvents.cpp similarity index 99% rename from arduino/realtek-ambz/libraries/WiFi/WiFiEvents.cpp rename to cores/realtek-amb/arduino/libraries/WiFi/WiFiEvents.cpp index 5d6e1c6..b889a9a 100644 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiEvents.cpp +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiEvents.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-05-16. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" #include @@ -179,7 +179,7 @@ void handleRtwEvent(uint16_t event, char *data, int len, int flags) { if (len != 124) return; eventId = ARDUINO_EVENT_WIFI_AP_STACONNECTED; - memcpy(eventInfo.wifi_ap_staconnected.mac, (const char *)data[10], 6); + memcpy(eventInfo.wifi_ap_staconnected.mac, (const char *)data + 10, 6); break; case WIFI_EVENT_STA_DISASSOC: diff --git a/cores/realtek-amb/arduino/libraries/WiFi/WiFiGeneric.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFiGeneric.cpp new file mode 100644 index 0000000..4c6a7f2 --- /dev/null +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiGeneric.cpp @@ -0,0 +1,233 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ + +#include "WiFiPrivate.h" + +int32_t WiFiClass::channel() { + int channel = 0; + wifi_get_channel(&channel); + return channel; +} + +bool WiFiClass::modePriv(WiFiMode mode, WiFiModeAction sta, WiFiModeAction ap) { + __wrap_rtl_printf_disable(); + __wrap_DiagPrintf_disable(); + startWifiTask(); + + if (!DATA->initialized) { + // initialize wifi first + LT_IM(WIFI, "Initializing LwIP"); + LwIP_Init(); + DATA->initialized = true; + } + LT_HEAP_I(); + WiFiMode currentMode = getMode(); + WiFiNetworkInfo &staInfo = DATA->sta; + WiFiNetworkInfo &apInfo = DATA->ap; + bool reenableSTA = false; + bool reenableAP = false; + + if (mode == WIFI_MODE_APSTA) { + if (currentMode == WIFI_MODE_STA) { + // adding AP mode doesn't seem to work fine: + // - STA -> AP+STA + LT_DM(WIFI, "STA was enabled: %s", staInfo.ssid); + reenableSTA = true; + } + if (currentMode == WIFI_MODE_AP) { + // restart AP mode later, as wifi has to be stopped first: + // - AP -> AP+STA + LT_DM(WIFI, "AP was enabled: %s", apInfo.ssid); + reenableAP = true; + } + } + + if (reenableSTA || reenableAP || mode == WIFI_MODE_NULL || currentMode == WIFI_MODE_AP || + currentMode && mode == WIFI_MODE_AP) { + // must stop wifi first: + // - STA -> NULL + // - STA -> AP + // - STA -> AP+STA + // - AP -> NULL + // - AP -> STA + // - AP -> AP+STA + // - AP+STA -> NULL + // - AP+STA -> AP + LT_DM(WIFI, "Stopping WiFi to change mode"); + if (wifi_off() != RTW_SUCCESS) { + LT_EM(WIFI, "Error while changing mode(%u)", mode); + goto error; + } + rltk_wlan_deinit_fastly(); + rltk_wlan_rf_off(); + init_event_callback_list(); + vTaskDelay(20); + currentMode = getMode(); + } + + if (currentMode == WIFI_MODE_NULL && mode != WIFI_MODE_NULL) { + // wifi is not running, enable it the usual way: + // - NULL -> STA + // - NULL -> AP + // - NULL -> AP+STA + if (wifi_on((rtw_mode_t)mode) != RTW_SUCCESS) { + LT_EM(WIFI, "Error while changing mode(%u)", mode); + goto error; + } + } else { + // just enable/disable wlan1: + // - STA -> AP+STA - unused (wifi reset required) + // - AP+STA -> STA + wifi_mode = mode; + /* if (ap == WLMODE_ENABLE) { + LT_DM(WIFI, "Mode: %s ENABLE", WLAN1_NAME); + rltk_wlan_init(WLAN1_IDX, RTW_MODE_AP); + rltk_wlan_start(WLAN1_IDX); + uint32_t timeout = 20; + while (1) { + if (rltk_wlan_running(WLAN1_IDX)) { + wifi_set_country_code(); + break; + } + if (timeout == 0) { + LT_EM(WIFI, "Error while changing mode(%u)", mode); + goto error; + } + vTaskDelay(1 * configTICK_RATE_HZ); + timeout--; + } + netif_set_up(WLAN1_NETIF); + netif_set_link_up(WLAN1_NETIF); + } */ + if (ap == WLMODE_DISABLE) { + LT_DM(WIFI, "Mode: %s DISABLE", WLAN1_NAME); + netif_set_link_down(WLAN1_NETIF); + netif_set_down(WLAN1_NETIF); + rltk_stop_softap(WLAN1_NAME); + rltk_wlan_init(WLAN1_IDX, RTW_MODE_NONE); + wext_set_mode(WLAN1_NAME, IW_MODE_INFRA); + } + vTaskDelay(50); + } + + if (mode & WIFI_MODE_AP) { + // indicate that the interface is an AP + // use NETNAME_AP to retrieve the actual iface name (wlan0/wlan1) + // (this is determined by STA bit being set in wifi_mode) + wext_set_mode(NETNAME_AP, IW_MODE_MASTER); + } + + if (sta == WLMODE_DISABLE) { + // mark that STA mode has been disabled manually + free(staInfo.ssid); + staInfo.ssid = NULL; + } + if (ap == WLMODE_DISABLE) { + // mark that AP mode has been disabled manually + free(apInfo.ssid); + apInfo.ssid = NULL; + } + + // force checking WiFi mode again (which will update wifi_mode) + getMode(); + + if (reenableSTA) { + // restart STA mode from previously used config (if set) + if (!restoreSTAConfig(staInfo)) + LT_EM(WIFI, "Couldn't restore STA mode: %s", staInfo.ssid); + } + if (reenableAP) { + // restart AP mode from previously used config (if set) + if (!restoreAPConfig(apInfo)) + LT_EM(WIFI, "Couldn't restore AP mode: %s", apInfo.ssid); + } + + // send STA start/stop events and AP stop event (start is handled in softAP()) + if (sta == WLMODE_ENABLE) { + wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_STA_START, -2); + } else if (sta == WLMODE_DISABLE) { + wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_STA_STOP, -2); + } + if (ap == WLMODE_DISABLE) { + wifi_indication(WIFI_EVENT_CONNECT, NULL, ARDUINO_EVENT_WIFI_AP_STOP, -2); + } + + LT_HEAP_I(); + __wrap_rtl_printf_enable(); + __wrap_DiagPrintf_enable(); + return true; + +error: + __wrap_rtl_printf_enable(); + __wrap_DiagPrintf_enable(); + return false; +} + +WiFiMode WiFiClass::getMode() { + if (!DATA->initialized) + return WIFI_MODE_NULL; + uint8_t wlan0_state = rltk_wlan_running(WLAN0_IDX); + uint8_t wlan1_state = rltk_wlan_running(WLAN1_IDX); + wifi_mode = (wifi_mode_t)wlan0_state; + + LT_DM(WIFI, "WLAN: %s=%u, %s=%u", WLAN0_NAME, wlan0_state, WLAN1_NAME, wlan1_state); + + if (wlan1_state) { + if (netif_is_up(WLAN1_NETIF)) + wifi_mode = (wifi_mode_t)(WIFI_MODE_AP | wlan0_state); + } else { + wifi_mode = (wifi_mode_t)(wlan0_state); + int mode = 0; + // check wlan0 mode to determine if it's an AP + if (wlan0_state) + wext_get_mode(WLAN0_NAME, &mode); + if (mode == IW_MODE_MASTER) + wifi_mode = (wifi_mode_t)(wifi_mode << 1); + } + + return wifi_mode; +} + +WiFiStatus WiFiClass::status() { + if (rltk_wlan_is_connected_to_ap() == 0) { + return WL_CONNECTED; + } else { + return WL_DISCONNECTED; + } +} + +bool WiFiClass::setSleep(bool enable) { + LT_DM(WIFI, "WiFi sleep mode %u", enable); + if (enable) { + if (wifi_enable_powersave() != RTW_SUCCESS) + return false; + } else { + if (wifi_disable_powersave() != RTW_SUCCESS) + return false; + } + DATA->sleep = enable; + return true; +} + +bool WiFiClass::getSleep() { + return DATA->sleep; +} + +bool WiFiClass::setTxPower(int power) { + return false; // wifi_set_txpower(power) == RTW_SUCCESS; +} + +int WiFiClass::getTxPower() { + return 0; + int power = 0; + wifi_get_txpower(&power); + return power; +} + +IPAddress WiFiClass::hostByName(const char *hostname) { + ip_addr_t ip; + int ret = netconn_gethostbyname(hostname, &ip); + if (ret == ERR_OK) { + return ip.addr; + } + return IPAddress(); +} diff --git a/cores/realtek-amb/arduino/libraries/WiFi/WiFiPrivate.h b/cores/realtek-amb/arduino/libraries/WiFi/WiFiPrivate.h new file mode 100644 index 0000000..aa3079d --- /dev/null +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiPrivate.h @@ -0,0 +1,67 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ + +#pragma once + +#include +#include + +extern "C" { + +// copy defines from PIO builder (for IDE to understand) +#define LWIP_TIMEVAL_PRIVATE 0 +#define LWIP_NETIF_HOSTNAME 1 +#define LWIP_SO_RCVBUF 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern struct netif xnetif[NET_IF_NUM]; + +// dhcps.c +extern void dns_server_init(struct netif *pnetif); +extern void dns_server_deinit(void); + +// wifi_util.c +extern void rltk_stop_softap(const char *ifname); +extern void rltk_suspend_softap(const char *ifname); +extern void rltk_suspend_softap_beacon(const char *ifname); + +} // extern "C" + +// WiFi.cpp +extern rtw_wifi_setting_t wifi_setting; +extern wifi_mode_t wifi_mode; +extern WiFiAuthMode securityTypeToAuthMode(uint8_t type); +// WiFiEvents.cpp +extern void startWifiTask(); +extern void handleRtwEvent(uint16_t event, char *data, int len, int flags); + +#define WLAN0_NETIF &xnetif[RTW_STA_INTERFACE] +#define WLAN1_NETIF &xnetif[RTW_AP_INTERFACE] + +#define NETIF_RTW_STA WLAN0_NETIF +#define NETIF_RTW_AP (wifi_mode & WIFI_MODE_STA ? WLAN1_NETIF : WLAN0_NETIF) + +#define NETNAME_STA WLAN0_NAME +#define NETNAME_AP (wifi_mode & WIFI_MODE_STA ? WLAN1_NAME : WLAN0_NAME) + +typedef struct { + bool initialized; + bool sleep; + SemaphoreHandle_t scanSem; + WiFiNetworkInfo sta; + WiFiNetworkInfo ap; +} WiFiData; + +#define DATA ((WiFiData *)data) +#define pDATA ((WiFiData *)pWiFi->data) +#define cDATA ((WiFiData *)cls->data) diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiSTA.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFiSTA.cpp similarity index 67% rename from arduino/realtek-ambz/libraries/WiFi/WiFiSTA.cpp rename to cores/realtek-amb/arduino/libraries/WiFi/WiFiSTA.cpp index 02a321a..7067a8f 100644 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiSTA.cpp +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiSTA.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" WiFiStatus WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, const uint8_t *bssid, bool connect) { @@ -11,20 +11,20 @@ WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, cons LT_HEAP_I(); - memset(wifi.bssid.octet, 0, ETH_ALEN); - strcpy((char *)wifi.ssid.val, ssid); - wifi.ssid.len = strlen(ssid); + WiFiNetworkInfo &info = DATA->sta; + if (info.ssid != ssid) + // free network info, if not called from restoreSTAConfig() + resetNetworkInfo(info); - wifi.security_type = RTW_SECURITY_OPEN; - wifi.password = NULL; - wifi.password_len = 0; - wifi.key_id = 0; + if (info.ssid != ssid) + info.ssid = strdup(ssid); + info.channel = channel; + info.auth = RTW_SECURITY_OPEN; if (passphrase) { - strcpy((char *)sta_password, passphrase); - wifi.security_type = RTW_SECURITY_WPA2_AES_PSK; - wifi.password = sta_password; - wifi.password_len = strlen(passphrase); + if (info.password != passphrase) + info.password = strdup(passphrase); + info.auth = RTW_SECURITY_WPA2_AES_PSK; } if (reconnect(bssid)) @@ -36,24 +36,26 @@ WiFiClass::begin(const char *ssid, const char *passphrase, int32_t channel, cons bool WiFiClass::config(IPAddress localIP, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) { if (!enableSTA(true)) return false; + WiFiNetworkInfo &info = DATA->sta; struct ip_addr d1, d2; - d1.addr = dns1; - d2.addr = dns2; - if (dns1[0]) + d1.addr = info.dns1 = dns1; + d2.addr = info.dns2 = dns2; + if (d1.addr) dns_setserver(0, &d1); - if (dns2[0]) + if (d2.addr) dns_setserver(0, &d2); if (!localIP[0]) { + info.localIP = 0; LwIP_DHCP(0, DHCP_START); return true; } struct netif *ifs = NETIF_RTW_STA; struct ip_addr ipaddr, netmask, gw; - ipaddr.addr = localIP; - netmask.addr = subnet; - gw.addr = gateway; + ipaddr.addr = info.localIP = localIP; + netmask.addr = info.subnet = subnet; + gw.addr = info.gateway = gateway; netif_set_addr(ifs, &ipaddr, &netmask, &gw); LwIP_DHCP(0, DHCP_STOP); return true; @@ -62,31 +64,39 @@ bool WiFiClass::config(IPAddress localIP, IPAddress gateway, IPAddress subnet, I bool WiFiClass::reconnect(const uint8_t *bssid) { int ret; uint8_t dhcpRet; + WiFiNetworkInfo &info = DATA->sta; - LT_IM(WIFI, "Connecting to %s", wifi.ssid.val); + LT_IM(WIFI, "Connecting to %s (bssid=%p)", info.ssid, bssid); __wrap_rtl_printf_disable(); __wrap_DiagPrintf_disable(); + wext_set_ssid(WLAN0_NAME, (uint8_t *)"-", 1); + if (!bssid) { ret = wifi_connect( - (char *)wifi.ssid.val, - wifi.security_type, - (char *)wifi.password, - wifi.ssid.len, - wifi.password_len, - wifi.key_id, + info.ssid, + (rtw_security_t)info.auth, + info.password, + strlen(info.ssid), + strlen(info.password), + -1, NULL ); } else { + if (info.bssid != bssid) { + free(info.bssid); + info.bssid = (uint8_t *)malloc(ETH_ALEN); + memcpy(info.bssid, bssid, ETH_ALEN); + } ret = wifi_connect_bssid( (unsigned char *)bssid, - (char *)wifi.ssid.val, - wifi.security_type, - (char *)wifi.password, + info.ssid, + (rtw_security_t)info.auth, + info.password, ETH_ALEN, - wifi.ssid.len, - wifi.password_len, - wifi.key_id, + strlen(info.ssid), + strlen(info.password), + -1, NULL ); } @@ -95,7 +105,7 @@ bool WiFiClass::reconnect(const uint8_t *bssid) { dhcpRet = LwIP_DHCP(0, DHCP_START); if (dhcpRet == DHCP_ADDRESS_ASSIGNED) { LT_HEAP_I(); - EventInfo *eventInfo = (EventInfo *)zalloc(sizeof(EventInfo)); + EventInfo *eventInfo = (EventInfo *)calloc(1, sizeof(EventInfo)); eventInfo->got_ip.if_index = 0; eventInfo->got_ip.esp_netif = NULL; eventInfo->got_ip.ip_info.ip.addr = localIP(); @@ -122,7 +132,9 @@ error: } bool WiFiClass::disconnect(bool wifiOff) { - int ret = wifi_disconnect(); + free(DATA->sta.ssid); + DATA->sta.ssid = NULL; + int ret = wifi_disconnect(); if (wifiOff) enableSTA(false); return ret == RTW_SUCCESS; @@ -141,33 +153,31 @@ bool WiFiClass::getAutoReconnect() { IPAddress WiFiClass::localIP() { if (!wifi_mode) return IPAddress(); - return LwIP_GetIP(NETIF_RTW_STA); + return netif_ip_addr4(NETIF_RTW_STA)->addr; } uint8_t *WiFiClass::macAddress(uint8_t *mac) { - if (getMode() == WIFI_MODE_NULL) { + if ((getMode() & WIFI_MODE_STA) == 0) { uint8_t *efuse = (uint8_t *)malloc(512); EFUSE_LogicalMap_Read(efuse); memcpy(mac, efuse + 0x11A, ETH_ALEN); free(efuse); return mac; } - memcpy(mac, LwIP_GetMAC(NETIF_RTW_STA), ETH_ALEN); + memcpy(mac, NETIF_RTW_STA.hwaddr, ETH_ALEN); return mac; } IPAddress WiFiClass::subnetMask() { - return LwIP_GetMASK(NETIF_RTW_STA); + return netif_ip_netmask4(NETIF_RTW_STA)->addr; } IPAddress WiFiClass::gatewayIP() { - return LwIP_GetGW(NETIF_RTW_STA); + return netif_ip_gw4(NETIF_RTW_STA)->addr; } IPAddress WiFiClass::dnsIP(uint8_t dns_no) { - struct ip_addr dns; - LwIP_GetDNS(&dns); - return dns.addr; + return dns_getserver(0)->addr; } IPAddress WiFiClass::broadcastIP() { @@ -195,14 +205,17 @@ const String WiFiClass::SSID() { } const String WiFiClass::psk() { - if (!isConnected() || !wifi.password) + if (!isConnected() || !DATA->sta.password) return ""; - return (char *)wifi.password; + return DATA->sta.password; } uint8_t *WiFiClass::BSSID() { - wext_get_bssid(NETNAME_STA, wifi.bssid.octet); - return wifi.bssid.octet; + WiFiNetworkInfo &info = DATA->sta; + if (!info.bssid) + info.bssid = (uint8_t *)malloc(ETH_ALEN); + wext_get_bssid(NETNAME_STA, info.bssid); + return info.bssid; } int8_t WiFiClass::RSSI() { diff --git a/arduino/realtek-ambz/libraries/WiFi/WiFiScan.cpp b/cores/realtek-amb/arduino/libraries/WiFi/WiFiScan.cpp similarity index 84% rename from arduino/realtek-ambz/libraries/WiFi/WiFiScan.cpp rename to cores/realtek-amb/arduino/libraries/WiFi/WiFiScan.cpp index 7a0e57b..75731ef 100644 --- a/arduino/realtek-ambz/libraries/WiFi/WiFiScan.cpp +++ b/cores/realtek-amb/arduino/libraries/WiFi/WiFiScan.cpp @@ -1,6 +1,6 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-04-25. */ -#include "WiFiPriv.h" +#include "WiFiPrivate.h" static rtw_result_t scanHandler(rtw_scan_handler_result_t *result) { WiFiClass *cls = (WiFiClass *)result->user_data; @@ -10,7 +10,7 @@ static rtw_result_t scanHandler(rtw_scan_handler_result_t *result) { if (result->scan_complete == RTW_TRUE) { scan->running = false; - xSemaphoreGive(cls->data.scanSem); + xSemaphoreGive(cDATA->scanSem); return RTW_SUCCESS; } @@ -34,7 +34,7 @@ static rtw_result_t scanHandler(rtw_scan_handler_result_t *result) { int16_t WiFiClass::scanNetworks(bool async, bool showHidden, bool passive, uint32_t maxMsPerChannel, uint8_t channel) { if (scan && scan->running) return WIFI_SCAN_RUNNING; - if (wifi_mode == WIFI_MODE_NULL) + if (getMode() == WIFI_MODE_NULL) enableSTA(true); scanDelete(); scanInit(); @@ -48,8 +48,8 @@ int16_t WiFiClass::scanNetworks(bool async, bool showHidden, bool passive, uint3 if (!async) { LT_IM(WIFI, "Waiting for results"); - xSemaphoreTake(data.scanSem, 1); // reset the semaphore quickly - xSemaphoreTake(data.scanSem, pdMS_TO_TICKS(maxMsPerChannel * 20)); + xSemaphoreTake(DATA->scanSem, 1); // reset the semaphore quickly + xSemaphoreTake(DATA->scanSem, pdMS_TO_TICKS(maxMsPerChannel * 20)); return scan->count; } return WIFI_SCAN_RUNNING; diff --git a/arduino/realtek-ambz/libraries/Wire/Wire.cpp b/cores/realtek-amb/arduino/libraries/Wire/Wire.cpp similarity index 95% rename from arduino/realtek-ambz/libraries/Wire/Wire.cpp rename to cores/realtek-amb/arduino/libraries/Wire/Wire.cpp index 0b7c94c..aa93e65 100644 --- a/arduino/realtek-ambz/libraries/Wire/Wire.cpp +++ b/cores/realtek-amb/arduino/libraries/Wire/Wire.cpp @@ -2,10 +2,9 @@ #include "Wire.h" -#include +#include extern "C" { -#include extern int i2c_write_timeout(i2c_t *obj, int address, char *data, int length, int stop, int timeout_ms); } @@ -46,8 +45,8 @@ bool TwoWire::setPins(int8_t sda, int8_t scl) { // set private pins _sda = sda; _scl = scl; - sda = pinTable[sda].gpio; - scl = pinTable[scl].gpio; + sda = pinInfo(sda)->gpio; + scl = pinInfo(scl)->gpio; // check if pins are valid if ((sda == PA_4 || sda == PA_19 || sda == PA_30) && (scl == PA_1 || scl == PA_22 || scl == PA_29)) { @@ -82,7 +81,7 @@ bool TwoWire::begin(int8_t sda, int8_t scl, uint32_t frequency) { frequency = WIRE_DEFAULT_FREQ; _i2c = new i2c_t; - i2c_init(_i2c, (PinName)pinTable[_sda].gpio, (PinName)pinTable[_scl].gpio); + i2c_init(_i2c, (PinName)pinInfo(_sda)->gpio, (PinName)pinInfo(_scl)->gpio); i2c_frequency(_i2c, frequency); _freq = frequency; return true; @@ -104,6 +103,7 @@ bool TwoWire::end() { i2c_reset(_i2c); delete _i2c; _i2c = NULL; + return true; } bool TwoWire::setClock(uint32_t freq) { @@ -111,6 +111,7 @@ bool TwoWire::setClock(uint32_t freq) { i2c_frequency(_i2c, freq); } _freq = freq; + return true; } void TwoWire::beginTransmission(uint8_t address) { diff --git a/arduino/realtek-ambz/libraries/Wire/Wire.h b/cores/realtek-amb/arduino/libraries/Wire/Wire.h similarity index 81% rename from arduino/realtek-ambz/libraries/Wire/Wire.h rename to cores/realtek-amb/arduino/libraries/Wire/Wire.h index 8bcafeb..bc48214 100644 --- a/arduino/realtek-ambz/libraries/Wire/Wire.h +++ b/cores/realtek-amb/arduino/libraries/Wire/Wire.h @@ -2,16 +2,9 @@ #pragma once +#include +#include #include -#include - -#ifdef __cplusplus -extern "C" { -#endif -// #include -#ifdef __cplusplus -} -#endif #if !defined(PIN_WIRE0_SDA) && defined(PIN_WIRE1_SDA) #define Wire1 Wire @@ -25,7 +18,7 @@ typedef struct i2c_s i2c_t; using arduino::RingBuffer; -class TwoWire : public ITwoWire { +class TwoWire : public HardwareI2C { private: i2c_t *_i2c = NULL; uint8_t _idx = 0; @@ -60,10 +53,10 @@ class TwoWire : public ITwoWire { int peek(); void flush(); - using ITwoWire::begin; - using ITwoWire::endTransmission; - using ITwoWire::requestFrom; - using ITwoWire::write; + using HardwareI2C::begin; + using HardwareI2C::endTransmission; + using HardwareI2C::requestFrom; + using HardwareI2C::write; using Print::write; }; diff --git a/cores/realtek-amb/arduino/src/ArduinoFamily.h b/cores/realtek-amb/arduino/src/ArduinoFamily.h new file mode 100644 index 0000000..a59c171 --- /dev/null +++ b/cores/realtek-amb/arduino/src/ArduinoFamily.h @@ -0,0 +1,27 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +// Provide GPIO names to variant.cpp files +#define LT_VARIANT_INCLUDE "sdk_private.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +extern uint32_t SystemCoreClock; +extern void vPortClearInterruptMask(uint32_t ulNewMaskValue); +extern uint32_t ulPortSetInterruptMask(void); + +#define clockCyclesPerMicrosecond() (SystemCoreClock / 1000000L) +#define clockCyclesToMicroseconds(a) (a * 1000L / (SystemCoreClock / 1000L)) +#define microsecondsToClockCycles(a) (a * (SystemCoreClock / 1000000L)) + +#define interrupts() vPortClearInterruptMask(0) +#define noInterrupts() ulPortSetInterruptMask() + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/arduino/realtek-ambz/cores/arduino/Tone.cpp b/cores/realtek-amb/arduino/src/Tone.cpp similarity index 100% rename from arduino/realtek-ambz/cores/arduino/Tone.cpp rename to cores/realtek-amb/arduino/src/Tone.cpp diff --git a/cores/realtek-amb/arduino/src/lt_api.c b/cores/realtek-amb/arduino/src/lt_api.c new file mode 100644 index 0000000..bfc1f49 --- /dev/null +++ b/cores/realtek-amb/arduino/src/lt_api.c @@ -0,0 +1,8 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-10. */ + +#include +#include + +uint32_t lt_cpu_get_cycle_count() { + return microsecondsToClockCycles(micros()); +} diff --git a/cores/realtek-amb/arduino/src/lt_defs.h b/cores/realtek-amb/arduino/src/lt_defs.h new file mode 100644 index 0000000..2083962 --- /dev/null +++ b/cores/realtek-amb/arduino/src/lt_defs.h @@ -0,0 +1,16 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_ARD_HAS_WIFI 1 +#define LT_ARD_HAS_SOFTSERIAL 1 +#define LT_ARD_HAS_SERIAL 1 + +#define LT_ARD_MD5_POLARSSL 1 + +#define ARDUINO_AMEBA + +// the SDK declares bool if not defined before +// which conflicts with C++ built-in bool +// so it's either -fpermissive or this: +#define bool bool diff --git a/arduino/realtek-ambz/cores/arduino/main.cpp b/cores/realtek-amb/arduino/src/main.cpp similarity index 61% rename from arduino/realtek-ambz/cores/arduino/main.cpp rename to cores/realtek-amb/arduino/src/main.cpp index 2eeaaed..9587dc7 100644 --- a/arduino/realtek-ambz/cores/arduino/main.cpp +++ b/cores/realtek-amb/arduino/src/main.cpp @@ -1,26 +1,21 @@ /* Copyright (c) Kuba SzczodrzyƄski 2022-06-19. */ #include +#include extern "C" { #include - -extern uint32_t GlobalDebugEnable; -extern uint16_t GlobalDebugLevel; -extern uint8_t GlobalPrivateLog; -extern uint8_t lt_uart_port; - -} // extern "C" +#include osThreadId main_tid = 0; -void initArduino() { - // make the SDK less verbose by default - GlobalDebugEnable = 0; - GlobalPrivateLog = 0; - lt_uart_port = LT_UART_DEFAULT_PORT; +#if LT_AUTO_DOWNLOAD_REBOOT && defined(PIN_SERIAL2_RX) && defined(PIN_SERIAL2_TX) +void lt_init_arduino() { + // initialize auto-download-reboot parser + Serial2.begin(115200); } +#endif bool startMainTask() { osThreadDef(mainTask, osPriorityRealtime, 1, 4096 * 4); @@ -35,3 +30,5 @@ void wait_for_debug() { } delay(1000); } + +} // extern "C" diff --git a/arduino/realtek-ambz/cores/arduino/wiring.c b/cores/realtek-amb/arduino/src/wiring.c similarity index 99% rename from arduino/realtek-ambz/cores/arduino/wiring.c rename to cores/realtek-amb/arduino/src/wiring.c index 72957c3..0cc3839 100644 --- a/arduino/realtek-ambz/cores/arduino/wiring.c +++ b/cores/realtek-amb/arduino/src/wiring.c @@ -17,6 +17,7 @@ */ #include + #include #ifndef portNVIC_SYSTICK_CURRENT_VALUE_REG @@ -88,6 +89,7 @@ unsigned long micros(void) { } void yield(void) { + runPeriodicTasks(); vTaskDelay(1); taskYIELD(); } diff --git a/arduino/realtek-ambz/cores/arduino/wiring_analog.c b/cores/realtek-amb/arduino/src/wiring_analog.c similarity index 63% rename from arduino/realtek-ambz/cores/arduino/wiring_analog.c rename to cores/realtek-amb/arduino/src/wiring_analog.c index 01b089a..05d0796 100644 --- a/arduino/realtek-ambz/cores/arduino/wiring_analog.c +++ b/cores/realtek-amb/arduino/src/wiring_analog.c @@ -17,17 +17,14 @@ */ #include -#include -#include -#include -#include +#include /* ADC */ -analogin_t adc1; -analogin_t adc2; -analogin_t adc3; +static analogin_t adc1; +static analogin_t adc2; +static analogin_t adc3; -bool g_adc_enabled[] = {false, false, false}; +static bool g_adc_enabled[] = {false, false, false}; // from realtek_amebaz_va0_example/example_sources/adc_vbat/src/main.c #define AD2MV(ad, offset, gain) (((ad >> 4) - offset) * 1000 / gain) @@ -109,53 +106,3 @@ void analogWrite(pin_size_t pinNumber, int value) { } } } - -typedef struct _tone_argument { - uint32_t ulPin; - uint32_t timer_id; -}; - -void _tone_timer_handler(const void *argument) { - struct _tone_argument *arg = (struct _tone_argument *)argument; - - uint32_t ulPin = (uint32_t)argument; - - noTone(arg->ulPin); - - os_timer_delete(arg->timer_id); - - free((struct _tone_argument *)arg); -} - -void _tone(uint32_t ulPin, unsigned int frequency, unsigned long duration) { - pwmout_t *obj; - - if ((pinTable[ulPin].supported & PIN_PWM) != PIN_PWM) { - return; - } - - if (pinTable[ulPin].enabled != PIN_PWM) { - if ((pinTable[ulPin].enabled == PIN_GPIO) || (pinTable[ulPin].enabled == PIN_IRQ)) { - pinRemoveMode(ulPin); - } - gpio_pin_struct[ulPin] = malloc(sizeof(pwmout_t)); - pwmout_t *obj = (pwmout_t *)gpio_pin_struct[ulPin]; - pwmout_init(obj, pinTable[ulPin].gpio); - pwmout_period(obj, 1.0 / frequency); - pwmout_pulsewidth(obj, 1.0 / (frequency * 2)); - pinTable[ulPin].enabled = PIN_PWM; - - } else { - // There is already a PWM configured - pwmout_t *obj = (pwmout_t *)gpio_pin_struct[ulPin]; - pwmout_period(obj, 1.0 / frequency); - pwmout_pulsewidth(obj, 1.0 / (frequency * 2)); - } - - if (duration > 0) { - struct _tone_argument *arg = (struct _tone_argument *)malloc(sizeof(struct _tone_argument)); - arg->ulPin = ulPin; - arg->timer_id = os_timer_create(_tone_timer_handler, 0, arg); - os_timer_start(arg->timer_id, duration); - } -} diff --git a/arduino/realtek-ambz/cores/arduino/wiring_digital.c b/cores/realtek-amb/arduino/src/wiring_digital.c similarity index 76% rename from arduino/realtek-ambz/cores/arduino/wiring_digital.c rename to cores/realtek-amb/arduino/src/wiring_digital.c index fbf0ebb..0c8cb32 100644 --- a/arduino/realtek-ambz/cores/arduino/wiring_digital.c +++ b/cores/realtek-amb/arduino/src/wiring_digital.c @@ -1,8 +1,5 @@ #include -#include -#include -#include -#include +#include extern void *gpio_pin_struct[PINS_COUNT]; @@ -16,7 +13,7 @@ void pinRemoveMode(pin_size_t pinNumber) { } if (pinEnabled(pin, PIN_GPIO)) { gpio_t *obj = (gpio_t *)gpio_pin_struct[pinNumber]; - gpio_deinit(obj, pin->gpio); + gpio_deinit(obj); free(obj); } if (pinEnabled(pin, PIN_IRQ)) { @@ -28,7 +25,7 @@ void pinRemoveMode(pin_size_t pinNumber) { pin->enabled = PIN_NONE; } -void pinMode(pin_size_t pinNumber, PinModeArduino pinMode) { +void pinMode(pin_size_t pinNumber, PinMode pinMode) { PinInfo *pin = pinInfo(pinNumber); if (!pin) return; @@ -110,28 +107,10 @@ void digitalWrite(pin_size_t pinNumber, PinStatus status) { PinStatus digitalRead(pin_size_t pinNumber) { PinInfo *pin = pinInfo(pinNumber); if (!pin) - return; + return LOW; if (pin->enabled != PIN_GPIO) - return; + return LOW; gpio_t *gpio = (gpio_t *)gpio_pin_struct[pinNumber]; return gpio_read(gpio); } - -/**************************** Extend API by RTK ***********************************/ - -uint32_t digitalPinToPort(uint32_t pinNumber) { - if (pinInvalid(pinNumber)) - return 0xFFFFFFFF; - - uint32_t pin_name = HAL_GPIO_GetPinName(pinTable[pinNumber].gpio); - return HAL_GPIO_GET_PORT_BY_NAME(pin_name); -} - -uint32_t digitalPinToBitMask(uint32_t pinNumber) { - if (pinInvalid(pinNumber)) - return 0xFFFFFFFF; - - uint32_t pin_name = HAL_GPIO_GetPinName(pinTable[pinNumber].gpio); - return 1 << (HAL_GPIO_GET_PIN_BY_NAME(pin_name)); -} diff --git a/arduino/realtek-ambz/cores/arduino/WInterrupts.c b/cores/realtek-amb/arduino/src/wiring_irq.c similarity index 58% rename from arduino/realtek-ambz/cores/arduino/WInterrupts.c rename to cores/realtek-amb/arduino/src/wiring_irq.c index 90a6cf4..4fd7cd5 100644 --- a/arduino/realtek-ambz/cores/arduino/WInterrupts.c +++ b/cores/realtek-amb/arduino/src/wiring_irq.c @@ -1,16 +1,14 @@ #include -#include -#include -#include +#include extern void *gpio_pin_struct[PINS_COUNT]; static void *gpio_irq_handler_list[PINS_COUNT] = {NULL}; static void *gpio_irq_handler_args[PINS_COUNT] = {NULL}; -extern bool pinInvalid(pin_size_t pinNumber); extern void pinRemoveMode(pin_size_t pinNumber); static void gpioIrqHandler(uint32_t id, gpio_irq_event event) { + // id is pin index if (gpio_irq_handler_list[id] != NULL) { if (gpio_irq_handler_args[id] == NULL) ((voidFuncPtr)gpio_irq_handler_list[id])(); @@ -20,37 +18,39 @@ static void gpioIrqHandler(uint32_t id, gpio_irq_event event) { } void attachInterrupt(pin_size_t interruptNumber, voidFuncPtr callback, PinStatus mode) { - attachInterruptParam(interruptNumber, callback, mode, NULL); + attachInterruptParam(interruptNumber, (voidFuncPtrParam)callback, mode, NULL); } void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, PinStatus mode, void *param) { - if (pinInvalid(interruptNumber)) + PinInfo *pin = pinInfo(interruptNumber); + if (pin == NULL) return; + uint32_t index = pinIndex(pin); - gpio_irq_handler_list[interruptNumber] = callback; - gpio_irq_handler_args[interruptNumber] = param; + gpio_irq_handler_list[index] = callback; + gpio_irq_handler_args[index] = param; - if (pinTable[interruptNumber].enabled == PIN_IRQ && pinTable[interruptNumber].mode == mode) + if (pin->enabled == PIN_IRQ && pin->mode == mode) // Nothing changes in pin mode return; - if (pinTable[interruptNumber].enabled != PIN_IRQ) + if (pin->enabled != PIN_IRQ) // pin mode changes; deinit gpio and free memory pinRemoveMode(interruptNumber); gpio_irq_t *gpio; - if (pinTable[interruptNumber].enabled == PIN_NONE) { + if (pin->enabled == PIN_NONE) { // allocate memory if pin not used before - gpio = malloc(sizeof(gpio_irq_t)); - gpio_pin_struct[interruptNumber] = gpio; - gpio_irq_init(gpio, pinTable[interruptNumber].gpio, gpioIrqHandler, interruptNumber); - pinTable[interruptNumber].enabled = PIN_IRQ; + gpio = malloc(sizeof(gpio_irq_t)); + gpio_pin_struct[index] = gpio; + gpio_irq_init(gpio, pin->gpio, gpioIrqHandler, index); + pin->enabled = PIN_IRQ; } else { // pin already used as irq - gpio = (gpio_irq_t *)gpio_pin_struct[interruptNumber]; + gpio = (gpio_irq_t *)gpio_pin_struct[index]; } - pinTable[interruptNumber].mode = mode; + pin->mode = mode; gpio_irq_event event; @@ -76,11 +76,13 @@ void attachInterruptParam(pin_size_t interruptNumber, voidFuncPtrParam callback, } void detachInterrupt(pin_size_t interruptNumber) { - if (pinInvalid(interruptNumber)) + PinInfo *pin = pinInfo(interruptNumber); + if (pin == NULL) return; + uint32_t index = pinIndex(pin); - if (pinTable[interruptNumber].enabled == PIN_IRQ) { + if (pin->enabled == PIN_IRQ) { pinRemoveMode(interruptNumber); } - gpio_irq_handler_list[interruptNumber] = NULL; + gpio_irq_handler_list[index] = NULL; } diff --git a/arduino/realtek-ambz/cores/arduino/wiring_pulse.c b/cores/realtek-amb/arduino/src/wiring_pulse.c similarity index 86% rename from arduino/realtek-ambz/cores/arduino/wiring_pulse.c rename to cores/realtek-amb/arduino/src/wiring_pulse.c index 7038f94..85161e6 100644 --- a/arduino/realtek-ambz/cores/arduino/wiring_pulse.c +++ b/cores/realtek-amb/arduino/src/wiring_pulse.c @@ -17,10 +17,7 @@ */ #include -#include -#include -#include -#include +#include extern void *gpio_pin_struct[]; @@ -28,23 +25,28 @@ extern void *gpio_pin_struct[]; * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds * to 3 minutes in length, but must be called at least a few dozen microseconds * before the start of the pulse. */ -extern unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) { +extern unsigned long pulseIn(uint8_t pinNumber, uint8_t state, unsigned long timeout) { // cache the port and bit of the pin in order to speed up the // pulse width measuring loop and achieve finer resolution. calling // digitalRead() instead yields much coarser resolution. + PinInfo *pin = pinInfo(pinNumber); + if (pin == NULL) + return; + uint32_t index = pinIndex(pin); + gpio_t *pGpio_t; uint32_t start_ticks, cur_ticks; - if (pin < 0 || pin > PINS_COUNT || (pinTable[pin].gpio == NC)) + if (pin < 0 || pin > PINS_COUNT || (pin->gpio == NC)) return 0; /* Handle */ - if (pinTable[pin].enabled != PIN_GPIO) { + if (pin->enabled != PIN_GPIO) { return 0; } - pGpio_t = (gpio_t *)gpio_pin_struct[pin]; + pGpio_t = (gpio_t *)gpio_pin_struct[index]; // wait for any previous pulse to end start_ticks = us_ticker_read(); diff --git a/platform/realtek-amb/config/build_info.h b/cores/realtek-amb/base/config/build_info.h similarity index 87% rename from platform/realtek-amb/config/build_info.h rename to cores/realtek-amb/base/config/build_info.h index bebb18f..d2ff95a 100644 --- a/platform/realtek-amb/config/build_info.h +++ b/cores/realtek-amb/base/config/build_info.h @@ -1,6 +1,6 @@ #pragma once -#define RTL_FW_COMPILE_TIME "20020/01/01-00:00:00" +#define RTL_FW_COMPILE_TIME "2020/01/01-00:00:00" #define RTL_FW_COMPILE_DATE "20200101" #define UTS_VERSION "2020/01/01-00:00:00" #define RTL8195AFW_COMPILE_TIME "2020/01/01-00:00:00" @@ -9,6 +9,7 @@ #define RTL8195AFW_COMPILE_HOST "localhost" #define RTL8195AFW_COMPILE_DOMAIN "localhost" #define RTL8195AFW_COMPILER "gcc" +#define RTL195AFW_COMPILER "gcc" #define RTL8710CFW_COMPILE_TIME "2020/01/01-00:00:00" #define RTL8710CFW_COMPILE_DATE "20200101" #define RTL8710CFW_COMPILE_BY "root" diff --git a/platform/realtek-amb/config/lwipopts.h b/cores/realtek-amb/base/config/lwipopts.h similarity index 100% rename from platform/realtek-amb/config/lwipopts.h rename to cores/realtek-amb/base/config/lwipopts.h diff --git a/cores/realtek-amb/base/config/main.h b/cores/realtek-amb/base/config/main.h new file mode 100644 index 0000000..dde552c --- /dev/null +++ b/cores/realtek-amb/base/config/main.h @@ -0,0 +1,45 @@ +#pragma once + +#include + +void wlan_network(); + +// clang-format off +#define WEP40_KEY { 0x12, 0x34, 0x56, 0x78, 0x90 } +// clang-format on + +#define CONFIG_WLAN 1 +#define SERIAL_DEBUG_RX 1 +#define STA_MODE_SSID "ap" +#define AP_MODE_SSID "wlan_ap_ssid" +#define AP_DEFAULT_CH 6 +#define WLAN0_NAME "wlan0" +#define WLAN1_NAME "wlan1" +#define WPA_PASSPHRASE "1234567890" +#define ATVER_1 1 +#define ATVER_2 2 +#define ATCMD_VER ATVER_1 +#define IP_ADDR0 192 +#define IP_ADDR1 168 +#define IP_ADDR2 1 +#define IP_ADDR3 80 +#define NETMASK_ADDR0 255 +#define NETMASK_ADDR1 255 +#define NETMASK_ADDR2 255 +#define NETMASK_ADDR3 0 +#define GW_ADDR0 192 +#define GW_ADDR1 168 +#define GW_ADDR2 1 +#define GW_ADDR3 1 +#define AP_IP_ADDR0 192 +#define AP_IP_ADDR1 168 +#define AP_IP_ADDR2 43 +#define AP_IP_ADDR3 1 +#define AP_NETMASK_ADDR0 255 +#define AP_NETMASK_ADDR1 255 +#define AP_NETMASK_ADDR2 255 +#define AP_NETMASK_ADDR3 0 +#define AP_GW_ADDR0 192 +#define AP_GW_ADDR1 168 +#define AP_GW_ADDR2 43 +#define AP_GW_ADDR3 1 diff --git a/cores/realtek-amb/base/lt_api.c b/cores/realtek-amb/base/lt_api.c new file mode 100644 index 0000000..a225a14 --- /dev/null +++ b/cores/realtek-amb/base/lt_api.c @@ -0,0 +1,219 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-02-27. */ + +#include +#include + +extern uint32_t GlobalDebugEnable; +extern uint16_t GlobalDebugLevel; +extern uint8_t GlobalPrivateLog; +extern uint8_t lt_uart_port; + +void lt_init_family() { + // make the SDK less verbose by default + GlobalDebugEnable = 0; + GlobalPrivateLog = 0; + lt_uart_port = LT_UART_DEFAULT_PORT; +} + +/* _____ _____ _ _ + / ____| __ \| | | | + | | | |__) | | | | + | | | ___/| | | | + | |____| | | |__| | + \_____|_| \____*/ +lt_cpu_model_t lt_cpu_get_model() { + uint8_t chipId; + EFUSE_OneByteReadROM(9902, 0xF8, &chipId, L25EOUTVOLTAGE); + return CPU_MODEL_ENUM(FAMILY, chipId); +} + +uint32_t lt_cpu_get_unique_id() { + return lt_cpu_get_mac_id(); +} + +uint32_t lt_cpu_get_mac_id() { + uint32_t chipId = 0; + uint8_t *id = (uint8_t *)&chipId; + // 9902 was extracted from ROM disassembly, probably not needed + /* EFUSE_OneByteReadROM(9902, 0x3B, id + 0, L25EOUTVOLTAGE); + EFUSE_OneByteReadROM(9902, 0x3C, id + 1, L25EOUTVOLTAGE); + EFUSE_OneByteReadROM(9902, 0x3D, id + 2, L25EOUTVOLTAGE); */ + // new method, based on EFUSE logical map + uint8_t *efuse = (uint8_t *)malloc(512); + // TODO do what EFUSE_LogicalMapRead() does, and read only the used data + EFUSE_LogicalMap_Read(efuse); + memcpy(id, efuse + 0x11A + 3, 3); + free(efuse); + return chipId; +} + +const char *lt_cpu_get_core_type() { + return "ARM Cortex-M4F"; +} + +uint32_t lt_cpu_get_freq() { + return CPU_ClkGet(false); +} + +/*_____ _ + | __ \ (_) + | | | | _____ ___ ___ ___ + | | | |/ _ \ \ / / |/ __/ _ \ + | |__| | __/\ V /| | (_| __/ + |_____/ \___| \_/ |_|\___\__*/ +void lt_reboot() { + // The Watchdog Way + lt_wdt_enable(1L); + while (1) {} +} + +bool lt_reboot_download_mode() { + // mww 0x40000138 0x8 + HAL_WRITE32(SYSTEM_CTRL_BASE, REG_SYS_NORESET_FF, 0x08); + // reboot it the ugly way + sys_reset(); + while (1) {} + return true; +} + +lt_reboot_reason_t lt_get_reboot_reason() { + // TODO + return REBOOT_REASON_UNKNOWN; +} + +void lt_gpio_recover() { + // PA14 and PA15 are apparently unusable with SWD enabled + sys_jtag_off(); + Pinmux_Config(PA_14, PINMUX_FUNCTION_GPIO); + Pinmux_Config(PA_15, PINMUX_FUNCTION_GPIO); +} + +/*______ _ _ + | ____| | | | + | |__ | | __ _ ___| |__ + | __| | |/ _` / __| '_ \ + | | | | (_| \__ \ | | | + |_| |_|\__,_|___/_| |*/ +lt_flash_id_t lt_flash_get_id() { + lt_flash_id_t id; + uint8_t idBytes[3]; + flash_read_id(NULL, idBytes, 3); + id.manufacturer_id = idBytes[0]; + id.chip_id = idBytes[1]; + id.chip_size_id = idBytes[2]; + return id; +} + +/*__ __ + | \/ | + | \ / | ___ _ __ ___ ___ _ __ _ _ + | |\/| |/ _ \ '_ ` _ \ / _ \| '__| | | | + | | | | __/ | | | | | (_) | | | |_| | + |_| |_|\___|_| |_| |_|\___/|_| \__, | + __/ | + |__*/ +uint32_t lt_ram_get_size() { + return 256 * 1024; +} + +/* ____ _______ + / __ \__ __|/\ + | | | | | | / \ + | | | | | | / /\ \ + | |__| | | |/ ____ \ + \____/ |_/_/ \*/ +lt_ota_type_t lt_ota_get_type() { + return OTA_TYPE_DUAL; +} + +bool lt_ota_is_valid(uint8_t index) { + uint32_t offset; + switch (index) { + case 1: + offset = FLASH_OTA1_OFFSET; + break; + case 2: + offset = FLASH_OTA2_OFFSET; + break; + default: + return false; + } + uint8_t *address = (uint8_t *)(SPI_FLASH_BASE + offset); + return memcmp(address, "81958711", 8) == 0; +} + +uint8_t lt_ota_dual_get_current() { + // RTL8710B is XIP, so check the code offset in flash + uint32_t addr = (uint32_t)lt_log; + uint32_t offs = addr - SPI_FLASH_BASE; + return offs > FLASH_OTA2_OFFSET ? 2 : 1; +} + +uint8_t lt_ota_dual_get_stored() { + uint32_t *ota_address = (uint32_t *)0x8009000; + if (*ota_address == 0xFFFFFFFF) + return 1; + uint32_t ota_counter = *((uint32_t *)0x8009004); + // even count of zero-bits means OTA1, odd count means OTA2 + // this allows to switch OTA images by simply clearing next bits, + // without needing to erase the flash + uint8_t count = 0; + for (uint8_t i = 0; i < 32; i++) { + if ((ota_counter & (1 << i)) == 0) + count++; + } + return 1 + (count % 2); +} + +bool lt_ota_switch(bool revert) { + uint8_t current = lt_ota_dual_get_current(); + uint8_t stored = lt_ota_dual_get_stored(); + if ((current == stored) == revert) + return true; + + if (!lt_ota_is_valid(stored ^ 0b11)) + return false; + + // - read current OTA switch value from 0x9004 + // - reset OTA switch to 0xFFFFFFFE if it's 0x0 + // - else check first non-zero bit of OTA switch + // - write OTA switch with first non-zero bit cleared + + uint32_t value = HAL_READ32(SPI_FLASH_BASE, FLASH_SYSTEM_OFFSET + 4); + if (value == 0) { + uint8_t *system = (uint8_t *)malloc(64); + lt_flash_read(FLASH_SYSTEM_OFFSET, system, 64); + // reset OTA switch + ((uint32_t *)system)[1] = -2; + lt_flash_erase_block(FLASH_SYSTEM_OFFSET); + return lt_flash_write(FLASH_SYSTEM_OFFSET, system, 64); + } + + // clear first non-zero bit + value <<= 1; + // write OTA switch to flash + flash_write_word(NULL, FLASH_SYSTEM_OFFSET + 4, value); + return true; +} + +/*_ __ _ _ _ + \ \ / / | | | | | | + \ \ /\ / /_ _| |_ ___| |__ __| | ___ __ _ + \ \/ \/ / _` | __/ __| '_ \ / _` |/ _ \ / _` | + \ /\ / (_| | || (__| | | | (_| | (_) | (_| | + \/ \/ \__,_|\__\___|_| |_|\__,_|\___/ \__, | + __/ | + |___*/ +bool lt_wdt_enable(uint32_t timeout) { + watchdog_init(timeout); + watchdog_start(); + return true; +} + +void lt_wdt_disable() { + watchdog_stop(); +} + +void lt_wdt_feed() { + watchdog_refresh(); +} diff --git a/cores/realtek-amb/base/lt_defs.h b/cores/realtek-amb/base/lt_defs.h new file mode 100644 index 0000000..e6250ff --- /dev/null +++ b/cores/realtek-amb/base/lt_defs.h @@ -0,0 +1,8 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_HAS_PRINTF 1 + +#define LT_HEAP_FUNC xPortGetFreeHeapSize +#define LT_REALLOC_FUNC pvPortReAlloc diff --git a/arduino/realtek-ambz/port/flashdb/fal_flash_ambz_port.c b/cores/realtek-amb/base/port/fal_flash_ambz_port.c similarity index 83% rename from arduino/realtek-ambz/port/flashdb/fal_flash_ambz_port.c rename to cores/realtek-amb/base/port/fal_flash_ambz_port.c index 79b25c3..cea509b 100644 --- a/arduino/realtek-ambz/port/flashdb/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) @@ -15,10 +17,11 @@ static int read(long offset, uint8_t *buf, size_t size) { } static int write(long offset, const uint8_t *buf, size_t size) { - return size * flash_stream_write(NULL, offset, size, buf); + return size * flash_stream_write(NULL, offset, size, (uint8_t *)buf); } static int erase(long offset, size_t size) { + offset &= ~(FLASH_ERASE_MIN_SIZE - 1); size = ((size - 1) / FLASH_ERASE_MIN_SIZE) + 1; for (uint16_t i = 0; i < size; i++) { flash_erase_sector(NULL, offset + i * FLASH_ERASE_MIN_SIZE); diff --git a/arduino/realtek-ambz/port/printf/printf.c b/cores/realtek-amb/base/port/printf.c similarity index 83% rename from arduino/realtek-ambz/port/printf/printf.c rename to cores/realtek-amb/base/port/printf.c index 9724504..01815cc 100644 --- a/arduino/realtek-ambz/port/printf/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 @@ -15,10 +12,10 @@ extern uint32_t UART_Writable(void *UARTx); extern void UART_CharPut(void *UARTx, uint8_t TxData); -static const void *uart_dev[3] = { - UART0_REG_BASE, - UART1_REG_BASE, - LOG_UART_REG_BASE, +static void *uart_dev[3] = { + (void *)UART0_REG_BASE, + (void *)UART1_REG_BASE, + (void *)LOG_UART_REG_BASE, }; uint8_t lt_uart_port = 2; diff --git a/arduino/realtek-ambz/port/printf/printf_port.h b/cores/realtek-amb/base/port/printf_port.h similarity index 68% rename from arduino/realtek-ambz/port/printf/printf_port.h rename to cores/realtek-amb/base/port/printf_port.h index f54885d..74d770e 100644 --- a/arduino/realtek-ambz/port/printf/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/arduino/realtek-ambz/cores/arduino/sdk_extern.h b/cores/realtek-amb/base/sdk_private.h similarity index 50% rename from arduino/realtek-ambz/cores/arduino/sdk_extern.h rename to cores/realtek-amb/base/sdk_private.h index c77cb73..4b89051 100644 --- a/arduino/realtek-ambz/cores/arduino/sdk_extern.h +++ b/cores/realtek-amb/base/sdk_private.h @@ -2,31 +2,48 @@ #pragma once -// va_list is declared by SDK and conflicting -#include +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus -// disable typedef in basic_types.h -#define boolean boolean_rtl +// note: this is *not* replacing any stdlib functions :) +#include -#include // define string macros first -#undef isdigit // then remove them, as they conflict -#undef islower // with ctype.h macros -#undef isprint -#undef isspace -#undef isxdigit -#undef strtol -#undef strtoul +// fix conflicts with Arduino's PinMode enum +#define PinMode PinModeRTL +// remove log_printf() if included before sdk_private.h +#undef log_printf +#if LT_RTL8710B #include -#include -#include #include -#include -#include -#include +#include +#endif +#if LT_RTL8720C +#include +#endif -// remove previously defined workaround -#undef boolean +#include +#undef MBED_GPIO_API_H // ..no comment +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// remove previously defined workarounds +#undef PinMode // undefine ROM stdio in favor of printf() library (wrappers) #undef printf @@ -36,6 +53,8 @@ #undef vsnprintf #undef vprintf #include +// conflict with lt_logger.h +#undef log_printf // moved from syscalls.h #define _close __rtl_close @@ -56,5 +75,6 @@ extern void SystemCoreClockUpdate(void); extern int _sscanf_patch(const char *buf, const char *fmt, ...); -// include printf() wrapper disable methods -#include +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/cores/realtek-ambz/base/config/FreeRTOSConfig.h b/cores/realtek-ambz/base/config/FreeRTOSConfig.h new file mode 100644 index 0000000..4a377c8 --- /dev/null +++ b/cores/realtek-ambz/base/config/FreeRTOSConfig.h @@ -0,0 +1,8 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +#include_next "FreeRTOSConfig.h" + +#undef configTOTAL_HEAP_SIZE +#define configTOTAL_HEAP_SIZE ((size_t)(160 * 1024)) diff --git a/cores/realtek-ambz/base/config/lwipopts.h b/cores/realtek-ambz/base/config/lwipopts.h new file mode 100644 index 0000000..7c5a6a9 --- /dev/null +++ b/cores/realtek-ambz/base/config/lwipopts.h @@ -0,0 +1,17 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +#include_next "lwipopts.h" + +// - 2022-05-23 set LWIP_NUM_NETIF_CLIENT_DATA to 1 +#define LWIP_NUM_NETIF_CLIENT_DATA 1 +// - 2022-05-23 set MEMP_NUM_UDP_PCB to 7 +#undef MEMP_NUM_UDP_PCB +#define MEMP_NUM_UDP_PCB 7 + +// LWIP_COMPAT_MUTEX cannot prevent priority inversion. It is recommended to implement priority-aware mutexes. (Define +// LWIP_COMPAT_MUTEX_ALLOWED to disable this error.) +#define LWIP_COMPAT_MUTEX_ALLOWED 1 + +#define LWIP_TCPIP_TIMEOUT 1 diff --git a/cores/realtek-ambz/base/config/platform_opts.h b/cores/realtek-ambz/base/config/platform_opts.h new file mode 100644 index 0000000..8469f3e --- /dev/null +++ b/cores/realtek-ambz/base/config/platform_opts.h @@ -0,0 +1,14 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +#include_next "platform_opts.h" + +// - 2022-05-18 include lwip/init.h +#include + +// - 2022-05-08 change CONFIG_USE_POLARSSL to CONFIG_USE_MBEDTLS +#undef CONFIG_USE_POLARSSL +#undef CONFIG_USE_MBEDTLS +#define CONFIG_USE_POLARSSL 0 +#define CONFIG_USE_MBEDTLS 1 diff --git a/platform/.clang-format b/cores/realtek-ambz/base/fixups/.clang-format similarity index 100% rename from platform/.clang-format rename to cores/realtek-ambz/base/fixups/.clang-format diff --git a/platform/realtek-ambz/fixups/app_start_patch.c b/cores/realtek-ambz/base/fixups/app_start_patch.c similarity index 98% rename from platform/realtek-ambz/fixups/app_start_patch.c rename to cores/realtek-ambz/base/fixups/app_start_patch.c index 7d12206..0778a50 100644 --- a/platform/realtek-ambz/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" } diff --git a/cores/realtek-ambz/base/fixups/basic_types.h b/cores/realtek-ambz/base/fixups/basic_types.h new file mode 100644 index 0000000..600279d --- /dev/null +++ b/cores/realtek-ambz/base/fixups/basic_types.h @@ -0,0 +1,8 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +// fix conflicting declaration with ArduinoCore-API +#ifdef ARDUINO +#define boolean boolean_rtl +#endif +#include_next "basic_types.h" +#undef boolean diff --git a/platform/realtek-ambz/fixups/cmsis.h b/cores/realtek-ambz/base/fixups/cmsis.h similarity index 100% rename from platform/realtek-ambz/fixups/cmsis.h rename to cores/realtek-ambz/base/fixups/cmsis.h diff --git a/platform/realtek-ambz/fixups/cmsis_ipsr.c b/cores/realtek-ambz/base/fixups/cmsis_ipsr.c similarity index 95% rename from platform/realtek-ambz/fixups/cmsis_ipsr.c rename to cores/realtek-ambz/base/fixups/cmsis_ipsr.c index ca47a89..d6307fd 100644 --- a/platform/realtek-ambz/fixups/cmsis_ipsr.c +++ b/cores/realtek-ambz/base/fixups/cmsis_ipsr.c @@ -8,4 +8,5 @@ __attribute__((weak)) uint32_t __get_IPSR() { uint32_t result; asm volatile ("MRS %0, ipsr" : "=r" (result) ); + return result; } diff --git a/cores/realtek-ambz/base/fixups/hal_crypto.h b/cores/realtek-ambz/base/fixups/hal_crypto.h new file mode 100644 index 0000000..bfd9bed --- /dev/null +++ b/cores/realtek-ambz/base/fixups/hal_crypto.h @@ -0,0 +1,12 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#include_next "hal_crypto.h" + +#pragma once + +// mbedTLS (ssl_tls.c) uses S1 and S2 as variable name +// rtl8710b_pinmux.h defines them as integer values +#if defined(CONFIG_SSL_RSA) && defined(RTL_HW_CRYPTO) && defined(S1) +#undef S1 +#undef S2 +#endif diff --git a/platform/realtek-ambz/fixups/lib_rtlstd_patch.a b/cores/realtek-ambz/base/fixups/lib_rtlstd_patch.a similarity index 100% rename from platform/realtek-ambz/fixups/lib_rtlstd_patch.a rename to cores/realtek-ambz/base/fixups/lib_rtlstd_patch.a diff --git a/platform/realtek-ambz/fixups/lib_rtlstd_patch.md b/cores/realtek-ambz/base/fixups/lib_rtlstd_patch.md similarity index 100% rename from platform/realtek-ambz/fixups/lib_rtlstd_patch.md rename to cores/realtek-ambz/base/fixups/lib_rtlstd_patch.md diff --git a/platform/realtek-ambz/fixups/log_uart.c b/cores/realtek-ambz/base/fixups/log_uart.c similarity index 100% rename from platform/realtek-ambz/fixups/log_uart.c rename to cores/realtek-ambz/base/fixups/log_uart.c diff --git a/platform/realtek-ambz/fixups/machine/endian.h b/cores/realtek-ambz/base/fixups/machine/endian.h similarity index 100% rename from platform/realtek-ambz/fixups/machine/endian.h rename to cores/realtek-ambz/base/fixups/machine/endian.h diff --git a/cores/realtek-ambz/base/fixups/memproc.h b/cores/realtek-ambz/base/fixups/memproc.h new file mode 100644 index 0000000..4f0718b --- /dev/null +++ b/cores/realtek-ambz/base/fixups/memproc.h @@ -0,0 +1,9 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#pragma once + +#include + +#define _memcmp memcmp +#define _memcpy memcpy +#define _memset memset diff --git a/platform/realtek-ambz/fixups/net_sockets.c b/cores/realtek-ambz/base/fixups/net_sockets.c similarity index 100% rename from platform/realtek-ambz/fixups/net_sockets.c rename to cores/realtek-ambz/base/fixups/net_sockets.c diff --git a/cores/realtek-ambz/base/fixups/platform/platform_stdlib.h b/cores/realtek-ambz/base/fixups/platform/platform_stdlib.h new file mode 100644 index 0000000..795004f --- /dev/null +++ b/cores/realtek-ambz/base/fixups/platform/platform_stdlib.h @@ -0,0 +1,3 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#include "../platform_stdlib.h" diff --git a/cores/realtek-ambz/base/fixups/platform_stdlib.h b/cores/realtek-ambz/base/fixups/platform_stdlib.h new file mode 100644 index 0000000..ebe54e1 --- /dev/null +++ b/cores/realtek-ambz/base/fixups/platform_stdlib.h @@ -0,0 +1,22 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#pragma once + +// platform_stdlib.h in amb1_sdk includes some stdlib headers, +// as well as Realtek's stdlib replacement headers. It also defines +// some macros to map stdlib functions to SDK functions, so it's +// generally just not needed at all. + +// This is also the only file that publicly includes strproc.h and memproc.h, +// so this fixup resolves all these issues. + +#include /* va_list */ +#include +#include +#include + +#include "basic_types.h" // fixup: replaces typedef boolean for Arduino compatibility +#include "memproc.h" // fixup: redirects to stdlib +#include "strproc.h" // fixup: redirects to stdlib + +#include "diag.h" diff --git a/cores/realtek-ambz/base/fixups/section_config.h b/cores/realtek-ambz/base/fixups/section_config.h new file mode 100644 index 0000000..fb968c8 --- /dev/null +++ b/cores/realtek-ambz/base/fixups/section_config.h @@ -0,0 +1,6 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +// section_config.h is in the same directory as basic_types.h +// make the former include a fixup instead +#include "basic_types.h" +#include_next "section_config.h" diff --git a/cores/realtek-ambz/base/fixups/strproc.h b/cores/realtek-ambz/base/fixups/strproc.h new file mode 100644 index 0000000..6a2b5c9 --- /dev/null +++ b/cores/realtek-ambz/base/fixups/strproc.h @@ -0,0 +1,8 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#pragma once + +#include + +#define _strcpy strcpy +#define _strlen strlen diff --git a/platform/realtek-ambz/fixups/wifi_mode.c b/cores/realtek-ambz/base/fixups/wifi_mode.c similarity index 100% rename from platform/realtek-ambz/fixups/wifi_mode.c rename to cores/realtek-ambz/base/fixups/wifi_mode.c diff --git a/cores/realtek-ambz/base/lt_defs.h b/cores/realtek-ambz/base/lt_defs.h new file mode 100644 index 0000000..0125e4b --- /dev/null +++ b/cores/realtek-ambz/base/lt_defs.h @@ -0,0 +1,8 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_HAS_LWIP 1 +#define LT_HAS_LWIP2 1 +#define LT_HAS_FREERTOS 1 +#define LT_HAS_MBEDTLS 1 diff --git a/cores/realtek-ambz/base/lt_family.h b/cores/realtek-ambz/base/lt_family.h new file mode 100644 index 0000000..9723ffb --- /dev/null +++ b/cores/realtek-ambz/base/lt_family.h @@ -0,0 +1,18 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +#include LT_VARIANT_H + +// Choose the main UART output port +#ifndef LT_UART_DEFAULT_PORT +#if HAS_SERIAL2 +#define LT_UART_DEFAULT_PORT 2 +#elif HAS_SERIAL0 +#define LT_UART_DEFAULT_PORT 0 +#elif HAS_SERIAL1 +#define LT_UART_DEFAULT_PORT 1 +#else +#error "No serial port is available" +#endif +#endif diff --git a/cores/realtek-ambz/base/wraps/stdlib.c b/cores/realtek-ambz/base/wraps/stdlib.c new file mode 100644 index 0000000..20e785c --- /dev/null +++ b/cores/realtek-ambz/base/wraps/stdlib.c @@ -0,0 +1,115 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-14. */ + +#include + +#define ROM __attribute__((long_call)) + +ROM int prvAtoi(const char *str); +ROM long simple_strtol(const char *str, char **str_end, int base); +ROM unsigned long simple_strtoul(const char *str, char **str_end, int base); +ROM int Rand(); +ROM char *__rtl_strcat_v1_00(char *dest, const char *src); +ROM char *_strcpy(char *dest, const char *src); +ROM char *__rtl_strncat_v1_00(char *dest, const char *src, size_t count); +ROM char *_strncpy(char *dest, const char *src, size_t count); +ROM char *_strchr(const char *str, int ch); +ROM int prvStrCmp(const char *lhs, const char *rhs); +ROM size_t prvStrLen(const char *str); +ROM int _strncmp(const char *lhs, const char *rhs, size_t count); +ROM char *_strpbrk(const char *dest, const char *breakset); +ROM char *prvStrStr(const char *str, const char *substr); +ROM char *prvStrtok(char *str, const char *delim); +ROM void *__rtl_memchr_v1_00(const void *ptr, int ch, size_t count); +ROM int _memcmp(const void *lhs, const void *rhs, size_t count); +ROM void *_memcpy(void *dest, const void *src, size_t count); +ROM void *__rtl_memmove_v1_00(void *dest, const void *src, size_t count); +ROM void *_memset(void *dest, int ch, size_t count); +ROM char *_strsep(char **stringp, const char *delim); + +int __wrap_atoi(const char *str) { + return prvAtoi(str); +} + +long __wrap_atol(const char *str) { + return simple_strtol(str, NULL, 10); +} + +long __wrap_strtol(const char *str, char **str_end, int base) { + return simple_strtol(str, str_end, base); +} + +unsigned long __wrap_strtoul(const char *str, char **str_end, int base) { + return simple_strtoul(str, str_end, base); +} + +int __wrap_rand() { + return Rand(); +} + +char *__wrap_strcat(char *dest, const char *src) { + return __rtl_strcat_v1_00(dest, src); +} + +char *__wrap_strcpy(char *dest, const char *src) { + return _strcpy(dest, src); +} + +char *__wrap_strncat(char *dest, const char *src, size_t count) { + return __rtl_strncat_v1_00(dest, src, count); +} + +char *__wrap_strncpy(char *dest, const char *src, size_t count) { + return _strncpy(dest, src, count); +} + +char *__wrap_strchr(const char *str, int ch) { + return _strchr(str, ch); +} + +int __wrap_strcmp(const char *lhs, const char *rhs) { + return prvStrCmp(lhs, rhs); +} + +size_t __wrap_strlen(const char *str) { + return prvStrLen(str); +} + +int __wrap_strncmp(const char *lhs, const char *rhs, size_t count) { + return _strncmp(lhs, rhs, count); +} + +char *__wrap_strpbrk(const char *dest, const char *breakset) { + return _strpbrk(dest, breakset); +} + +char *__wrap_strstr(const char *str, const char *substr) { + return prvStrStr(str, substr); +} + +char *__wrap_strtok(char *str, const char *delim) { + return prvStrtok(str, delim); +} + +void *__wrap_memchr(const void *ptr, int ch, size_t count) { + return __rtl_memchr_v1_00(ptr, ch, count); +} + +int __wrap_memcmp(const void *lhs, const void *rhs, size_t count) { + return _memcmp(lhs, rhs, count); +} + +void *__wrap_memcpy(void *dest, const void *src, size_t count) { + return _memcpy(dest, src, count); +} + +void *__wrap_memmove(void *dest, const void *src, size_t count) { + return __rtl_memmove_v1_00(dest, src, count); +} + +void *__wrap_memset(void *dest, int ch, size_t count) { + return _memset(dest, ch, count); +} + +char *__wrap_strsep(char **stringp, const char *delim) { + return _strsep(stringp, delim); +} diff --git a/platform/realtek-ambz/openocd/amebaz.cfg b/cores/realtek-ambz/misc/amebaz.cfg similarity index 100% rename from platform/realtek-ambz/openocd/amebaz.cfg rename to cores/realtek-ambz/misc/amebaz.cfg diff --git a/platform/realtek-ambz/bin/boot_all_10C7.bin b/cores/realtek-ambz/misc/boot_all_10C7.bin similarity index 100% rename from platform/realtek-ambz/bin/boot_all_10C7.bin rename to cores/realtek-ambz/misc/boot_all_10C7.bin diff --git a/platform/realtek-ambz/bin/boot_all_77F7.bin b/cores/realtek-ambz/misc/boot_all_77F7.bin similarity index 100% rename from platform/realtek-ambz/bin/boot_all_77F7.bin rename to cores/realtek-ambz/misc/boot_all_77F7.bin diff --git a/platform/realtek-ambz/bin/boot_all_C556.bin b/cores/realtek-ambz/misc/boot_all_C556.bin similarity index 100% rename from platform/realtek-ambz/bin/boot_all_C556.bin rename to cores/realtek-ambz/misc/boot_all_C556.bin diff --git a/platform/realtek-ambz/ld/export-rom_symbol_v01.txt b/cores/realtek-ambz/misc/export-rom_symbol_v01.txt similarity index 100% rename from platform/realtek-ambz/ld/export-rom_symbol_v01.txt rename to cores/realtek-ambz/misc/export-rom_symbol_v01.txt diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_4M_980k_cpp.ld b/cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip1.template.ld similarity index 94% rename from platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_4M_980k_cpp.ld rename to cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip1.template.ld index 9028410..0358098 100644 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_4M_980k_cpp.ld +++ b/cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip1.template.ld @@ -25,8 +25,8 @@ MEMORY XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xF5000-0x20 /* XIP1: 980k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x08100000+0x20, LENGTH = 0xF5000-0x20 /* XIP2: 980k, 32 Bytes resvd for header */ + XIP1 (rx) : ORIGIN = 0x08000000+0x20+${FLASH_OTA1_OFFSET}, LENGTH = ${FLASH_OTA1_LENGTH}-0x20 /* XIP1, 32 Bytes resvd for header */ + XIP2 (rx) : ORIGIN = 0x08000000+0x20+${FLASH_OTA2_OFFSET}, LENGTH = ${FLASH_OTA2_LENGTH}-0x20 /* XIP2, 32 Bytes resvd for header */ } diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_cpp.ld b/cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip2.template.ld similarity index 94% rename from platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_cpp.ld rename to cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip2.template.ld index 35aff74..c2cd4d4 100644 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_cpp.ld +++ b/cores/realtek-ambz/misc/rlx8711B-symbol-v02-img2_xip2.template.ld @@ -25,8 +25,8 @@ MEMORY XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xC5000-0x20 /* XIP1: 788k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x080D0000+0x20, LENGTH = 0xC5000-0x20 /* XIP2: 788k, 32 Bytes resvd for header */ + XIP1 (rx) : ORIGIN = 0x08000000+0x20+${FLASH_OTA1_OFFSET}, LENGTH = ${FLASH_OTA1_LENGTH}-0x20 /* XIP1, 32 Bytes resvd for header */ + XIP2 (rx) : ORIGIN = 0x08000000+0x20+${FLASH_OTA2_OFFSET}, LENGTH = ${FLASH_OTA2_LENGTH}-0x20 /* XIP2, 32 Bytes resvd for header */ } diff --git a/cores/realtek-ambz2/base/fixups/memory.c b/cores/realtek-ambz2/base/fixups/memory.c new file mode 100644 index 0000000..373037c --- /dev/null +++ b/cores/realtek-ambz2/base/fixups/memory.c @@ -0,0 +1,32 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +#include +#include +#include +#include + +#include +#include +#include + +int __wrap_memcmp(const void *av, const void *bv, size_t len) { + return utility_stubs.memcmp(av, bv, len); +} + +void *__wrap_memcpy(void *s1, const void *s2, size_t n) { + return utility_stubs.memcpy(s1, s2, n); +} + +void *__wrap_memmove(void *destaddr, const void *sourceaddr, unsigned length) { + return utility_stubs.memmove(destaddr, sourceaddr, length); +} + +void *__wrap_memset(void *dst0, int val, size_t length) { + return utility_stubs.memset(dst0, val, length); +} + +#if (CHIP_VER >= CHIP_B_CUT) +int __wrap_memcmp_s(const void *av, const void *bv, size_t len) { + return utility_stubs.memcmp_s(av, bv, len); +} +#endif diff --git a/cores/realtek-ambz2/base/fixups/memory.h b/cores/realtek-ambz2/base/fixups/memory.h new file mode 100644 index 0000000..be63e14 --- /dev/null +++ b/cores/realtek-ambz2/base/fixups/memory.h @@ -0,0 +1,17 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +#pragma once + +// Remove SDK definitions of memory utilities. +// Include stdlib versions instead. +// Wrapper functions for the removed prototypes are provided in memory.c. + +#include +#include +#include + +// Map SDK functions so that they point to stdlib again +#define rt_memcmp memcmp +#define rt_memcpy memcpy +#define rt_memmove memmove +#define rt_memset memset diff --git a/cores/realtek-ambz2/base/fixups/strproc.c b/cores/realtek-ambz2/base/fixups/strproc.c new file mode 100644 index 0000000..18d9de8 --- /dev/null +++ b/cores/realtek-ambz2/base/fixups/strproc.c @@ -0,0 +1,168 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +#include +#include +#include +#include +#include + +typedef struct strproc_func_stubs_s { + char *(*strcat)(char *dest, const char *src); + char *(*strchr)(const char *s, int c); + int (*strcmp)(const char *cs, const char *ct); + int (*strncmp)(const char *cs, const char *ct, size_t count); + int (*strnicmp)(const char *s1, const char *s2, size_t len); + char *(*strcpy)(char *dest, const char *src); + char *(*strncpy)(char *dest, const char *src, size_t count); + size_t (*strlcpy)(char *dst, const char *src, size_t s); + size_t (*strlen)(const char *s); + size_t (*strnlen)(const char *s, size_t count); + char *(*strncat)(char *dest, const char *src, size_t count); + char *(*strpbrk)(const char *cs, const char *ct); + size_t (*strspn)(const char *s, const char *accept); + char *(*strstr)(const char *s1, const char *s2); + char *(*strtok)(char *s, const char *ct); + size_t (*strxfrm)(char *dest, const char *src, size_t n); + char *(*strsep)(char **s, const char *ct); + double (*strtod)(const char *str, char **endptr); + float (*strtof)(const char *str, char **endptr); + long double (*strtold)(const char *str, char **endptr); + long (*strtol)(const char *nptr, char **endptr, int base); + long long (*strtoll)(const char *nptr, char **endptr, int base); + unsigned long (*strtoul)(const char *nptr, char **endptr, int base); + unsigned long long (*strtoull)(const char *nptr, char **endptr, int base); + int (*atoi)(const char *num); + unsigned int (*atoui)(const char *num); + long (*atol)(const char *num); + unsigned long (*atoul)(const char *num); + unsigned long long (*atoull)(const char *num); + double (*atof)(const char *str); + + uint32_t reserved[16]; // reserved space for next ROM code version function table extending. +} strproc_func_stubs_t; + +extern const strproc_func_stubs_t strproc_stubs; + +// Wrappers + +char *__wrap_strcat(char *dest, const char *src) { + return strproc_stubs.strcat(dest, src); +} + +char *__wrap_strchr(const char *s, int c) { + return strproc_stubs.strchr(s, c); +} + +int __wrap_strcmp(const char *cs, const char *ct) { + return strproc_stubs.strcmp(cs, ct); +} + +int __wrap_strncmp(const char *cs, const char *ct, size_t count) { + return strproc_stubs.strncmp(cs, ct, count); +} + +char *__wrap_strcpy(char *dest, const char *src) { + return strproc_stubs.strcpy(dest, src); +} + +char *__wrap_strncpy(char *dest, const char *src, size_t count) { + return strproc_stubs.strncpy(dest, src, count); +} + +size_t __wrap_strlen(const char *s) { + return strproc_stubs.strlen(s); +} + +char *__wrap_strncat(char *dest, const char *src, size_t count) { + return strproc_stubs.strncat(dest, src, count); +} + +char *__wrap_strpbrk(const char *cs, const char *ct) { + return strproc_stubs.strpbrk(cs, ct); +} + +size_t __wrap_strspn(const char *s, const char *accept) { + return strproc_stubs.strspn(s, accept); +} + +char *__wrap_strstr(const char *s1, const char *s2) { + return strproc_stubs.strstr(s1, s2); +} + +char *__wrap_strtok(char *s, const char *ct) { + return strproc_stubs.strtok(s, ct); +} + +size_t __wrap_strxfrm(char *dest, const char *src, size_t n) { + return strproc_stubs.strxfrm(dest, src, n); +} + +double __wrap_strtod(const char *str, char **endptr) { + return strproc_stubs.strtod(str, endptr); +} + +float __wrap_strtof(const char *str, char **endptr) { + return strproc_stubs.strtof(str, endptr); +} + +long double __wrap_strtold(const char *str, char **endptr) { + return strproc_stubs.strtold(str, endptr); +} + +double __wrap_atof(const char *str) { + return strproc_stubs.atof(str); +} + +long __wrap_strtol(const char *nptr, char **endptr, int base) { + return strproc_stubs.strtol(nptr, endptr, base); +} + +long long __wrap_strtoll(const char *nptr, char **endptr, int base) { + return strproc_stubs.strtoll(nptr, endptr, base); +} + +unsigned long __wrap_strtoul(const char *nptr, char **endptr, int base) { + return strproc_stubs.strtoul(nptr, endptr, base); +} + +unsigned long long __wrap_strtoull(const char *nptr, char **endptr, int base) { + return strproc_stubs.strtoull(nptr, endptr, base); +} + +int __wrap_atoi(const char *num) { + return strproc_stubs.atoi(num); +} + +long __wrap_atol(const char *num) { + return strproc_stubs.atol(num); +} + +// Standalone functions + +unsigned long atoul(const char *num) { + return strproc_stubs.atoul(num); +} + +unsigned long long atoull(const char *num) { + return strproc_stubs.atoull(num); +} + +unsigned int atoui(const char *num) { + return strproc_stubs.atoui(num); +} + +size_t strnlen(const char *s, size_t count) { + return strproc_stubs.strnlen(s, count); +} + +size_t strlcpy(char *dst, const char *src, size_t s) { + return strproc_stubs.strlcpy(dst, src, s); +} + +int strnicmp(const char *s1, const char *s2, size_t len) { + return strproc_stubs.strnicmp(s1, s2, len); +} + +char *strsep(char **s, const char *ct) { + return strproc_stubs.strsep(s, ct); +} diff --git a/cores/realtek-ambz2/base/fixups/strproc.h b/cores/realtek-ambz2/base/fixups/strproc.h new file mode 100644 index 0000000..aaa619f --- /dev/null +++ b/cores/realtek-ambz2/base/fixups/strproc.h @@ -0,0 +1,22 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +#pragma once + +// Remove SDK definitions of string processing methods. +// Include stdlib versions instead. +// Wrapper functions for the removed prototypes are provided in strproc.c. + +#include +#include +#include +#include + +// These functions aren't part of stdlib. + +unsigned long atoul(const char *num); +unsigned long long atoull(const char *num); +unsigned int atoui(const char *num); +size_t strnlen(const char *s, size_t count); +size_t strlcpy(char *dst, const char *src, size_t s); +int strnicmp(const char *s1, const char *s2, size_t len); +char *strsep(char **s, const char *ct); diff --git a/platform/realtek-ambz2/fixups/inc/time64.h b/cores/realtek-ambz2/base/fixups/time64.h similarity index 100% rename from platform/realtek-ambz2/fixups/inc/time64.h rename to cores/realtek-ambz2/base/fixups/time64.h diff --git a/cores/realtek-ambz2/base/fixups/utility.h b/cores/realtek-ambz2/base/fixups/utility.h new file mode 100644 index 0000000..f66be93 --- /dev/null +++ b/cores/realtek-ambz2/base/fixups/utility.h @@ -0,0 +1,6 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-03. */ + +#pragma once + +// proxy because we're not using soc/realtek/8710c/misc/utilities/include as it contains ctype.h +#include diff --git a/cores/realtek-ambz2/base/lt_defs.h b/cores/realtek-ambz2/base/lt_defs.h new file mode 100644 index 0000000..0125e4b --- /dev/null +++ b/cores/realtek-ambz2/base/lt_defs.h @@ -0,0 +1,8 @@ +#pragma once + +#error "Don't include this file directly" + +#define LT_HAS_LWIP 1 +#define LT_HAS_LWIP2 1 +#define LT_HAS_FREERTOS 1 +#define LT_HAS_MBEDTLS 1 diff --git a/cores/realtek-ambz2/base/lt_family.h b/cores/realtek-ambz2/base/lt_family.h new file mode 100644 index 0000000..9723ffb --- /dev/null +++ b/cores/realtek-ambz2/base/lt_family.h @@ -0,0 +1,18 @@ +/* Copyright (c) Kuba SzczodrzyƄski 2023-03-02. */ + +#pragma once + +#include LT_VARIANT_H + +// Choose the main UART output port +#ifndef LT_UART_DEFAULT_PORT +#if HAS_SERIAL2 +#define LT_UART_DEFAULT_PORT 2 +#elif HAS_SERIAL0 +#define LT_UART_DEFAULT_PORT 0 +#elif HAS_SERIAL1 +#define LT_UART_DEFAULT_PORT 1 +#else +#error "No serial port is available" +#endif +#endif diff --git a/platform/realtek-ambz2/ld/rtl8710c_ram.ld b/cores/realtek-ambz2/misc/rtl8710c_ram.ld similarity index 100% rename from platform/realtek-ambz2/ld/rtl8710c_ram.ld rename to cores/realtek-ambz2/misc/rtl8710c_ram.ld diff --git a/docs/README.md b/docs/README.md index d54d7c3..f8e57d7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,6 +2,6 @@ This documentation is best suited for rendering with MkDocs. Some elements may not display correctly in the GitHub markdown reader. -Please visit [https://docs.libretuya.ml/](https://docs.libretuya.ml/) for the full experience. +Please visit [https://docs.libretiny.eu/](https://docs.libretiny.eu/) for the full experience. If you still want to read the docs on GitHub, visit [SUMMARY.md](../SUMMARY.md). diff --git a/TODO.md b/docs/TODO.md similarity index 64% rename from TODO.md rename to docs/TODO.md index 7017d3a..937adbc 100644 --- a/TODO.md +++ b/docs/TODO.md @@ -11,6 +11,9 @@ 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 + - pretty much done for ambz and ambz2, Beken is yet left to do (`os_malloc()` etc.) +- remove all network protocol client/server implementations from SDKs (mDNS, HTTP, DNS, etc.) ### New families @@ -27,6 +30,12 @@ Explicit is better than implicit. - write OpenOCD flashers, using uf2ota library + FAL for partitions (in ltchiptool repository) +### Development + +- write Contributor's Guide +- export LT cores in an Arduino IDE-compatible format (automatically - GitHub Actions) +- consider using precompiled SDK blobs for improved build speed (especially on e.g. Raspberry Pi) + ### Serial - configuration of RX/TX pins @@ -34,6 +43,8 @@ Explicit is better than implicit. ### Other +- refactor `SerialClass` to have a shared header `Serial.h` in the common core (and `SerialData`, just like WiFi). Move ADR to common core +- implement Wire on BK, refactor the API and class - watchdog API - `Preferences` library - test/fix IPv6 on different families diff --git a/docs/boards_tuya_all.json b/docs/boards_tuya_all.json index cf108ac..2832f16 100644 --- a/docs/boards_tuya_all.json +++ b/docs/boards_tuya_all.json @@ -415,6 +415,32 @@ "datasheet_id": "Kbtesqh678sbe" } }, + "tcs905": { + "tcs905-3s": { + "mcu": "bk7231n", + "flash": 2097152, + "ram": 262144, + "pins_total": 22, + "connectivity": [ + "wifi", + "ble" + ], + "datasheet_name": "TCS905-3S-Module-Datasheet", + "datasheet_id": "Kc5xc8hhigndh" + }, + "tcs905-u": { + "mcu": "bk7231n", + "flash": 2097152, + "ram": 262144, + "pins_total": 21, + "connectivity": [ + "wifi", + "ble" + ], + "datasheet_name": "TCS905-U-module-datasheet", + "datasheet_id": "Kc5x1p35fs5zf" + } + }, "axy": { "axy2s": { "mcu": "ecr6600", @@ -493,6 +519,20 @@ "datasheet_id": "Kbohlj8eg19u5" } }, + "wx": { + "wxu": { + "mcu": "t103c-hl", + "flash": 2097152, + "ram": 327680, + "pins_total": 21, + "connectivity": [ + "wifi", + "ble" + ], + "datasheet_name": "wxu-module-datasheet", + "datasheet_id": "Kc2xk9qlk04so" + } + }, "wr": { "wr1": { "mcu": "rtl8710bn", diff --git a/docs/reference/config.md b/docs/dev/config.md similarity index 76% rename from docs/reference/config.md rename to docs/dev/config.md index af5f7ef..ac64f39 100644 --- a/docs/reference/config.md +++ b/docs/dev/config.md @@ -10,12 +10,31 @@ custom_fw_name = my_firmware # custom firmware version # - default: current date in yy.mm.dd format custom_fw_version = 1.2.0 + +# custom build options (#defines, NOT compiler flags) +custom_options.lwip = + LWIP_IPV4 = 1 +custom_options.freertos = + configUSE_TICK_HOOK = 1 + +# partition layout modification (not recommended, unless you know what you're doing) +custom_flash.app = 0x12000 + +# custom board JSON (overrides) +# - path relative to the project directory; only values specified +# in the JSON will override the defaults +# (it's like using board_build.xxx but for more keys) +custom_board = myboard.json + +# custom library versions (not recommended) +custom_versions.lwip = 2.1.3 +custom_versions.beken_bdk = 2021.06.07 ``` -## LibreTuya options +## LibreTiny options !!! note - See [LibreTuyaConfig.h](../../ltapi/_libre_tuya_config_8h_source.md) for most options and their defaults. + See [lt_config.h](../../ltapi/lt__config_8h.md) for most options and their defaults. All options are configurable via C++ defines in PlatformIO project file. For example: ```ini title="platformio.ini" @@ -29,16 +48,18 @@ build_flags = ### Logger -- `LT_LOGGER` (1) - enable/disable LibreTuya logger globally; disabling this sets the loglevel to `LT_LEVEL_NONE` - the logger can't be enabled even by using `lt_log_set_port()` +- `LT_LOGGER` (1) - enable/disable LibreTiny logger globally; disabling this sets the loglevel to `LT_LEVEL_NONE` - the logger can't be enabled even by using `lt_log_set_port()` - `LT_LOGLEVEL` - global LT loglevel: - - `LT_LEVEL_VERBOSE` - - `LT_LEVEL_TRACE` - same as `LT_LEVEL_VERBOSE` - - `LT_LEVEL_DEBUG` - - `LT_LEVEL_INFO` - default - - `LT_LEVEL_WARN` - - `LT_LEVEL_ERROR` - - `LT_LEVEL_FATAL` - - `LT_LEVEL_NONE` - disables everything + + - `LT_LEVEL_VERBOSE` + - `LT_LEVEL_TRACE` - same as `LT_LEVEL_VERBOSE` + - `LT_LEVEL_DEBUG` + - `LT_LEVEL_INFO` - default + - `LT_LEVEL_WARN` + - `LT_LEVEL_ERROR` + - `LT_LEVEL_FATAL` + - `LT_LEVEL_NONE` - disables everything + - `LT_LOGGER_TIMESTAMP` (1) - print program runtime in printk-like format - `LT_LOGGER_CALLER` (1) - print calling method name - `LT_LOGGER_TASK` (1) - print calling FreeRTOS task (if available) @@ -83,7 +104,7 @@ Options for controlling default UART log output. - `LT_UART_DEFAULT_LOGGER` (unset) - override default output port for LT logger only - `LT_UART_DEFAULT_SERIAL` (unset) - override default output port for `Serial` class (without a number) - `LT_UART_SILENT_ENABLED` (1) - enable auto-silencing of SDK "loggers"; this makes the serial output much more readable, but can hide some error messages -- `LT_UART_SILENT_ALL` (0) - disable all SDK output (LT output and logger still work) +- `LT_UART_SILENT_ALL` (0) - disable all SDK output (LT output and logger still work); since v1.0.0 this has no effect if `LT_UART_SILENT_ENABLED` is 0 !!! info Values 0, 1 and 2 correspond to physical UART port numbers (refer to board pinout for the available ports). @@ -101,19 +122,21 @@ Options for controlling default UART log output. ### Family feature config !!! bug "Warning" - These options are not meant for end-users. They're provided here as a reference for developers. + These options are not meant for end-users. They're provided here as a reference for developers. **Do not set these options manually**. -These options are selectively set by all families, as part of the build process. They are used for enabling LT core API parts, if the family has support for it. +These options are selectively set by all families, as part of the build process. They are used for enabling LT core API parts, if the family has support for it. Files named `lt_defs.h`, containing these options, are read by the PlatformIO builders (note: they're never included by C code). The `LT_ARD_*` options are only used with Arduino frameworks. The meaning of most flags is as follows: +- `LT_HAS_FREERTOS` - FreeRTOS supported and used - `LT_HAS_LWIP` - LwIP in SDK (any version) - `LT_HAS_LWIP2` - LwIP v2.0.0 or newer -- `LT_HAS_FREERTOS` - FreeRTOS supported and used - `LT_HAS_MBEDTLS` - mbedTLS in SDK -- `LT_ARD_HAS_MD5` - MD5 library implemented, `MD5Impl.h` available -- `LT_ARD_HAS_WIFI` - WiFi library implemented, `WiFiData.h` available +- `LT_HAS_PRINTF` - printf library implemented +- `LT_ARD_HAS_SERIAL` - Serial class implemented, `Serial.h` available - `LT_ARD_HAS_SOFTSERIAL` - SoftwareSerial library implemented, `SoftwareSerial.h` available +- `LT_ARD_HAS_WIFI` - WiFi library implemented, `WiFiData.h` available - `LT_HEAP_FUNC` - function name used to get available heap size (for `LT_HEAP_I()`) +- `LT_REALLOC_FUNC` - function name used for `realloc()` call diff --git a/docs/libs-3rd-party.md b/docs/dev/libs-3rd-party.md similarity index 63% rename from docs/libs-3rd-party.md rename to docs/dev/libs-3rd-party.md index 3706f99..06640ed 100644 --- a/docs/libs-3rd-party.md +++ b/docs/dev/libs-3rd-party.md @@ -1,6 +1,6 @@ # Libraries -A page outlining 3-rd party libraries compatible with LibreTuya. +A page outlining 3-rd some party libraries compatible with LibreTiny. !!! note To use some (most? (all?)) of these, a flag in `platformio.ini` is required to disable compatibility checks (because most libs are meant for ESP32/Arduino official framework): @@ -9,27 +9,27 @@ A page outlining 3-rd party libraries compatible with LibreTuya. lib_compat_mode = off ``` -## MQTT +## [256dpi/MQTT](https://registry.platformio.org/libraries/256dpi/MQTT) Tested with `realtek-ambz`. ```ini lib_deps = 256dpi/MQTT@^2.5.0 ``` -## DNSServer +## [bbx10/DNSServer](https://registry.platformio.org/libraries/bbx10/DNSServer) Tested with `beken-72xx`. ```ini lib_deps = bbx10/DNSServer@^1.1.0 ``` This is the same library as in ESP32 Arduino Core. -## AsyncTCP-esphome +## [esphome/AsyncTCP-esphome](https://registry.platformio.org/libraries/esphome/AsyncTCP-esphome) Tested with `beken-72xx` and `realtek-ambz`. ```ini lib_deps = esphome/AsyncTCP-esphome@^2.0.0 ``` This is ESPHome's fork of the original library. -## ESPAsyncWebServer-esphome +## [esphome/ESPAsyncWebServer-esphome](https://registry.platformio.org/libraries/esphome/ESPAsyncWebServer-esphome) Tested with `beken-72xx` and `realtek-ambz`. ```ini lib_deps = esphome/ESPAsyncWebServer-esphome@^3.0.0 diff --git a/docs/dev/lt-api.md b/docs/dev/lt-api.md new file mode 100644 index 0000000..95bf1b2 --- /dev/null +++ b/docs/dev/lt-api.md @@ -0,0 +1,187 @@ +# LibreTiny API + +The LibreTiny API is divided in two parts: + +- the C API, available in all families and frameworks +- the C++ API, available in the Arduino framework only. + +The C++ API is a thin wrapper around the C API (using classes with inline functions). +It's provided for less-experienced users, who are used to Arduino IDE's classes like `ESP` (and for backwards compatibility). +It's recommended to use the C API wherever possible. + +## C API + +This API is available using: + +- `#include ` +- `#include ` + +### CPU + +{% + include-markdown "../../ltapi/lt__cpu_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### Device + +{% + include-markdown "../../ltapi/lt__device_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### Flash + +{% + include-markdown "../../ltapi/lt__flash_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### Memory + +{% + include-markdown "../../ltapi/lt__mem_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### OTA + +{% + include-markdown "../../ltapi/lt__ota_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### Utilities + +{% + include-markdown "../../ltapi/lt__utils_8h.md" + start="## Public Functions\n" + end="## Macros" +%} + +### Watchdog + +{% + include-markdown "../../ltapi/lt__wdt_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +### Logger + +{% + include-markdown "../../ltapi/lt__logger_8h.md" + start="## Public Functions\n" + end="## Macros" +%} + +### POSIX compatibility API + +A small subset of POSIX functions, commonly present in other Arduino cores, is provided for compatibility. + +{% + include-markdown "../../ltapi/lt__posix__api_8h.md" + start="## Public Functions\n" + end="## Public Functions Documentation" +%} + +## C++ API + +This API is available using: + +- `#include ` + +### LibreTiny + +{% + include-markdown "../../ltapi/class_libre_tiny.md" + start="# Detailed Description\n" + end="## Public Functions Documentation" +%} + +{% + include-markdown "../../ltapi/class_libre_tiny.md" + start="## Public Functions\n" + end="# Detailed Description" +%} + +### LibreTinyOTA + +{% + include-markdown "../../ltapi/class_libre_tiny_o_t_a.md" + start="# Detailed Description\n" + end="## Public Functions Documentation" +%} + +{% + include-markdown "../../ltapi/class_libre_tiny_o_t_a.md" + start="## Public Functions\n" + end="# Detailed Description" +%} + +### LibreTinyWDT + +{% + include-markdown "../../ltapi/class_libre_tiny_w_d_t.md" + start="# Detailed Description\n" + end="## Public Functions Documentation" +%} + +{% + include-markdown "../../ltapi/class_libre_tiny_w_d_t.md" + start="## Public Functions\n" + end="# Detailed Description" +%} + +### ESP (compatibility class) + +{% + include-markdown "../../ltapi/class_esp_class.md" + start="# Detailed Description\n" + end="## Public Functions Documentation" +%} + +{% + include-markdown "../../ltapi/class_esp_class.md" + start="## Public Functions\n" + end="# Detailed Description" +%} + +### Arduino custom API + +These functions extend the standard Wiring (Arduino) library, to provide additional features. + +{% + include-markdown "../../ltapi/wiring__custom_8h.md" + start="## Public Functions\n" + end="## Macros" +%} + +### Arduino compatibility API + +These functions and macros provide compatibility between LT and other Arduino cores, such as ESP32. + +{% + include-markdown "../../ltapi/wiring__compat_8h.md" + start="## Public Functions\n" + end="## Macros" +%} + +{% + include-markdown "../../ltapi/wiring__compat_8h.md" + start="## Macros\n" + end="## Public Functions Documentation" +%} + +## Chip & family types + +{% + include-markdown "../../ltapi/lt__types_8h.md" + start="## Public Types Documentation\n" + end="## Macro Definition Documentation" +%} diff --git a/docs/dev/migration_v1.0.0.md b/docs/dev/migration_v1.0.0.md new file mode 100644 index 0000000..b3a3063 --- /dev/null +++ b/docs/dev/migration_v1.0.0.md @@ -0,0 +1,44 @@ +# Migration to v1.0.0 + +1.0.0 is the first major release of LT. Compared to previous versions, few things have changed which can impact developers using LT in PlatformIO (but shouldn't affect ESPHome users at all). + +## GPIO numbering + +Pin numbers passed to `pinMode()`/`digitalWrite()`/etc. are now the raw GPIO numbers of the chip. Previously, one had to use `D#` numbering in these functions, so you have to migrate your code to use GPIO numbers instead. + +To make the migration easier, you can simply change: + +```cpp +digitalWrite(1, LOW); +``` + +to: + +```cpp +digitalWrite(PIN_D1, LOW); +// or +digitalWrite(D1, LOW); +``` + +For more information, refer to [GPIO instructions](../getting-started/gpio.md). + +## Environment stability + +All public headers exported by LT are now stable between all chip families - this means that they're not including any code from the vendor SDK. + +This change was made to prevent the SDK from introducing its own functions and macros, which often replace stdlib functions, or cause other compilation issues. + +If your code is using vendor SDK functions, you'll have to import the appropriate headers yourself. + +## OTA (.uf2 packages) + +The format of OTA packages has changed slightly, to reflect the OTA scheme naming change (described below). There's also a distinction between the `flasher` (PC flasher) and `device` (on-device OTA code) in the package. + +New OTA packages are backwards-compatible (i.e. can be installed on devices running LT v0.x.x), but **v1.0.0 will not accept older packages** - it's **not** possible to rollback a device from v1.0.0 to v0.x.x with an old .uf2 file. + +## OTA scheme naming change + +Previously, each chip family had a "has dual OTA" property, which was very confusing (even to me, the author of the code). A new scheme has been introduced: + +- single OTA - devices with a separate "download" partition, which is used by the bootloader to flash the main application +- dual OTA - devices with two separate application partitions, which can be updated directly by the application diff --git a/docs/ota/README.md b/docs/dev/ota/README.md similarity index 97% rename from docs/ota/README.md rename to docs/dev/ota/README.md index 72900e1..2a8821f 100644 --- a/docs/ota/README.md +++ b/docs/dev/ota/README.md @@ -1,6 +1,6 @@ # UF2-based OTA -LibreTuya's OTA updating is based on [Microsoft's UF2 specification](https://microsoft.github.io/uf2/). Some aspects of the process, such as OTA1/2 support and target partition selection, have been customized with extension tags. +LibreTiny's OTA updating is based on [Microsoft's UF2 specification](https://microsoft.github.io/uf2/). Some aspects of the process, such as OTA1/2 support and target partition selection, have been customized with extension tags. !!! note Just like in UF2, all values in this format are little-endian. @@ -26,12 +26,6 @@ Each firmware image may be either applicable: For easier understanding, these update types will be referred to in this document using the numbers. -## Custom family IDs - -{% - include-markdown "../status/supported_families.md" -%} - ## Extension tags Standard tags are used: `VERSION`, `DEVICE` and `DEVICE_ID`. diff --git a/docs/ota/library.md b/docs/dev/ota/library.md similarity index 95% rename from docs/ota/library.md rename to docs/dev/ota/library.md index c7f3126..5a0c63b 100644 --- a/docs/ota/library.md +++ b/docs/dev/ota/library.md @@ -1,6 +1,6 @@ # uf2ota library -uf2ota library allows to write a LibreTuya UF2 file to the flash, while parsing all the necessary tags. It manages the target partitions, compatibility checks, and works on top of the FAL provided by FlashDB. +uf2ota library allows to write a LibreTiny UF2 file to the flash, while parsing all the necessary tags. It manages the target partitions, compatibility checks, and works on top of the FAL provided by FlashDB. ## Usage example diff --git a/docs/ota/uf2ota.md b/docs/dev/ota/uf2ota.md similarity index 93% rename from docs/ota/uf2ota.md rename to docs/dev/ota/uf2ota.md index e8a4519..09b33ad 100644 --- a/docs/ota/uf2ota.md +++ b/docs/dev/ota/uf2ota.md @@ -1,6 +1,6 @@ # uf2ota.py -This is a tool for converting LibreTuya firmware images to UF2 format for OTA updates. +This is a tool for converting LibreTiny firmware images to UF2 format for OTA updates. ```console $ python uf2ota.py @@ -51,7 +51,7 @@ Tags: - FIRMWARE: esphome - VERSION: 2022.6.0-dev - OTA_VERSION: 01 - - DEVICE: LibreTuya + - DEVICE: LibreTiny - LT_HAS_OTA1: 01 - LT_HAS_OTA2: 01 - LT_PART_1: ota1 @@ -63,7 +63,7 @@ Total binary size: 302448 # dump -Dump UF2 file (only LibreTuya format) into separate firmware binaries. +Dump UF2 file (only LibreTiny format) into separate firmware binaries. ```console $ python uf2ota.py dump out.uf2 diff --git a/docs/reference/project-structure.md b/docs/dev/project-structure.md similarity index 95% rename from docs/reference/project-structure.md rename to docs/dev/project-structure.md index 8da2480..edf8a4e 100644 --- a/docs/reference/project-structure.md +++ b/docs/dev/project-structure.md @@ -6,11 +6,11 @@ arduino/ │ ├─ cores/ Wiring core files │ ├─ libraries/ Supported built-in family libraries │ ├─ port/ External library port units -├─ libretuya/ +├─ libretiny/ │ ├─ api/ Library interfaces │ ├─ common/ Units common to all families │ ├─ compat/ Fixes for compatibility with ESP32 framework -│ ├─ core/ LibreTuya API for Arduino cores +│ ├─ core/ LibreTiny API for Arduino cores │ ├─ libraries/ Built-in family-independent libraries | ├─ port/ External library port units | ├─ posix/ POSIX-like C utility functions @@ -26,7 +26,7 @@ builder/ │ ├─ -arduino.py Arduino Core build system ├─ libs/ Builders for external libraries ├─ utils/ SCons utils used during the build -├─ arduino-common.py Builder to provide ArduinoCore-API and LibreTuya APIs +├─ arduino-common.py Builder to provide ArduinoCore-API and LibreTiny APIs ├─ main.py Main PlatformIO builder docs/ Project documentation, guides, tips, etc. platform/ diff --git a/docs/dev/stdlib.md b/docs/dev/stdlib.md new file mode 100644 index 0000000..d3079f8 --- /dev/null +++ b/docs/dev/stdlib.md @@ -0,0 +1,107 @@ +# C stdlib + +Usually, functions available in C standard library should not be defined by the SDK. Instead, they should be included using GCC's headers, and implemented by the libc or wrapped and implemented in the SDK. + +The following functions should not be defined by the SDK. Their presence creates conflicts due to incompatibility with C library, so they should be removed or disabled, and replaced with wrappers. + +Memory management functions must be wrapped and redirected to FreeRTOS. The necessary linker flags are already added for all families (in `base.py`), and a FreeRTOS implementation of the wrappers are provided in `malloc.c` in the common core. If the family doesn't use FreeRTOS, a separate implementation must be added. + +Additionally, if the `printf` library is used in the chip family code, all other vendor-defined printf-like functions should be replaced with it. + +Function prototypes taken from [devdocs.io](https://devdocs.io/c/). + +```cpp +// stdlib.h / Dynamic memory management +void *calloc(size_t num, size_t size); +void *malloc(size_t size); +void *realloc(void *ptr, size_t new_size); +void free(void *ptr); +// stdlib.h / Conversions to numeric formats +double atof(const char *str); +int atoi(const char *str); +long atol(const char *str); +long long atoll(const char *str); +double strtod(const char *str, char **str_end); +float strtof(const char *str, char **str_end); +long strtol(const char *str, char **str_end, int base); +long double strtold(const char *str, char **str_end); +long long strtoll(const char *str, char **str_end, int base); +unsigned long strtoul(const char *str, char **str_end, int base); +unsigned long long strtoull(const char *str, char **str_end, int base); +// stdlib.h / Random numbers +int rand(); + +// string.h / Character classification +int isalnum(int ch); +int isalpha(int ch); +int islower(int ch); +int isupper(int ch); +int isdigit(int ch); +int isxdigit(int ch); +int iscntrl(int ch); +int isgraph(int ch); +int isspace(int ch); +int isblank(int ch); +int isprint(int ch); +int ispunct(int ch); +int tolower(int ch); +int toupper(int ch); +// string.h / String manipulation +char *strcat(char *dest, const char *src); +char *strcpy(char *dest, const char *src); +char *strncat(char *dest, const char *src, size_t count); +char *strncpy(char *dest, const char *src, size_t count); +size_t strxfrm(char *dest, const char *src, size_t count); +// string.h / String examination +char *strchr(const char *str, int ch); +int strcmp(const char *lhs, const char *rhs); +size_t strcspn(const char *dest, const char *src); +size_t strlen(const char *str); +int strncmp(const char *lhs, const char *rhs, size_t count); +char *strpbrk(const char *dest, const char *breakset); +char *strrchr(const char *str, int ch); +size_t strspn(const char *dest, const char *src); +char *strstr(const char *str, const char *substr); +char *strtok(char *str, const char *delim); +// string.h / Character array manipulation +void *memchr(const void *ptr, int ch, size_t count); +int memcmp(const void *lhs, const void *rhs, size_t count); +void *memcpy(void *dest, const void *src, size_t count); +void *memmove(void *dest, const void *src, size_t count); +void *memset(void *dest, int ch, size_t count); + +// stdio.h / Unformatted input/output +int putc(int ch, FILE *stream); +int putchar(int ch); +int puts(const char *str); + +// stdio.h / Formatted input/output +int printf(const char *format, ...); +int sprintf(char *buffer, const char *format, ...); +int snprintf(char *buffer, size_t bufsz, const char *format, ...); +int vprintf(const char *format, va_list vlist); +int vsprintf(char *buffer, const char *format, va_list vlist); +int vsnprintf(char *buffer, size_t bufsz, const char *format, va_list vlist); + +// POSIX/BSD (from www.die.net) +size_t strlcat(char *dst, const char *src, size_t size); +size_t strlcpy(char *dst, const char *src, size_t size); +size_t strnlen(const char *s, size_t maxlen); +char *strsep(char **stringp, const char *delim); + +// Non-stdlib +_calloc_r +_free_r +_malloc_r +_realloc_r +atoui +atoul +atoull +strnicmp +zalloc + +// Additional forbidden macros +#define max(a, b) +#define min(a, b) +typedef bool boolean; +``` diff --git a/docs/flashing/SUMMARY.md b/docs/flashing/SUMMARY.md index 332d425..625860c 100644 --- a/docs/flashing/SUMMARY.md +++ b/docs/flashing/SUMMARY.md @@ -2,9 +2,7 @@ * [Flashing PlatformIO projects](platformio.md) * [Flashing ESPHome](esphome.md) +* [Dumping stock firmware](dumping.md) * [Using ltchiptool GUI](tools/ltchiptool.md) * [Converting with tuya-cloudcutter](tools/cloudcutter.md) -* 🔌 Chip connection guide - * [Beken BK72xx](../platform/beken-72xx/flashing.md) - * [Realtek RTL8710Bx](../platform/realtek-ambz/flashing.md) * [Auto-download-reboot](tools/adr.md) diff --git a/docs/flashing/chip-connection/SUMMARY.md b/docs/flashing/chip-connection/SUMMARY.md new file mode 100644 index 0000000..2b29f15 --- /dev/null +++ b/docs/flashing/chip-connection/SUMMARY.md @@ -0,0 +1,4 @@ +# Chip connection guides + +* [Beken BK72xx](../../platform/beken-72xx/flashing.md) +* [Realtek RTL8710Bx](../../platform/realtek-ambz/flashing.md) diff --git a/docs/flashing/dumping.md b/docs/flashing/dumping.md new file mode 100644 index 0000000..26b4aa8 --- /dev/null +++ b/docs/flashing/dumping.md @@ -0,0 +1,5 @@ +# Dumping stock firmware + +It is a good idea to dump the stock firmware (full flash contents) of your device before flashing custom firmware. + +Currently, the easiest way to dump firmware is to use [ltchiptool](tools/ltchiptool.md). Download/install the tool, and follow the guide. diff --git a/docs/flashing/esphome.md b/docs/flashing/esphome.md index 48e3c49..d4958fa 100644 --- a/docs/flashing/esphome.md +++ b/docs/flashing/esphome.md @@ -13,7 +13,7 @@ ESPHome can be flashed in few different ways, depending on your needs. === "CLI" - The flasher program built-in LibreTuya is also available for ESPHome. + The flasher program built-in LibreTiny is also available for ESPHome. - use `python -m esphome run yourdevice.yml` to recompile AND upload the firmware - use `python -m esphome upload yourdevice.yml` to upload without recompiling diff --git a/docs/flashing/inc/ota-cloudcutter.md b/docs/flashing/inc/ota-cloudcutter.md index b99b7a8..02077e2 100644 --- a/docs/flashing/inc/ota-cloudcutter.md +++ b/docs/flashing/inc/ota-cloudcutter.md @@ -3,6 +3,6 @@ !!! note This currently applies to BK7231T and BK7231N only. `tuya-cloudcutter` can't be used for other chips. -Grab the `bk7231x_app.ota.ug.bin` file from the build directory - take care to choose the correct file. It must have "OTA" and "UG" in its name. +Grab the `image_bk7231x_app.ota.ug.bin` file from the build directory - take care to choose the correct file. It must have "OTA" and "UG" in its name. Next, refer to [Using tuya-cloudcutter](../tools/cloudcutter.md) guide. diff --git a/docs/flashing/inc/ota-openbeken.md b/docs/flashing/inc/ota-openbeken.md index 55b8ea3..cafba8d 100644 --- a/docs/flashing/inc/ota-openbeken.md +++ b/docs/flashing/inc/ota-openbeken.md @@ -2,4 +2,4 @@ [OpenBeken](https://github.com/openshwprojects/OpenBK7231T_App) is a custom, Tasmota-like firmware for non-ESP chips. Currently, this part of the guide applies to BK7231 only, as that's the only chip supported both by LT and OBK. -OBK is compatible with standard Beken OTA packages, but the web panel does a filename check to prevent chip type mismatch. Grab the `bk7231x_app.ota.bin` file from build directory (note: without "UG" in the name!), rename it to something like `OpenBK7231T_esphome.rbl` (change T to N depending on the chip type), and drop it on the OTA panel. +OBK is compatible with standard Beken OTA packages, but the web panel does a filename check to prevent chip type mismatch. Grab the `image_bk7231t_app.ota.rbl` file from build directory (note: without "UG" in the name!), rename it to something like `OpenBK7231T_esphome.rbl` (change T to N depending on the chip type), and drop it on the OTA panel. diff --git a/docs/flashing/inc/uart-info.md b/docs/flashing/inc/uart-info.md index 0b16fa9..9467d2d 100644 --- a/docs/flashing/inc/uart-info.md +++ b/docs/flashing/inc/uart-info.md @@ -1 +1 @@ -The device needs to be connected to your PC with a UART-TTL adapter. Refer to chip connection guides (see: menu on the left) to learn how to connect your device. +The device needs to be connected to your PC with a UART-TTL adapter. Refer to [chip connection guides](../chip-connection/SUMMARY.md) to learn how to connect your device. diff --git a/docs/flashing/inc/uart-ltchiptool.md b/docs/flashing/inc/uart-ltchiptool.md index c05bc60..0c15962 100644 --- a/docs/flashing/inc/uart-ltchiptool.md +++ b/docs/flashing/inc/uart-ltchiptool.md @@ -1,6 +1,6 @@ ## Using ltchiptool (wired, via UART) -You can use the [ltchiptool](https://github.com/libretuya/ltchiptool) GUI or CLI to manually flash the firmware. Grab the `firmware.uf2` file from the build directory. Then, follow the [ltchiptool usage guide](../tools/ltchiptool.md) to flash it to the device. +You can use the [ltchiptool](../tools/ltchiptool.md) GUI or CLI to manually flash the firmware. Grab the `firmware.uf2` file from the build directory. Then, follow the [ltchiptool usage guide](../tools/ltchiptool.md) to flash it to the device. !!! tip The UF2 file may have a different name, depending on the project you're building. Usually it's best to grab the latest (sorted by date) file with UF2 extension from the build directory. diff --git a/docs/flashing/platformio.md b/docs/flashing/platformio.md index 09c561e..5dc6ef8 100644 --- a/docs/flashing/platformio.md +++ b/docs/flashing/platformio.md @@ -1,6 +1,6 @@ # Flashing PlatformIO projects -PlatformIO projects developed with LibreTuya can be flashed just like any other PIO project. +PlatformIO projects developed with LibreTiny can be flashed just like any other PIO project. !!! abstract All binary files generated by PlatformIO will be in `.pio/build//`. The methods described below may require you to get a file from that directory. @@ -9,7 +9,7 @@ PlatformIO projects developed with LibreTuya can be flashed just like any other ## Built-in flasher -LibreTuya has a built-in firmware uploader, based on [ltchiptool](tools/ltchiptool.md). Pressing `Upload` in PlatformIO IDE does all the work for you. +LibreTiny has a built-in firmware uploader, based on [ltchiptool](tools/ltchiptool.md). Pressing `Upload` in PlatformIO IDE does all the work for you. If you have more than one COM port, configure your PIO project first: diff --git a/docs/flashing/tools/adr.md b/docs/flashing/tools/adr.md index 8ae6a7e..a976b67 100644 --- a/docs/flashing/tools/adr.md +++ b/docs/flashing/tools/adr.md @@ -7,7 +7,7 @@ This feature allows to upload code using UART, without needing to ground the CEN It is enabled by default (using the `LT_AUTO_DOWNLOAD_REBOOT` option). It works by listening to incoming UART data, and checking if it matches a command that the flashing program would send. If it does, a chip reboot is performed and the uploading process starts. !!! note - ADR will only work if there's already a recent build of LibreTuya flashed to the device (and if the device doesn't bootloop or freeze immediately). + ADR will only work if there's already a recent build of LibreTiny flashed to the device (and if the device doesn't bootloop or freeze immediately). ## Beken 72xx @@ -15,4 +15,4 @@ The code listens on UART1 for a link-check command (`01 E0 FC 01 00`). The baudr ## Realtek AmebaZ -This is not yet implemented. +This only works when using [ltchiptool](ltchiptool.md) for flashing. Upon starting UART communication, the tool sends `55 AA 22 E0 D6 FC` (0x55AA followed by the `realtek-ambz` family ID). After detecting that pattern, the chip proceeds to reboot into UART download mode (using [`lt_reboot_download_mode()`](../../../ltapi/lt__device_8h.md)) diff --git a/docs/flashing/tools/cloudcutter.md b/docs/flashing/tools/cloudcutter.md index 87969d4..3e1ae56 100644 --- a/docs/flashing/tools/cloudcutter.md +++ b/docs/flashing/tools/cloudcutter.md @@ -22,7 +22,7 @@ If your device doesn't have a profile yet, it will probably not work. You can co ### Firmware building -1. [Compile ESPHome](../../projects/esphome.md), or your custom firmware based on LibreTuya. +1. [Compile ESPHome](../../projects/esphome.md), or your custom firmware based on LibreTiny. 2. Get the firmware binary, named `bk7231x_app.ota.ug.bin` from the build directory (`.pio/build//` or `.esphome/build//.pioenvs//`). 3. Put it in the `custom-firmware` directory of tuya-cloudcutter. diff --git a/docs/flashing/tools/ltchiptool.md b/docs/flashing/tools/ltchiptool.md index 3c0c908..3a8e0df 100644 --- a/docs/flashing/tools/ltchiptool.md +++ b/docs/flashing/tools/ltchiptool.md @@ -1,22 +1,22 @@ # ltchiptool -[ltchiptool](https://github.com/libretuya/ltchiptool) is a universal, easy-to-use GUI flashing/dumping tool for BK7231, RTL8710B and RTL8720C. It also contains some CLI utilities for binary firmware manipulation. +[ltchiptool](https://github.com/libretiny-eu/ltchiptool) is a universal, easy-to-use GUI flashing/dumping tool for BK7231, RTL8710B and RTL8720C. It also contains some CLI utilities for binary firmware manipulation.
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![PyPI](https://img.shields.io/pypi/v/ltchiptool)](https://pypi.org/project/ltchiptool/) -[![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/libretuya/ltchiptool?include_prereleases&label=GUI%20release)](https://github.com/libretuya/ltchiptool/releases/latest) +[![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/libretuya/ltchiptool?include_prereleases&label=GUI%20release)](https://github.com/libretiny-eu/ltchiptool/releases/latest) - +
## Installation
-[:material-download-outline: Download Windows GUI](https://github.com/libretuya/ltchiptool/releases/latest){ .md-button } +[:material-download-outline: Download Windows GUI](https://github.com/libretiny-eu/ltchiptool/releases/latest){ .md-button }
### CLI program @@ -26,7 +26,7 @@ Install the package from PyPI, using `pip install ltchiptool`. Run the CLI using ### GUI application ???+ quote "Windows 7 and newer" - Download the latest release .EXE from the [GitHub Releases page](https://github.com/libretuya/ltchiptool/releases/latest). Open the file, and you're ready to go! + Download the latest release .EXE from the [GitHub Releases page](https://github.com/libretiny-eu/ltchiptool/releases/latest). Open the file, and you're ready to go! ??? quote "Windows (manual installation)" Install the package from PyPI (**including GUI extras**), using `pip install ltchiptool[gui]`. Note that Python 3.10 or newer is required for the GUI. I recommend Python 3.10 since it has [prebuilt wheels](https://pypi.org/project/wxPython/4.2.0/#files) of wxPython, which doesn't require C++ build dependencies. @@ -45,23 +45,58 @@ Install the package from PyPI, using `pip install ltchiptool`. Run the CLI using ## GUI Usage -The main window is somewhat similar to [NodeMCU PyFlasher](https://github.com/marcelstoer/nodemcu-pyflasher). +The main window is somewhat similar to [NodeMCU PyFlasher](https://github.com/marcelstoer/nodemcu-pyflasher). Available modes of operation are described below. -- For dumping, choose `Read flash`. If you've previously chosen an input or output file, it will generate a dump filename with the current timestamp and chip type. Otherwise, click `Browse` and choose the output file. By default, the tool will attempt to read the entire flash chip (usually 2 MiB). -- For flashing, choose `Write flash`. Click `Browse` and select *any* valid firmware file. The file type and chip type will be auto-detected, along with correct flash offset and length. No need to worry about overwriting the bootloader anymore! - - If the file you're selecting is `Unrecognized` or `Not flashable`, it's most likely not a valid firmware file. Refer to usage guides of the custom firmware project of choice, to find which file is meant for flashing. -- **It's best to leave `Auto-detect advanced parameters` checked**. If you're an experienced user and want to flash custom areas of the flash, uncheck the box and specify the parameters manually. -- When you're ready, hit `Start`. The tool will try to connect to the chip on the selected UART port. The black log window will print any warnings/errors, as well as **a short guide on how to put the chip in download mode**. +### Dumping firmware + +It is a good idea to dump the stock firmware (full flash contents) of your device before flashing custom firmware. + +1. Choose the `Read flash` option. If you've previously chosen an input or output file, it will generate a dump filename based on the current timestamp and chip type. Otherwise, click `Browse` and choose the output file. +2. You need to pick the "family" of your chip (the chip model). If you choose the wrong option, the process will fail, but the device won't be bricked. +3. Now, connect the chip to your PC, according to the [chip connection guides](../chip-connection/SUMMARY.md). Select the COM port that your UART adapter is using. +4. By default, the tool will attempt to read the entire flash chip (usually 2 MiB). Unless you know what you're doing, the default values don't need to be changed. +5. Hit `Start`. The tool will try to connect to the chip on the selected UART port. The black log window will print any warnings/errors. The dumping process should begin shortly. + +### Flashing firmware + +If you want to flash custom firmware, or restore stock firmware from a previously dumped file, follow the steps below. !!! info - LibreTuya generates multiple firmware files in the build directory. **You usually want to flash the `.uf2` file**, but since ltchiptool can detect file types, you can choose a different firmware file and it'll tell you if that works. + LibreTiny generates multiple firmware files in the build directory. **You usually want to flash the `.uf2` file**, but since ltchiptool can detect file types, you can choose a different firmware file and it'll tell you if that works. + +1. Choose `Write flash`. Click `Browse` and select a valid firmware file. The file type and chip type will be auto-detected, along with correct flash offset and length. No need to worry about overwriting the bootloader anymore! +2. Connect the chip to your PC, according to the [chip connection guides](../chip-connection/SUMMARY.md). Select the COM port that your UART adapter is using. +3. Hit `Start`. The tool will try to connect to the chip on the selected UART port. The black log window will print any warnings/errors. The flashing process should begin shortly. + +!!! info + **It's best to leave `Auto-detect advanced parameters` checked**. If you're an experienced user and want to flash custom areas of the flash, uncheck the box and specify the parameters manually. + + If the file you're selecting is `Unrecognized` or `Not flashable`, it's most likely not a valid firmware file. Refer to usage guides of the custom firmware project of choice, to find which file is meant for flashing. ## CLI Usage +### Flashing/dumping + +This is for users, who are more experienced with using a terminal. There are three main commands used for flashing: + +- `ltchiptool flash file ` - detect file type based on its contents (i.e. chip from which a dump was acquired), similar to Linux `file` command +- `ltchiptool flash read ` - make a full flash dump of the connected device; specifying the family is required +- `ltchiptool flash write ` - upload a file to the device; detects file type automatically (just like the `file` command above) + +Supported device families can be checked using `ltchiptool list families` command. In the commands above, you can use any of the family names (name/code/short name/etc). + +The upload UART port and baud rate should be detected automatically. To override it, use `-d COMx` or `-d /dev/ttyUSBx`. To change the target baud rate, use `-b 460800`. +Note that the baud rate is changed after linking. Linking is performed using chip-default baud rate. + +It's not required to specify chip family for writing files - `ltchiptool` tries to recognize contents of the file, and chooses the best settings automatically. +If you want to flash unrecognized/raw binaries (or fine-tune the flashing parameters), specify `-f ` and `-s `. + +## CLI Reference + !!! note If you're here to learn how to flash or dump firmware files, use the instructions above. - The content below serves as a short documentation page for [`ltchiptool`](https://github.com/libretuya/ltchiptool) and is mostly meant for advanced users. + The content below serves as a short documentation page for [`ltchiptool`](https://github.com/libretiny-eu/ltchiptool) and is mostly meant for advanced users. ```console $ ltchiptool --help @@ -88,22 +123,6 @@ Commands: uf2 Work with UF2 files ``` -### Flashing/dumping - -There are three main commands used for flashing: - -- `ltchiptool flash file ` - detect file type based on its contents (i.e. chip from which a dump was acquired), similar to Linux `file` command -- `ltchiptool flash read ` - make a full flash dump of the connected device; specifying the family is required -- `ltchiptool flash write ` - upload a file to the device; detects file type automatically (just like the `file` command above) - -Supported device families can be checked using `ltchiptool list families` command. In the commands above, you can use any of the family names (name/code/short name/etc). - -The upload UART port and baud rate is detected automatically. To override it, use `-d COMx` or `-d /dev/ttyUSBx`. To change the target baud rate, use `-b 460800`. -Note that the baud rate is changed after linking. Linking is performed using chip-default baud rate. - -It's not required to specify chip family for writing files - `ltchiptool` tries to recognize contents of the file, and chooses the best settings automatically. -If you want to flash unrecognized/raw binaries (or fine-tune the flashing parameters), specify `-f ` and `-s `. - ### UF2 Example ```console @@ -116,7 +135,7 @@ Tags: - FIRMWARE: arduinotest - VERSION: 22.08.01 - OTA_VERSION: 01 - - DEVICE: LibreTuya + - DEVICE: LibreTiny - BUILD_DATE: 6d08e862 - LT_HAS_OTA1: 01 - LT_HAS_OTA2: 00 diff --git a/docs/getting-started/README.md b/docs/getting-started/README.md index ed03791..ce21485 100644 --- a/docs/getting-started/README.md +++ b/docs/getting-started/README.md @@ -1,9 +1,9 @@ # Getting started -Using LibreTuya is simple, just like every other PlatformIO development platform. +Using LibreTiny is simple, just like every other PlatformIO development platform. 1. [Install PlatformIO](https://platformio.org/platformio-ide) -2. `platformio platform install -f https://github.com/kuba2k2/libretuya` +2. `platformio platform install -f https://github.com/kuba2k2/libretiny` ## Board selection @@ -15,11 +15,11 @@ Using LibreTuya is simple, just like every other PlatformIO development platform ## Run community projects -LibreTuya was developed with popular community projects in mind. Currently, unofficial [ESPHome port](../projects/esphome.md) is available ([the PR](https://github.com/esphome/esphome/pull/3509) will hopefully be merged into upstream at some point). +LibreTiny was developed with popular community projects in mind. Currently, unofficial [ESPHome port](../projects/esphome.md) is available ([the PR](https://github.com/esphome/esphome/pull/3509) will hopefully be merged into upstream at some point). ## Develop your own project -If you're developing your own embedded software, and want it to run on LibreTuya-supported chips, create a project. +If you're developing your own embedded software, and want it to run on LibreTiny-supported chips, create a project. - use PlatformIO IDE (PIO Home -> Open -> New Project) - run `pio project init` in your desired project directory @@ -28,16 +28,14 @@ Next, read one of the [flashing guides](../flashing/SUMMARY.md) to run your proj ### LT configuration -LibreTuya has a few configuration options that change its behavior or features. Refer to [LT configuration](../reference/config.md) for details. +LibreTiny has a few configuration options that change its behavior or features. Refer to [LT configuration](../dev/config.md) for details. -### GPIO usage +### GPIO usage - important change !!! important - This can be confusing at first, so make sure to read this part carefully to understand it. + Since v1.0.0, GPIOs are no longer meant to be referenced by `D#` numbers. - Input/output pin numbers in Arduino code (i.e. `digitalWrite()`) use Arduino pin numbers - for example `D1`, `D3`. This is the same as simply `1` or `3`, but it cannot be confused with CPU GPIO numbers. - - On the board pinout page, the purple blocks represent Arduino pins, while the dark red blocks refer to GPIO numbers. + If your program is using Arduino I/O functions, refer to the [Migration guide](../dev/migration_v1.0.0.md) to modify your program accordingly. ### Examples diff --git a/docs/getting-started/gpio.md b/docs/getting-started/gpio.md new file mode 100644 index 0000000..6bf604e --- /dev/null +++ b/docs/getting-started/gpio.md @@ -0,0 +1,31 @@ +# GPIO usage instructions + +!!! note + This has changed since v1.0.0. Refer to the [migration guide](../dev/migration_v1.0.0.md) for more info. + +GPIO pins can be accessed in a few ways: + +- using the raw GPIO number of the chip +- using the "function macro" of the pin +- using Arduino digital pin numbers (`D#`, deprecated) + +This applies both to Arduino code and ESPHome YAML configs. + +## GPIO numbers - Arduino only + +The simplest form of GPIO access is by using raw pin numbers of the CPU (just like on ESP8266/ESP32). For example, to access GPIO6, write `digitalRead(6)`. + +## Function macros - Arduino & ESPHome + +If you go to a board documentation page (like [this one - CB2S](../../boards/cb2s/README.md)) you'll see a pinout drawing, containing various labels in small blocks. There's also a table below to make the pinout a bit more clear. + +**You can use any of these labels** to access a particular pin. For example, to access GPIO6, which is also the PWM0 pin on CB2S, one can use: + +- `digitalRead(PIN_P6)` (Arduino) or `pin: P6` (ESPHome) +- `digitalRead(PIN_PWM0)` (Arduino) or `pin: PWM0` (ESPHome) + +## Arduino `D#` numbers (deprecated) + +This method of accessing pins is deprecated since v1.0.0, and **will** (probably) **be removed** in the future. It's kept for legacy compatibility. + +To access the previously mentioned GPIO6, use `digitalRead(D2)` or `digitalRead(PIN_D2)` or `pin: D2`. Note that the `D#` pin numbers are not consistent between boards (for example, on WB3S, GPIO6 is already D4). diff --git a/docs/libs-built-in.md b/docs/libs-built-in.md deleted file mode 100644 index beded9d..0000000 --- a/docs/libs-built-in.md +++ /dev/null @@ -1,40 +0,0 @@ -# Built-in libraries -(in alphabetical order) - -## base64 -- [Source](https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/base64.cpp): ESP32 Arduino Core -- [Reference](../ltapi/classbase64.md) - -Helper base64 encoder used in some libs taken from ESP32. - -## HTTPClient -- [Source](https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient): ESP32 Arduino Core -- [Reference](../ltapi/class_h_t_t_p_client.md) -- [Examples](https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient/examples) - -HTTP(S) client. - -## NetUtils - -Utilities and common classes related to network. - -- [ssl/MbedTLSClient.cpp](../ltapi/class_mbed_t_l_s_client.md) ([source](https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFiClientSecure/src): ESP32 WiFiClientSecure) -- [IPv6Address.cpp](../ltapi/classarduino_1_1_i_pv6_address.md) ([source](https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/IPv6Address.cpp): ESP32 IPv6Address) -- [LwIPRxBuffer.cpp](../ltapi/class_lw_i_p_rx_buffer.md) ([source](https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/src/WiFiClient.cpp): ESP32 WiFiClient) - -## WebServer -- [Source](https://github.com/espressif/arduino-esp32/tree/master/libraries/WebServer/src): ESP32 Arduino Core -- [Reference](../ltapi/class_web_server.md) -- Examples: - - [HelloServer](https://github.com/espressif/arduino-esp32/blob/master/libraries/WebServer/examples/HelloServer/HelloServer.ino) - - [MultiHomedServers](https://github.com/espressif/arduino-esp32/blob/master/libraries/WebServer/examples/MultiHomedServers/MultiHomedServers.ino) - -## WiFiMulti -- [Source](https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFi/src): ESP32 Arduino Core -- [Reference](../ltapi/class_wi_fi_multi.md) -- [Docs](https://docs.espressif.com/projects/arduino-esp32/en/latest/api/wifi.html#wifimulti) -- Examples: - - [WiFiMulti](https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiMulti/WiFiMulti.ino) - - [WiFiClientBasic](https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino) - -Class for selecting best available AP from a list of several ones. diff --git a/docs/ota/flashing.md b/docs/ota/flashing.md deleted file mode 100644 index f02241e..0000000 --- a/docs/ota/flashing.md +++ /dev/null @@ -1,4 +0,0 @@ -It is possible to upload firmware binaries manually, using the command-line tool `ltchiptool`. For this, you need the `.uf2` file generated after compilation (usually found in `.pio/build/my_board/`). - -1. Install Python. Afterwards, run `pip install ltchiptool`. -2. `ltchiptool uf2 upload my_firmware.uf2 uart COM96` (replace `my_firmware.uf2` with your file name and `COM96` with your upload port). diff --git a/docs/platform/beken-72xx/README.md b/docs/platform/beken-72xx/README.md index cd8ef15..551959d 100644 --- a/docs/platform/beken-72xx/README.md +++ b/docs/platform/beken-72xx/README.md @@ -1,5 +1,10 @@ # Beken 72xx +
+ +[Read flashing guide](flashing.md){ .md-button } +
+ ## Resources Name | Notes @@ -17,7 +22,7 @@ Name There are many chip variations in this SoC family: -- BK7231 - marked BK7321QN40, so we're calling it "BK7231Q" to reduce confusion +- BK7231 - marked BK7231QN40, so we're calling it "BK7231Q" to reduce confusion - BK7231T - BK7231N - BK7231S diff --git a/docs/platform/beken-72xx/flashing.md b/docs/platform/beken-72xx/flashing.md index 541c25a..d712b9e 100644 --- a/docs/platform/beken-72xx/flashing.md +++ b/docs/platform/beken-72xx/flashing.md @@ -33,7 +33,7 @@ Downloading is done using UART. For best experience, you should have two USB<->U Note that the download mode can only be activated when the flasher is running (there's no GPIO-strapping like on ESP8266). Additionally, BK7231T (not N) will exit the download mode when the flasher finishes its work. !!! tip - BK7231N can't be software-bricked, because it has a ROM that contains the download mode. **BK7231T doesn't contain the ROM, so be careful with this one**. + BK7231N can't be software-bricked, because it has a ROM that contains the download mode. **BK7231T doesn't contain it, so be careful with this one**. ## bk7231tools @@ -41,26 +41,26 @@ Note that the download mode can only be activated when the flasher is running (t ## Auto-download-reboot -If you have a recent version of LibreTuya installed on the chip, you can use [Auto-download-reboot](../../flashing/tools/adr.md) to reboot the chip automatically. This is enabled by default, so you don't have to change anything. +If you have a recent version of LibreTiny installed on the chip, you can use [Auto-download-reboot](../../flashing/tools/adr.md) to reboot the chip automatically. This is enabled by default, so you don't have to change anything. ## Single-adapter usage If you only have a single adapter, or just want to use the UART1 (upload) port only, you can change the logging port. -Refer to [Options & config](../../reference/config.md) (`Serial output` section). Set `LT_UART_DEFAULT_PORT` to `1`, which will use UART1 for all output. +Refer to [Options & config](../../dev/config.md) (`Serial output` section). Set `LT_UART_DEFAULT_PORT` to `1`, which will use UART1 for all output. ## Firmware output files These files are present in the build directory after successful compilation: -File | Description ---------------------------|---------------------------------------- -**firmware.uf2** | **UF2 package for UART and OTA upload** -bk7231t_app.ota.rbl | Beken OTA package (e.g. OpenBeken) -bk7231t_app.ota.ug.bin | Tuya OTA package (incl. Cloudcutter) -bk7231t_app_0x011000.rbl | App partition - flashable at 0x11000 -bk7231t_app_0x011000.crc | Encrypted app image - not for flashing -bk7231t_app_0x129F0A.rblh | RBL header - not for flashing +File | Description +--------------------------------|---------------------------------------- +**firmware.uf2** | **UF2 package for UART and OTA upload** +image_bk7231t_app.ota.rbl | Beken OTA package (e.g. OpenBeken) +image_bk7231t_app.ota.ug.bin | Tuya OTA package (incl. Cloudcutter) +image_bk7231t_app.0x011000.rbl | App partition - flashable at 0x11000 +image_bk7231t_app.0x011000.crc | Encrypted app image - not for flashing +image_bk7231t_app.0x129F0A.rblh | RBL header - not for flashing ## SPI flashing (unbricking BK7231T) diff --git a/docs/platform/realtek-ambz/README.md b/docs/platform/realtek-ambz/README.md index 6d127fc..3b3d02a 100644 --- a/docs/platform/realtek-ambz/README.md +++ b/docs/platform/realtek-ambz/README.md @@ -1,5 +1,10 @@ # Realtek AmebaZ +
+ +[Read flashing guide](flashing.md){ .md-button } +
+ ## Resources Name | Notes diff --git a/docs/platform/realtek-ambz/debugging.md b/docs/platform/realtek-ambz/debugging.md index 4c03336..4a81fd9 100644 --- a/docs/platform/realtek-ambz/debugging.md +++ b/docs/platform/realtek-ambz/debugging.md @@ -4,13 +4,13 @@ Debugging of Realtek Ameba chips is possible and was tested with OpenOCD running *(the following is applicable to Arduino framework, and was not tested with SDK framework)* -LibreTuya has ready-to-use OpenOCD config files: +LibreTiny has ready-to-use OpenOCD config files: -- [platform/realtek-ambz/openocd/amebaz.cfg](../../../platform/realtek-ambz/openocd/amebaz.cfg) +- [platform/realtek-ambz/openocd/amebaz.cfg](../../../cores/realtek-ambz/misc/amebaz.cfg) ## Local debugger -It should be possible to use PlatformIO's built-in debugging capabilities directly, when plugging an OpenOCD-compatible debugger into your PC. As there are no debugger interfaces built into Tuya boards, you need to specify your interface of choice in `platformio.ini`: +It should be possible to use PlatformIO's built-in debugging capabilities directly, when plugging an OpenOCD-compatible debugger into your PC. As there are no debugger interfaces built into these IoT boards, you need to specify your interface of choice in `platformio.ini`: ```ini [env:my_board] openocd_interface = diff --git a/docs/platform/realtek-ambz/flashing.md b/docs/platform/realtek-ambz/flashing.md index ee90b37..b1059fa 100644 --- a/docs/platform/realtek-ambz/flashing.md +++ b/docs/platform/realtek-ambz/flashing.md @@ -41,8 +41,8 @@ These files are present in the build directory after successful compilation: File | Description ------------------------|------------------------------------------------------------------- **firmware.uf2** | **UF2 package for UART and OTA upload** -image_0x00B000.ota1.bin | OTA 1 image, flashable to 0xB000 -image_0x0D0000.ota2.bin | OTA 2 image, flashable to 0xD0000 (the address might be different) +image_ota1.0x00B000.bin | OTA 1 image, flashable to 0xB000 +image_ota2.0x0D0000.bin | OTA 2 image, flashable to 0xD0000 (the address might be different) ## Other tools/guides @@ -50,7 +50,7 @@ These tools are **not recommended** and are kept here for reference only. Don't - [Flashing (Tuya manual)](https://developer.tuya.com/en/docs/iot/burn-and-authorize-wr-series-modules?id=Ka789pjc581u8) - [ImageTool (AmebaZ/AmebaD)](https://images.tuyacn.com/smart/Image_Tool/Image_Tool.zip) -- [rtltool.py](https://github.com/libretuya/ltchiptool/blob/master/ltchiptool/soc/ambz/util/rtltool.py) +- [rtltool.py](https://github.com/libretiny-eu/ltchiptool/blob/master/ltchiptool/soc/ambz/util/rtltool.py) OTA1/2 files can be flashed using `ImageTool_v2.3.1_AmebaZ(8710b)`. Browse and select one of the files and enter an appropriate address. Select COM port, press `Open` and then `Download`. diff --git a/docs/platform/realtek-ambz/memory-management.md b/docs/platform/realtek-ambz/memory-management.md deleted file mode 100644 index f65d243..0000000 --- a/docs/platform/realtek-ambz/memory-management.md +++ /dev/null @@ -1,15 +0,0 @@ -# Memory management - -Function | Target | #define location | Notes ---------------|------------------------|---------------------------------------------------|------------------------------------------------------------------------------------------------ -__`malloc`__ | __`pvPortMalloc`__ | `component/common/api/platform/platform_stdlib.h` | -`zalloc` | `os_zalloc` (ROM) | | This is **PROBABLY BROKEN**. ROM disassembly shows it only does memset on a fixed memory range. -__`zalloc`__ | __`pvPortZalloc`__ | `arduino/realtek-ambz/cores/WVariant.h` | Custom implementation in `rtl_sys.cpp` -`calloc` | `os_calloc` | ? | This one is not in ROM. I didn't dig any deeper into it. -`calloc` | `calloc_freertos` | `component/os/freertos/cmsis_os.h` | Probably not used -`calloc` | `__rtl_calloc_r` (ROM) | | Not used, as I preferred to use FreeRTOS memory management. -__`calloc`__ | __`pvPortCalloc`__ | `arduino/realtek-ambz/cores/WVariant.h` | Custom implementation in `rtl_sys.cpp` -__`realloc`__ | __`pvPortRealloc`__ | `arduino/realtek-ambz/cores/WVariant.h` | -__`free`__ | __`vPortFree`__ | `component/common/api/platform/platform_stdlib.h` | - -__Underlined__ item means that it is defined and used in code. diff --git a/docs/platform/realtek-ambz/stdlib.md b/docs/platform/realtek-ambz/stdlib.md deleted file mode 100644 index 17caa3b..0000000 --- a/docs/platform/realtek-ambz/stdlib.md +++ /dev/null @@ -1,189 +0,0 @@ -# C library - -The following is an auto-generated list of C standard library definitions included in the SDK. `Location` column contains the location of a matching symbol. - -## ctype.h - -### Character classification functions - -Definition | Value | Location ------------|------------|--------- -`isalnum` | | -`isalpha` | | -`isblank` | | -`iscntrl` | | -`isdigit` | `in_range` | -`isgraph` | | -`islower` | `in_range` | -`isprint` | `in_range` | -`ispunct` | | -`isspace` | | -`isupper` | | -`isxdigit` | | - -## stdarg.h - -Definition | Value | Location ------------|----------------------|--------- -`va_start` | `__builtin_va_start` | -`va_arg` | `__builtin_va_arg` | -`va_end` | `__builtin_va_end` | -`va_copy` | `__builtin_va_copy` | - -## stddef.h - -Definition | Value | Location ---------------|---------------------|--------- -`ptrdiff_t` | `long int` | -`size_t` | `long unsigned int` | -`max_align_t` | | -`nullptr_t` | | -`NULL` | | - -## stdint.h - -### Types - -Definition | Value | Location ------------------|----------------------|--------- -`intmax_t` | `long int` | -`uintmax_t` | `long unsigned int` | -`int8_t` | `signed char` | -`uint8_t` | `unsigned char` | -`int16_t` | `short int` | -`uint16_t` | `short unsigned int` | -`int32_t` | `int` | -`uint32_t` | `unsigned int` | -`int64_t` | `long int` | -`uint64_t` | `long unsigned int` | -`int_least8_t` | `signed char` | -`uint_least8_t` | `unsigned char` | -`int_least16_t` | `short int` | -`uint_least16_t` | `short unsigned int` | -`int_least32_t` | `int` | -`uint_least32_t` | `unsigned int` | -`int_least64_t` | `long int` | -`uint_least64_t` | `long unsigned int` | -`int_fast8_t` | `signed char` | -`uint_fast8_t` | `unsigned char` | -`int_fast16_t` | `long int` | -`uint_fast16_t` | `long unsigned int` | -`int_fast32_t` | `long int` | -`uint_fast32_t` | `long unsigned int` | -`int_fast64_t` | `long int` | -`uint_fast64_t` | `long unsigned int` | -`intptr_t` | `long int` | -`uintptr_t` | `long unsigned int` | - -## stdio.h - -### Formatted input/output - -Definition | Value | Location -------------|-----------------|----------------- -`fprintf` | | -`fscanf` | | -`printf` | `rtl_printf` | `lib_rtlstd.a` -`scanf` | | -`snprintf` | `rtl_snprintf` | `lib_rtlstd.a` -`sprintf` | `rtl_sprintf` | `lib_rtlstd.a` -`sscanf` | `_sscanf_patch` | `lib_platform.a` -`vfprintf` | | -`vfscanf` | | -`vprintf` | | -`vscanf` | | -`vsnprintf` | `rtl_vsnprintf` | `lib_rtlstd.a` -`vsprintf` | | -`vsscanf` | | - -### Error-handling - -Definition | Value | Location ------------|---------------|------------- -`clearerr` | `__sclearerr` | -`feof` | `__sfeof` | -`ferror` | `__sferror` | -`perror` | | `lib_mdns.a` - -## stdlib.h - -### String conversion - -Definition | Value | Location ------------|------------------|--------- -`atof` | | -`atoi` | `prvAtoi` | ROM -`atol` | `simple_strtol` | ROM -`atoll` | | -`strtod` | | -`strtof` | | -`strtol` | `simple_strtol` | ROM -`strtold` | | -`strtoll` | | -`strtoul` | `simple_strtoul` | ROM -`strtoull` | | - -### Pseudo-random sequence generation - -Definition | Value | Location ------------|--------|--------- -`rand` | `Rand` | ROM -`srand` | | - -### Dynamic memory management - -Definition | Value | Location ------------|----------------|--------- -`calloc` | | -`free` | `vPortFree` | SDK -`malloc` | `pvPortMalloc` | SDK -`realloc` | | - -## string.h - -### Copying - -Definition | Value | Location ------------|-----------------------|--------- -`memcpy` | `_memcpy` | ROM -`memmove` | `__rtl_memmove_v1_00` | ROM -`strcpy` | `_strcpy` | ROM -`strncpy` | `_strncpy` | ROM - -### Concatenation - -Definition | Value | Location ------------|-----------------------|--------- -`strcat` | `__rtl_strcat_v1_00` | ROM -`strncat` | `__rtl_strncat_v1_00` | ROM - -### Comparison - -Definition | Value | Location ------------|-------------|--------- -`memcmp` | `_memcmp` | ROM -`strcmp` | `prvStrCmp` | ROM -`strcoll` | | -`strncmp` | `_strncmp` | ROM -`strxfrm` | | - -### Searching - -Definition | Value | Location ------------|----------------------|--------- -`memchr` | `__rtl_memchr_v1_00` | ROM -`strchr` | `_strchr` | ROM -`strcspn` | | -`strpbrk` | `_strpbrk` | ROM -`strrchr` | | -`strspn` | | -`strstr` | `prvStrStr` | ROM -`strtok` | `prvStrtok` | ROM - -### Other - -Definition | Value | Location ------------|-------------|--------- -`memset` | `_memset` | ROM -`strerror` | | -`strlen` | `prvStrLen` | ROM diff --git a/docs/projects/esphome.md b/docs/projects/esphome.md index 12ab910..94fddf1 100644 --- a/docs/projects/esphome.md +++ b/docs/projects/esphome.md @@ -2,13 +2,13 @@ Because ESPHome does not natively support running on non-ESP chips, you need to use a fork of the project. -There are two basic ways to install and use LibreTuya-ESPHome. You can choose the option that best suits you: +There are two basic ways to install and use LibreTiny-ESPHome. You can choose the option that best suits you: - command line (CLI) - for more experienced users; compilation using CLI commands, somewhat easier to troubleshoot - ESPHome Dashboard (GUI) - for new users, might be an easy way to go; config management & compilation using web-based dashboard !!! tip - You can use LibreTuya-ESPHome for ESP32/ESP8266 compilation as well - the forked version *extends* the base, and doesn't remove any existing features. Keep in mind that you might not have latest ESPHome updates until the fork gets updated (which usually happens at most every few weeks). + You can use LibreTiny-ESPHome for ESP32/ESP8266 compilation as well - the forked version *extends* the base, and doesn't remove any existing features. Keep in mind that you might not have latest ESPHome updates until the fork gets updated (which usually happens at most every few weeks). ## Find your device's board @@ -23,13 +23,13 @@ If your board isn't listed, use one of the **Generic** boards, depending on the !!! important Read [Getting started](../getting-started/README.md) first - most importantly, the first part about installation. - **It is very important that you have the latest version of LibreTuya installed** (not `libretuya-esphome` - this is a different thing!) **so that you don't face issues that are already resolved**. + **It is very important that you have the latest version of LibreTiny installed** (not `libretiny-esphome` - this is a different thing!) **so that you don't face issues that are already resolved**. Assuming you have PlatformIO, git and Python installed: 1. Open a terminal/cmd.exe, create `esphome` directory and `cd` into it. - 2. `git clone https://github.com/kuba2k2/libretuya-esphome` - 3. `cd` into the newly created `libretuya-esphome` directory. + 2. `git clone https://github.com/kuba2k2/libretiny-esphome` + 3. `cd` into the newly created `libretiny-esphome` directory. 4. Check if it works by typing `python -m esphome` !!! tip @@ -42,17 +42,17 @@ If your board isn't listed, use one of the **Generic** boards, depending on the For this, you need Docker, Docker Compose and Python installed. After running the commands, you'll have a running ESPHome Dashboard interface that you can connect to. - 1. `git clone https://github.com/kuba2k2/libretuya-esphome` (or download the .ZIP and unpack it, not recommended) - 2. Open a terminal/cmd.exe in the cloned directory (`libretuya-esphome`). - 3. `python docker/build.py --tag libretuya --arch amd64 --build-type docker build` - this will build the Docker image of ESPHome. Change `amd64` to something else if you're using a Raspberry Pi. + 1. `git clone https://github.com/kuba2k2/libretiny-esphome` (or download the .ZIP and unpack it, not recommended) + 2. Open a terminal/cmd.exe in the cloned directory (`libretiny-esphome`). + 3. `python docker/build.py --tag libretiny --arch amd64 --build-type docker build` - this will build the Docker image of ESPHome. Change `amd64` to something else if you're using a Raspberry Pi. 4. Create a `docker-compose.yml` file in the same directory: ```yaml title="docker-compose.yml" version: "3" services: esphome: - container_name: esphome-libretuya - image: esphome/esphome-amd64:libretuya # (2)! + container_name: esphome-libretiny + image: esphome/esphome-amd64:libretiny # (2)! volumes: - ./configs:/config:rw # (1)! - /etc/localtime:/etc/localtime:ro @@ -76,7 +76,7 @@ If your board isn't listed, use one of the **Generic** boards, depending on the esphome: name: yourdevice - libretuya: + libretiny: board: wr3 # THIS IS YOUR BOARD CODE framework: version: latest @@ -102,7 +102,7 @@ If your board isn't listed, use one of the **Generic** boards, depending on the - `New Device` - `Continue` - enter name and WiFi details - - choose `LibreTuya` + - choose `LibreTiny` - choose the board that you found before - select `Skip` 3. A new config file will be added. Press `Edit` and proceed to the next section. @@ -133,10 +133,10 @@ Now, refer to the [flashing guide](../flashing/esphome.md) to learn how to uploa !!! note This part is for advanced users. You'll probably be fine with the default options. -All options from [Options & config](../reference/config.md) can be customized in the `libretuya:` block: +All options from [Options & config](../dev/config.md) can be customized in the `libretiny:` block: ```yaml title="yourdevice.yml" -libretuya: +libretiny: framework: version: latest lt_config: @@ -149,7 +149,7 @@ libretuya: Additionally, few options have their dedicated keys: ```yaml title="yourdevice.yml" -libretuya: +libretiny: framework: version: latest # verbose/trace/debug/info/warn/error/fatal diff --git a/docs/reference/lt-api.md b/docs/reference/lt-api.md deleted file mode 100644 index f051c1e..0000000 --- a/docs/reference/lt-api.md +++ /dev/null @@ -1,47 +0,0 @@ -# LibreTuya API - -## Class functions - -{% - include-markdown "../../ltapi/class_libre_tuya.md" - start="(class_libre_tuya.md)\n" - end="[More...]" -%} - -{% - include-markdown "../../ltapi/class_libre_tuya.md" - start="# Detailed Description\n" - end="## Public Functions Documentation\n" -%} - -{% - include-markdown "../../ltapi/class_libre_tuya.md" - start="## Public Functions\n" - end="# Detailed Description\n" -%} - -## Common methods - -{% - include-markdown "../../ltapi/_libre_tuya_a_p_i_8h.md" - start="## Public Functions\n" - end="## Public Functions Documentation\n" - heading-offset=1 -%} - -## Wiring custom methods - -{% - include-markdown "../../ltapi/_libre_tuya_custom_8h.md" - start="## Public Functions\n" - end="## Macros\n" -%} - -## Logger - -{% - include-markdown "../../ltapi/lt__logger_8h.md" - start="## Public Functions\n" - end="## Public Functions Documentation\n" - heading-offset=1 -%} diff --git a/docs/build_json.py b/docs/scripts/build_json.py similarity index 100% rename from docs/build_json.py rename to docs/scripts/build_json.py diff --git a/docs/markdown.py b/docs/scripts/markdown.py similarity index 100% rename from docs/markdown.py rename to docs/scripts/markdown.py diff --git a/docs/scripts/prepare_doxygen.py b/docs/scripts/prepare_doxygen.py new file mode 100644 index 0000000..b217af2 --- /dev/null +++ b/docs/scripts/prepare_doxygen.py @@ -0,0 +1,38 @@ +# Copyright (c) Kuba SzczodrzyƄski 2023-03-11. + +import re +from glob import glob +from os.path import dirname, join + +inputs_path = join(dirname(__file__), "..", "..", "cores/common/base/**/*.*") +outputs_path = join( + dirname(__file__), "..", "..", "cores/common/arduino/libraries/**/*.*" +) +inputs = glob(inputs_path, recursive=True) +outputs = glob(outputs_path, recursive=True) + +functions = {} + +for input in inputs: + with open(input, "r") as f: + code = f.read() + regex = r"\/\*\*(.+?)\*\/\n.+?\s\*?(\w+)\(.*?\);" + for match in re.finditer(regex, code, re.DOTALL): + functions[match[2]] = match[1] + +for output in outputs: + with open(output, "r") as f: + code = f.read() + regex = r"(\t*)\/\*\*.+?@copydoc (\w+)\(\)" + + def transform(match: re.Match): + docs: str = functions.get(match[2], None) + if not docs: + return match[0] + indent = "\n" + match[1] + docs = indent.join(docs.split("\n")) + return match[1] + "/** " + docs + + code = re.sub(regex, transform, code, re.DOTALL) + with open(output, "w") as f: + f.write(code) diff --git a/docs/update_docs.py b/docs/scripts/update_docs.py similarity index 82% rename from docs/update_docs.py rename to docs/scripts/update_docs.py index db90bfd..a35241c 100644 --- a/docs/update_docs.py +++ b/docs/scripts/update_docs.py @@ -1,9 +1,9 @@ # Copyright (c) Kuba SzczodrzyƄski 2022-05-31. import sys -from os.path import dirname, join +from os.path import dirname, isfile, join -sys.path.append(join(dirname(__file__), "..")) +sys.path.append(join(dirname(__file__), "..", "..")) import re from typing import Dict, List, Set @@ -15,7 +15,7 @@ from ltchiptool.util.fileio import readjson, readtext from ltchiptool.util.misc import sizeof from markdown import Markdown -OUTPUT = join(dirname(__file__), "status") +OUTPUT = join(dirname(__file__), "..", "status") def load_chip_type_h() -> str: @@ -23,10 +23,11 @@ def load_chip_type_h() -> str: join( dirname(__file__), "..", - "arduino", - "libretuya", - "core", - "ChipType.h", + "..", + "cores", + "common", + "base", + "lt_types.h", ) ) code = re.sub(r"//.+", "", code) @@ -57,7 +58,7 @@ def get_family_mcus() -> Set[str]: def get_family_names() -> Set[str]: - return set(family.short_name for family in Family.get_all()) + return set(family.short_name for family in Family.get_all() if family.is_chip) def get_board_mcus(boards: List[Board]) -> Set[str]: @@ -70,8 +71,8 @@ def get_board_mcus(boards: List[Board]) -> Set[str]: def get_enum_keys(code: str, name: str) -> Set[str]: code = code.replace("\t", " ") - code = code.partition(f"enum {name}")[2] - code = code.partition(";")[0] + code = code.partition(f"{name};")[0] + code = code.rpartition("{")[2] code = code.strip().strip("{}").strip() code = [line.strip().strip(",").strip() for line in code.split("\n")] code = filter(None, code) @@ -79,11 +80,11 @@ def get_enum_keys(code: str, name: str) -> Set[str]: def get_enum_mcus(code: str) -> Set[str]: - return get_enum_keys(code, "ChipType") + return get_enum_keys(code, "lt_cpu_model_t") def get_enum_families(code: str) -> Set[str]: - return set(family[2:] for family in get_enum_keys(code, "ChipFamily")) + return set(family[2:] for family in get_enum_keys(code, "lt_cpu_family_t")) def board_json_sort(tpl): @@ -218,36 +219,51 @@ def write_families(): rows = [] for family in Family.get_all(): + # TODO update the table to support parent-child relationship + if not family.is_chip: + continue + docs = None + for f in family.inheritance: + readme = join(dirname(__file__), "..", "platform", f.name, "README.md") + if isfile(readme): + docs = f"../{f.name}/" row = [ # Title "[{}]({})".format( family.description, - family.url, + docs, ) - if family.url + if docs else family.description, # Name (parent) - f"`{family.name or '-'}`" - if not family.parent - else f"`{family.name}` (`{family.parent}`)", + family.is_supported + and ( + f"`{family.name}`" + if not family.parent + else f"`{family.name}` (`{family.parent_name}`)" + ) + or "`-`", # Code - f"`{family.code or '-'}`" - if not family.parent - else f"`{family.code}` (`{family.parent_code}`)", + family.is_supported + and ( + f"`{family.code}`" + if not family.parent + else f"`{family.code}` (`{family.parent_code}`)" + ) + or "`-`", # Short name & ID "`{}` (0x{:X})".format( family.short_name, family.id, ), # Arduino Core - "✔" if family.has_arduino_core else "❌", + "✔" if family.is_supported and family.has_arduino_core else "❌", # Source SDK - "`{}` ([{}]({}))".format( - family.framework, - family.sdk_name, - family.sdk, + "[`{}`]({})".format( + family.target_package, + f"https://github.com/libretiny-eu/{family.target_package}", ) - if family.sdk + if family.target_package else "-", ] rows.append(row) @@ -256,7 +272,7 @@ def write_families(): def write_boards_list(boards: List[Board]): - md = Markdown(dirname(__file__), join("..", "boards", "SUMMARY")) + md = Markdown(join(dirname(__file__), ".."), join("..", "boards", "SUMMARY")) items = [] for board in boards: symbol = get_board_symbol(board) @@ -322,7 +338,7 @@ if __name__ == "__main__": "boards_tuya_all", ] for name in boards_all: - file = join(dirname(__file__), f"{name}.json") + file = join(dirname(__file__), "..", f"{name}.json") data = readjson(file) write_unsupported_boards( series=data, diff --git a/docs/status/supported.md b/docs/status/supported.md index 3aed119..a7ec757 100644 --- a/docs/status/supported.md +++ b/docs/status/supported.md @@ -24,9 +24,9 @@ If you have an unsupported chip, feel free to reach out using Issues or on the D A list of chip families currently supported by this project. !!! note - The term *family* was chosen over *platform*, in order to reduce possible confusion between LibreTuya supported "platforms" and PlatformIO's "platform", as an entire package. *Family* is also more compatible with the UF2 term. + The term *family* was chosen over *platform*, in order to reduce possible confusion between LibreTiny supported "platforms" and PlatformIO's "platform", as an entire package. *Family* is also more compatible with the UF2 term. -The following list corresponds to UF2 OTA format family names, and is also [available as JSON](../../families.json). The IDs are also present in [ChipType.h](../../ltapi/_chip_type_8h_source.md). +The following list corresponds to UF2 OTA format family names, and is also [available as JSON](../../families.json). The IDs are also present in [lt_Types.h](../../ltapi/lt__types_8h.md). {% include-markdown "supported_families.md" diff --git a/docs/status/supported_boards.md b/docs/status/supported_boards.md deleted file mode 100644 index 7182c61..0000000 --- a/docs/status/supported_boards.md +++ /dev/null @@ -1,39 +0,0 @@ - - -Name | MCU | Flash | RAM | Pins* | Wi-Fi | BLE | ZigBee | Family name ---------------------------------------------------------------------------|-----------|-------|---------|-------------|-------|-----|--------|---------------- -**Generic** | | | | | | | | -[BK7231N (Tuya QFN32)](../../boards/generic-bk7231n-qfn32-tuya/README.md) | BK7231N | 2 MiB | 256 KiB | 19 (19 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[BK7231T (Tuya QFN32)](../../boards/generic-bk7231t-qfn32-tuya/README.md) | BK7231T | 2 MiB | 256 KiB | 19 (19 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -[BK7252](../../boards/generic-bk7252/README.md) | BK7252 | 4 MiB | 512 KiB | 38 (38 I/O) | ✔ | ✔ | ❌ | `beken-7251` -[RTL8710BN (2M/468k)](../../boards/generic-rtl8710bn-2mb-468k/README.md) | RTL8710BN | 2 MiB | 256 KiB | 18 (18 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[RTL8710BN (2M/788k)](../../boards/generic-rtl8710bn-2mb-788k/README.md) | RTL8710BN | 2 MiB | 256 KiB | 18 (18 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[RTL8710BX (4M/980k)](../../boards/generic-rtl8710bx-4mb-980k/README.md) | RTL8710BX | 4 MiB | 256 KiB | 17 (17 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[RTL8720CF (2M/992k)](../../boards/generic-rtl8720cf-2mb-992k/README.md) | RTL8720CF | 2 MiB | 256 KiB | 20 (20 I/O) | ✔ | ✔ | ❌ | `realtek-ambz2` -**Ai-Thinker Co., Ltd.** | | | | | | | | -[BW12](../../boards/bw12/README.md) | RTL8710BX | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[BW15](../../boards/bw15/README.md) | RTL8720CF | 2 MiB | 256 KiB | 16 (13 I/O) | ✔ | ✔ | ❌ | `realtek-ambz2` -**Tuya Inc.** | | | | | | | | -[CB2L](../../boards/cb2l/README.md) | BK7231N | 2 MiB | 256 KiB | 7 (5 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[CB2S](../../boards/cb2s/README.md) | BK7231N | 2 MiB | 256 KiB | 11 (8 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[CB3L](../../boards/cb3l/README.md) | BK7231N | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[CB3S](../../boards/cb3s/README.md) | BK7231N | 2 MiB | 256 KiB | 22 (16 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[CB3SE](../../boards/cb3se/README.md) | BK7231N | 2 MiB | 256 KiB | 22 (17 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[WB2L](../../boards/wb2l/README.md) | BK7231T | 2 MiB | 256 KiB | 7 (5 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -[WB2S](../../boards/wb2s/README.md) | BK7231T | 2 MiB | 256 KiB | 11 (8 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -[WB3L](../../boards/wb3l/README.md) | BK7231T | 2 MiB | 256 KiB | 21 (17 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -[WB3S](../../boards/wb3s/README.md) | BK7231T | 2 MiB | 256 KiB | 22 (16 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -[WR2](../../boards/wr2/README.md) | RTL8710BN | 2 MiB | 256 KiB | 11 (8 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR2E](../../boards/wr2e/README.md) | RTL8710BN | 2 MiB | 256 KiB | 11 (8 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR3](../../boards/wr3/README.md) | RTL8710BN | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR3E](../../boards/wr3e/README.md) | RTL8710BN | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR3N](../../boards/wr3n/README.md) | RTL8710BN | 2 MiB | 256 KiB | 16 (10 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR2L](../../boards/wr2l/README.md) | RTL8710BX | 2 MiB | 256 KiB | 7 (5 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR2LE](../../boards/wr2le/README.md) | RTL8710BX | 2 MiB | 256 KiB | 7 (5 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR3L](../../boards/wr3l/README.md) | RTL8710BX | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -[WR3LE](../../boards/wr3le/README.md) | RTL8710BX | 2 MiB | 256 KiB | 16 (12 I/O) | ✔ | ❌ | ❌ | `realtek-ambz` -**Unknown** | | | | | | | | -[LSC LMA35](../../boards/lsc-lma35/README.md) | BK7231N | 2 MiB | 256 KiB | 22 (15 I/O) | ✔ | ✔ | ❌ | `beken-7231n` -[LSC LMA35 T](../../boards/lsc-lma35-t/README.md) | BK7231T | 2 MiB | 256 KiB | 22 (15 I/O) | ✔ | ✔ | ❌ | `beken-7231u` -**N/A** | | | | | | | | -[Native](../../boards/generic-native/README.md) | NATIVE | 4 MiB | 4 MiB | - | ✔ | ❌ | ❌ | `host-native` diff --git a/docs/status/supported_chips.md b/docs/status/supported_chips.md deleted file mode 100644 index 7a0d597..0000000 --- a/docs/status/supported_chips.md +++ /dev/null @@ -1,13 +0,0 @@ - - -- BK7231N -- BK7231S -- BK7231T -- BK7231U -- BK7251 -- BK7252 -- BL2028N -- NATIVE -- RTL8710BN -- RTL8710BX -- RTL8720CF diff --git a/docs/status/supported_families.md b/docs/status/supported_families.md deleted file mode 100644 index 3c17c61..0000000 --- a/docs/status/supported_families.md +++ /dev/null @@ -1,14 +0,0 @@ - - -Title | Name (parent) | Code | Short name & ID | Arduino Core | Source SDK ---------------------------------------------------------------------------|---------------------------------|----------------------|-------------------------|--------------|---------------------------------------------------------------------------------- -Realtek Ameba1 | `-` | `-` | `RTL8710A` (0x9FFFD543) | ❌ | - -[Realtek AmebaZ](https://www.amebaiot.com/en/amebaz/) | `realtek-ambz` (`realtek-amb`) | `ambz` (`amb`) | `RTL8710B` (0x22E0D6FC) | ✔ | `framework-realtek-amb1` ([amb1_sdk](https://github.com/ambiot/amb1_sdk)) -[Realtek AmebaZ2](https://www.amebaiot.com/en/amebaz2/) | `realtek-ambz2` (`realtek-amb`) | `ambz2` (`amb`) | `RTL8720C` (0xE08F7564) | ❌ | `framework-realtek-ambz2` ([ambz2_sdk](https://github.com/ambiot/ambz2_sdk)) -Realtek AmebaD | `-` | `-` | `RTL8720D` (0x3379CFE2) | ❌ | - -[Beken 7231U/7231T](http://www.bekencorp.com/en/goods/detail/cid/13.html) | `beken-7231u` (`beken-72xx`) | `bk7231u` (`bk72xx`) | `BK7231U` (0x675A40B0) | ✔ | `framework-beken-bdk` ([bdk_freertos](https://github.com/bekencorp/bdk_freertos)) -[Beken 7231N](http://www.bekencorp.com/en/goods/detail/cid/39.html) | `beken-7231n` (`beken-72xx`) | `bk7231n` (`bk72xx`) | `BK7231N` (0x7B3EF230) | ✔ | `framework-beken-bdk` ([bdk_freertos](https://github.com/bekencorp/bdk_freertos)) -[Beken 7251/7252](http://www.bekencorp.com/en/goods/detail/cid/21.html) | `beken-7251` (`beken-72xx`) | `bk7251` (`bk72xx`) | `BK7251` (0x6A82CC42) | ✔ | `framework-beken-bdk` ([bdk_freertos](https://github.com/bekencorp/bdk_freertos)) -Boufallo 602 | `-` | `-` | `BL602` (0xDE1270B7) | ❌ | - -Xradiotech 809 | `-` | `-` | `XR809` (0x51E903A8) | ❌ | - -Native host architecture | `host-native` | `native` | `NATIVE` (0xDEADBEEF) | ❌ | - diff --git a/docs/status/unsupported_boards_tuya_all.md b/docs/status/unsupported_boards_tuya_all.md deleted file mode 100644 index fe61c1b..0000000 --- a/docs/status/unsupported_boards_tuya_all.md +++ /dev/null @@ -1,53 +0,0 @@ - - -Name | MCU | Flash | RAM | Pins | Wi-Fi | BLE | ZigBee ----------------|------------|-------|---------|------|-------|-----|------- -**AXY Series** | | | | | | | -AXY2S | ECR6600 | 2 MiB | 512 KiB | 11 | ✔ | ✔ | ❌ -AXY3L | ECR6600 | 2 MiB | 512 KiB | 18 | ✔ | ✔ | ❌ -AXY3S | ECR6600 | 2 MiB | 512 KiB | 22 | ✔ | ✔ | ❌ -AXYU | ECR6600 | 2 MiB | 512 KiB | 21 | ✔ | ✔ | ❌ -**CB Series** | | | | | | | -CB1S | BK7231N | 2 MiB | 256 KiB | 18 | ✔ | ✔ | ❌ -CB8P | BK7231N | 2 MiB | 256 KiB | 10 | ✔ | ✔ | ❌ -CBLC5 | BK7231N | 2 MiB | 256 KiB | 15 | ✔ | ✔ | ❌ -CBLC9 | BK7231N | 2 MiB | 256 KiB | 8 | ✔ | ✔ | ❌ -CBU | BK7231N | 2 MiB | 256 KiB | 21 | ✔ | ✔ | ❌ -**CR Series** | | | | | | | -CR2S | RTL8720CM | 4 MiB | 4 MiB | 11 | ✔ | ✔ | ❌ -CR3L | RTL8720CM | 4 MiB | 4 MiB | 18 | ✔ | ✔ | ❌ -CRG1 | RTL8720CM | 4 MiB | 4 MiB | 25 | ✔ | ✔ | ❌ -**WB Series** | | | | | | | -WB1S | BK7231T | 2 MiB | 256 KiB | 18 | ✔ | ✔ | ❌ -WB8P | BK7231T | 2 MiB | 256 KiB | 10 | ✔ | ✔ | ❌ -WBLC5 | BK7231T | 2 MiB | 256 KiB | 15 | ✔ | ✔ | ❌ -WBLC9 | BK7231T | 2 MiB | 256 KiB | 8 | ✔ | ✔ | ❌ -**WBR Series** | | | | | | | -WBR1 | RTL8720CF | 2 MiB | 256 KiB | 18 | ✔ | ✔ | ❌ -WBR2 | RTL8720CF | 2 MiB | 256 KiB | 11 | ✔ | ✔ | ❌ -WBR2L | RTL8720CF | 2 MiB | 256 KiB | 7 | ✔ | ✔ | ❌ -WBR3 | RTL8720CF | 2 MiB | 256 KiB | 16 | ✔ | ✔ | ❌ -WBR3L | RTL8720CF | 2 MiB | 256 KiB | 18 | ✔ | ✔ | ❌ -WBR3S | RTL8720CF | 2 MiB | 256 KiB | 22 | ✔ | ✔ | ❌ -WBRU | RTL8720CF | 2 MiB | 256 KiB | 21 | ✔ | ✔ | ❌ -WBR3N | RTL8720CS | 4 MiB | 512 KiB | 16 | ✔ | ✔ | ❌ -WBRG1 | RTL8720CSM | 8 MiB | 4 MiB | 25 | ✔ | ✔ | ❌ -WBR1D | RTL8720DN | 4 MiB | 512 KiB | 18 | ✔ | ✔ | ❌ -WBR2D | RTL8720DN | 4 MiB | 512 KiB | 11 | ✔ | ✔ | ❌ -WBR3D | RTL8720DN | 4 MiB | 512 KiB | 16 | ✔ | ✔ | ❌ -WBR3T | RTL8720DN | 4 MiB | 512 KiB | 16 | ✔ | ✔ | ❌ -**WL Series** | | | | | | | -WL2H-U | LN882H | ? | 296 KiB | 21 | ✔ | ✔ | ❌ -**WR Series** | | | | | | | -WR1 | RTL8710BN | 1 MiB | 256 KiB | 18 | ✔ | ❌ | ❌ -WR1E | RTL8710BN | 2 MiB | 256 KiB | 18 | ✔ | ❌ | ❌ -WR4 | RTL8710BN | 1 MiB | 256 KiB | 16 | ✔ | ❌ | ❌ -WR5E | RTL8710BN | 2 MiB | 256 KiB | 15 | ✔ | ❌ | ❌ -WR6 | RTL8710BN | 2 MiB | 256 KiB | 14 | ✔ | ❌ | ❌ -WR6-H | RTL8710BN | 2 MiB | 256 KiB | 14 | ✔ | ❌ | ❌ -WRG1 | RTL8711AM | 4 MiB | 2 MiB | 25 | ✔ | ❌ | ❌ -**WT Series** | | | | | | | -WT3 | T2 | 2 MiB | 256 KiB | 16 | ✔ | ✔ | ❌ -**XR Series** | | | | | | | -XR1 | XR809 | 2 MiB | 384 KiB | 18 | ✔ | ❌ | ❌ -XR3 | XR809 | 2 MiB | 384 KiB | 16 | ✔ | ❌ | ❌ diff --git a/docs/style.css b/docs/style.css index fddc2c6..c21e408 100644 --- a/docs/style.css +++ b/docs/style.css @@ -12,9 +12,21 @@ article a[href^="https://"]::after { display: inline-block; } -a[href^="https://docs.libretuya.ml"]::after, +a[href^="https://docs.libretiny.eu"]::after, a[href^="http://localhost"]::after, a[href^="https://"].md-button::after, div[align="center"] a[href^="https://"]::after { display: none !important; } + +/* ugly but it works ÂŻ\_(ツ)_/ÂŻ */ +a[href="SUMMARY/"], +a[href="../SUMMARY/"], +a[href="../../SUMMARY/"], +a[href="../../../SUMMARY/"], +a[href="../../../../SUMMARY/"], +a[href="../../../../../SUMMARY/"] +{ + height: 8px; + pointer-events: none; +} diff --git a/examples/PinScan/README.md b/examples/PinScan/README.md index 56cd313..d0e710e 100644 --- a/examples/PinScan/README.md +++ b/examples/PinScan/README.md @@ -9,7 +9,7 @@ By using a simple TUI (text user interface), you can check which I/O pins corres Uploading the example and opening up a terminal (e.g. PuTTY) presents this menu: ``` -LibreTuya v0.8.0, PinScan v1.0 +LibreTiny v0.8.0, PinScan v1.0 Board: cb2s I/O count: 11 Digital I/O count: 11 diff --git a/examples/PinScan/platformio.ini b/examples/PinScan/platformio.ini index 35a5baa..c1220b1 100644 --- a/examples/PinScan/platformio.ini +++ b/examples/PinScan/platformio.ini @@ -1,5 +1,5 @@ [env] -platform = libretuya +platform = libretiny framework = arduino [env:bk7231n] diff --git a/examples/PinScan/src/help.cpp b/examples/PinScan/src/help.cpp index 48e8e74..e7e6aa8 100644 --- a/examples/PinScan/src/help.cpp +++ b/examples/PinScan/src/help.cpp @@ -7,7 +7,7 @@ void printHelp(uint8_t mode) { switch (mode) { case '\0': stream->setTimeout(10000); - stream->println("LibreTuya v" LT_VERSION_STR ", PinScan v" EXAMPLE_VER); + stream->println("LibreTiny v" LT_VERSION_STR ", PinScan v" EXAMPLE_VER); stream->println("Board: " LT_BOARD_STR); stream->print("I/O count: "); stream->println(PINS_COUNT); diff --git a/external-libs.json b/external-libs.json new file mode 100644 index 0000000..4cb871b --- /dev/null +++ b/external-libs.json @@ -0,0 +1,125 @@ +{ + "$schema": "./external-libs.schema.json", + "flashdb": { + "package": "library-flashdb", + "sources": [ + "+", + "+" + ], + "includes": [ + "+", + "+" + ] + }, + "printf": { + "package": "library-printf", + "sources": [ + "+" + ], + "includes": [ + "+" + ], + "flags": [ + "-Wno-maybe-uninitialized" + ], + "linkflags": [ + "-Wl,-wrap,printf", + "-Wl,-wrap,sprintf", + "-Wl,-wrap,vsprintf", + "-Wl,-wrap,snprintf", + "-Wl,-wrap,vsnprintf", + "-Wl,-wrap,vprintf", + "-Wl,-wrap,puts", + "-Wl,-wrap,putchar" + ], + "defines": { + "PRINTF_INCLUDE_CONFIG_H": "1" + } + }, + "ltchiptool": { + "package": "tool-ltchiptool", + "sources": [ + "+" + ], + "includes": [ + "+<.>" + ] + }, + "arduino-api": { + "package": "framework-arduino-api", + "sources": [ + "+", + "+", + "+", + "+", + "+", + "+" + ], + "includes": [ + "+<.>", + "+" + ] + }, + "freertos": { + "package": "library-freertos", + "sources": [ + "+" + ], + "includes": [ + "+" + ], + "defines": { + "FREERTOS_PORT_${FREERTOS_PORT_DEFINE}": "1" + } + }, + "freertos-port": { + "package": "library-freertos-port", + "sources": [ + "+<./$FREERTOS_PORT/*.c>" + ], + "includes": [ + "!<./$FREERTOS_PORT>" + ], + "defines": { + "FREERTOS_PORT_${FREERTOS_PORT_DEFINE}": "1" + } + }, + "lwip-amb1": { + "package": "library-lwip", + "sources": [ + "+", + "+", + "+", + "+", + "+", + "+", + "+", + "+", + "+" + ], + "includes": [ + "+", + "+", + "+", + "+" + ] + }, + "lwip-bdk": { + "package": "library-lwip", + "sources": [ + "+", + "+", + "+", + "+", + "+", + "+", + "+", + "+" + ], + "includes": [ + "+", + "+", + "+" + ] + } +} diff --git a/external-libs.schema.json b/external-libs.schema.json new file mode 100644 index 0000000..87fb8a3 --- /dev/null +++ b/external-libs.schema.json @@ -0,0 +1,65 @@ +{ + "type": "object", + "properties": { + "$schema": { + "type": "string" + } + }, + "patternProperties": { + "^[a-z0-9-_]+$": { + "type": "object", + "properties": { + "package": { + "type": "string", + "pattern": "^(tool|library|framework)-[a-z0-9-]+$" + }, + "sources": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[!+-]<[$\\w/*.]+>$" + } + }, + "includes": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[!+-]<[$\\w/*.]+>$" + } + }, + "flags": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "linkflags": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[^\\s]+$" + } + }, + "defines": { + "type": "object", + "patternProperties": { + "^[A-Za-z0-9_]+$": { + "type": [ + "string", + "number" + ] + } + } + } + }, + "additionalProperties": false, + "required": [ + "package", + "sources", + "includes" + ] + } + }, + "additionalProperties": false +} diff --git a/families.json b/families.json index 01ae01f..3cbbd3a 100644 --- a/families.json +++ b/families.json @@ -1,117 +1,115 @@ -[ - { +{ + "$schema": "./families.schema.json", + "realtek-amb": { + "parent": null, + "code": "amb", + "description": "Realtek Ameba" + }, + "realtek-amb1": { + "parent": "realtek-amb", + "code": "amb1", + "description": "Realtek Ameba1", "id": "0x9FFFD543", "short_name": "RTL8710A", - "description": "Realtek Ameba1" + "mcus": [] }, - { - "id": "0x22E0D6FC", - "short_name": "RTL8710B", - "description": "Realtek AmebaZ", - "parent_description": "Realtek Ameba", - "name": "realtek-ambz", + "realtek-ambz": { "parent": "realtek-amb", "code": "ambz", - "parent_code": "amb", - "url": "https://www.amebaiot.com/en/amebaz/", - "sdk": "https://github.com/ambiot/amb1_sdk", - "framework": "framework-realtek-amb1", + "description": "Realtek AmebaZ", + "id": "0x22E0D6FC", + "short_name": "RTL8710B", + "package": "framework-realtek-amb1", "mcus": [ "RTL8710BN", "RTL8710BX" ] }, - { - "id": "0xE08F7564", - "short_name": "RTL8720C", - "description": "Realtek AmebaZ2", - "parent_description": "Realtek Ameba", - "name": "realtek-ambz2", + "realtek-ambz2": { "parent": "realtek-amb", "code": "ambz2", - "parent_code": "amb", - "url": "https://www.amebaiot.com/en/amebaz2/", - "sdk": "https://github.com/ambiot/ambz2_sdk", - "framework": "framework-realtek-ambz2", + "description": "Realtek AmebaZ2", + "id": "0xE08F7564", + "short_name": "RTL8720C", + "package": "framework-realtek-ambz2", "mcus": [ "RTL8720CF" ] }, - { + "realtek-ambd": { + "parent": "realtek-amb", + "code": "ambd", + "description": "Realtek AmebaD", "id": "0x3379CFE2", "short_name": "RTL8720D", - "description": "Realtek AmebaD" + "mcus": [] }, - { + "beken-72xx": { + "parent": null, + "code": "bk72xx", + "description": "Beken 72xx" + }, + "beken-72xx-gen1": { + "parent": "beken-72xx", + "code": "bk72xxgen1", + "description": "Beken 72xx (ARM)", + "package": "framework-beken-bdk" + }, + "beken-72xx-gen2": { + "parent": "beken-72xx", + "code": "bk72xxgen2", + "description": "Beken 72xx (RISC-V & ARM)" + }, + "beken-7231u": { + "parent": "beken-72xx-gen1", + "code": "bk7231u", + "description": "Beken 7231U/7231T", "id": "0x675A40B0", "short_name": "BK7231U", - "description": "Beken 7231U/7231T", - "parent_description": "Beken 72xx", - "name": "beken-7231u", - "parent": "beken-72xx", - "code": "bk7231u", - "parent_code": "bk72xx", - "url": "http://www.bekencorp.com/en/goods/detail/cid/13.html", - "sdk": "https://github.com/bekencorp/bdk_freertos", - "framework": "framework-beken-bdk", "mcus": [ "BK7231T", "BK7231S", "BK7231U" ] }, - { + "beken-7231n": { + "parent": "beken-72xx-gen1", + "description": "Beken 7231N", + "code": "bk7231n", "id": "0x7B3EF230", "short_name": "BK7231N", - "description": "Beken 7231N", - "parent_description": "Beken 72xx", - "name": "beken-7231n", - "parent": "beken-72xx", - "code": "bk7231n", - "parent_code": "bk72xx", - "url": "http://www.bekencorp.com/en/goods/detail/cid/39.html", - "sdk": "https://github.com/bekencorp/bdk_freertos", - "framework": "framework-beken-bdk", "mcus": [ "BK7231N", "BL2028N" ] }, - { + "beken-7251": { + "parent": "beken-72xx-gen1", + "code": "bk7251", + "description": "Beken 7251/7252", "id": "0x6A82CC42", "short_name": "BK7251", - "description": "Beken 7251/7252", - "parent_description": "Beken 72xx", - "name": "beken-7251", - "parent": "beken-72xx", - "code": "bk7251", - "parent_code": "bk72xx", - "url": "http://www.bekencorp.com/en/goods/detail/cid/21.html", - "sdk": "https://github.com/bekencorp/bdk_freertos", - "framework": "framework-beken-bdk", "mcus": [ "BK7251", "BK7252" ] }, - { + "boufallo-bl678": { + "parent": null, + "code": "bl678", + "description": "Boufallo BL6xx/BL7xx/BL8xx" + }, + "boufallo-bl60x": { + "parent": "boufallo-bl678", + "code": "bl60x", + "description": "Boufallo BL602/BL604", "id": "0xDE1270B7", - "short_name": "BL602", - "description": "Boufallo 602" + "short_name": "BL60X", + "mcus": [] }, - { - "id": "0x51E903A8", - "short_name": "XR809", - "description": "Xradiotech 809" - }, - { - "id": "0xDEADBEEF", - "short_name": "NATIVE", - "description": "Native host architecture", - "name": "host-native", - "code": "native", - "mcus": [ - "NATIVE" - ] + "winnermicro-iot": { + "parent": null, + "code": "wmiot", + "description": "WinnerMicro W60x/W800x" } -] +} diff --git a/families.schema.json b/families.schema.json new file mode 100644 index 0000000..0254022 --- /dev/null +++ b/families.schema.json @@ -0,0 +1,55 @@ +{ + "type": "object", + "properties": { + "$schema": { + "type": "string" + } + }, + "patternProperties": { + "^[a-z0-9-]+$": { + "type": "object", + "properties": { + "parent": { + "type": [ + "string", + "null" + ], + "pattern": "^[a-z0-9-]+$" + }, + "code": { + "type": "string", + "pattern": "^[a-z0-9]+$" + }, + "description": { + "type": "string" + }, + "id": { + "type": "string", + "pattern": "^0x[0-9A-F]{8}$" + }, + "short_name": { + "type": "string", + "pattern": "^[A-Z0-9]+$" + }, + "package": { + "type": "string", + "pattern": "^framework-[a-z0-9-]+$" + }, + "mcus": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[A-Z0-9]+$" + } + } + }, + "additionalProperties": false, + "required": [ + "parent", + "code", + "description" + ] + } + }, + "additionalProperties": false +} diff --git a/mkdocs.yml b/mkdocs.yml index 0f2bfec..0329105 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,8 +1,8 @@ -site_name: LibreTuya +site_name: LibreTiny docs_dir: . -site_url: https://docs.libretuya.ml/ -repo_url: https://github.com/kuba2k2/libretuya +site_url: https://docs.libretiny.eu/ +repo_url: https://github.com/kuba2k2/libretiny theme: name: material @@ -24,9 +24,10 @@ plugins: projects: # project names must be alphanumeric, else snippets won't work ltapi: - src-dirs: arduino/libretuya/ + src-dirs: cores/common/ doxy-cfg: - PREDEFINED: __cplusplus + OPTIMIZE_OUTPUT_FOR_C: YES + PREDEFINED: __cplusplus DOXYGEN=1 CASE_SENSE_NAMES: NO save-api: . - literate-nav: @@ -34,11 +35,6 @@ plugins: - section-index - include-markdown - search - - git-revision-date-localized: - type: timeago - enable_creation_date: true - exclude: - - ltapi/* extra_css: - docs/style.css diff --git a/platform.json b/platform.json index a980627..46cd823 100644 --- a/platform.json +++ b/platform.json @@ -1,61 +1,46 @@ { - "name": "libretuya", - "title": "LibreTuya", - "description": "Free your Tuya IoT modules.", + "name": "libretiny", + "title": "LibreTiny", + "description": "PlatformIO development platform for IoT modules", "repository": { "type": "git", - "url": "https://github.com/kuba2k2/platformio-libretuya" + "url": "https://github.com/kuba2k2/platformio-libretiny" }, - "version": "0.13.0", + "version": "1.0.0-alpha.1", "frameworks": { + "base": { + "title": "Base Framework (SDK only)", + "script": "builder/frameworks/base.py" + }, "arduino": { - "title": "Generic Arduino framework", + "title": "Arduino Framework", "script": "builder/frameworks/arduino.py" - }, - "realtek-ambz-sdk": { - "tilte": "Realtek AmebaZ - SDK", - "package": "framework-realtek-amb1", - "script": "builder/frameworks/realtek-ambz-sdk.py" - }, - "realtek-ambz-arduino": { - "tilte": "Realtek AmebaZ - Arduino", - "package": "framework-realtek-amb1", - "script": "builder/frameworks/realtek-ambz-arduino.py" - }, - "realtek-ambz2-sdk": { - "tilte": "Realtek AmebaZ2 - SDK", - "package": "framework-realtek-ambz2", - "script": "builder/frameworks/realtek-ambz2-sdk.py" - }, - "beken-72xx-sdk": { - "title": "Beken 72XX - SDK", - "package": "framework-beken-bdk", - "script": "builder/frameworks/beken-72xx-sdk.py" - }, - "beken-72xx-arduino": { - "title": "Beken 72XX - Arduino", - "package": "framework-beken-bdk", - "script": "builder/frameworks/beken-72xx-arduino.py" } }, "packages": { "framework-realtek-amb1": { "type": "framework", "optional": true, - "version": "https://github.com/libretuya/framework-realtek-amb1#v2022.06.21", + "version": "https://github.com/libretiny-eu/framework-realtek-amb1#v2022.06.21", + "version_prefix": true, "toolchains": { "any": "gccarmnoneeabi@~1.100301.0" }, "libraries": { - "lwip": [ - "v2.1.3-amb1" - ] + "freertos": "8.1.2", + "lwip": { + "1.4.1": "1.4.1-amb1", + "2.0.0": "2.0.0-amb1", + "2.1.3": "2.1.3-amb1", + "default": "2.1.3-amb1" + } } }, "framework-realtek-ambz2": { "type": "framework", "optional": true, - "version": "https://github.com/libretuya/framework-realtek-ambz2#v2022.11.17", + "version": "https://github.com/libretiny-eu/framework-realtek-ambz2#v2022.11.17", + "version_prefix": true, "toolchains": { "any": "gccarmnoneeabi@~1.100301.0" } @@ -63,55 +48,47 @@ "framework-beken-bdk": { "type": "framework", "optional": true, - "version": "https://github.com/libretuya/framework-beken-bdk#v2021.06.07", + "version": "https://github.com/libretiny-eu/framework-beken-bdk#v2021.06.07", + "version_prefix": true, "toolchains": { - "any":"gccarmnoneeabi@~1.100301.0" + "any": "gccarmnoneeabi@~1.100301.0" }, "libraries": { - "lwip": [ - "v2.1.3-bdk" - ] + "freertos": "9.0.0", + "lwip": { + "2.0.2": "2.0.2-bdk", + "2.1.0": "2.1.0-bdk", + "2.1.3": "2.1.3-bdk", + "default": "2.1.3-bdk" + } } }, "framework-arduino-api": { "type": "framework", "optional": true, - "version": "https://github.com/libretuya/ArduinoCore-API#3a4cbfc", - "manifest": { - "description": "Hardware independent layer of the Arduino cores" - }, - "libraries": { - "flashdb": [ - "03500fa" - ], - "printf": [ - "v6.0.0" - ] - } + "version": "https://github.com/libretiny-eu/ArduinoCore-API#2022.08.24" }, "library-lwip": { "type": "framework", "optional": true, - "base_url": "https://github.com/libretuya/lwip", - "manifest": { - "description": "lwIP - A Lightweight TCPIP stack" - } + "base_url": "https://github.com/libretiny-eu/lwip" + }, + "library-freertos": { + "type": "framework", + "optional": true, + "base_url": "https://github.com/libretiny-eu/library-freertos" + }, + "library-freertos-port": { + "type": "framework", + "version": "https://github.com/libretiny-eu/library-freertos-port#2023.03.13" }, "library-flashdb": { "type": "framework", - "optional": true, - "base_url": "https://github.com/armink/FlashDB", - "manifest": { - "description": "An ultra-lightweight database that supports key-value and time series data" - } + "version": "https://github.com/libretiny-eu/library-flashdb#1.2.0" }, "library-printf": { "type": "framework", - "optional": true, - "base_url": "https://github.com/eyalroz/printf", - "manifest": { - "description": "Tiny, fast(ish), self-contained and fully loaded printf, sprinf etc. implementation, mainly for embedded systems." - } + "version": "https://github.com/libretiny-eu/library-printf#6.1.0" }, "toolchain-gccarmnoneeabi": { "type": "toolchain", @@ -124,7 +101,8 @@ }, "tool-ltchiptool": { "type": "uploader", - "version": "https://github.com/libretuya/ltchiptool#v2.0.2", + "version": "https://github.com/libretiny-eu/ltchiptool#v4.0.0", + "version_prefix": true, "note": "This is used only for C/C++ code from ltchiptool." }, "tool-openocd": { diff --git a/platform.py b/platform.py index 6ec5ffd..82ac785 100644 --- a/platform.py +++ b/platform.py @@ -2,22 +2,22 @@ import importlib import json +import os import platform import sys from os import system -from os.path import dirname, join -from typing import Dict +from os.path import dirname +from typing import Dict, List +import click from platformio.debug.config.base import DebugConfigBase from platformio.debug.exception import DebugInvalidOptionsError -from platformio.package.exception import MissingPackageManifestError -from platformio.package.manager.base import BasePackageManager -from platformio.package.meta import PackageItem, PackageSpec +from platformio.package.meta import PackageItem from platformio.platform.base import PlatformBase from platformio.platform.board import PlatformBoardConfig from semantic_version import SimpleSpec, Version -LTCHIPTOOL_VERSION = "^3.0.2" +LTCHIPTOOL_VERSION = "^4.0.0" # Install & import tools @@ -26,8 +26,8 @@ def check_ltchiptool(install: bool): # update ltchiptool to a supported version print("Installing/updating ltchiptool") system( - f"{sys.executable} -m pip install -U --force-reinstall " - f'"ltchiptool >= {LTCHIPTOOL_VERSION}, < 4.0"' + f'"{sys.executable}" -m pip install -U --force-reinstall ' + f'"ltchiptool >= {LTCHIPTOOL_VERSION[1:]}, < 5.0"' ) # unload all modules from the old version @@ -75,67 +75,6 @@ if dirname(__file__) in sys.path: # Let ltchiptool know about LT's location ltchiptool.lt_set_path(dirname(__file__)) -libretuya_packages = None -manifest_default = {"version": "0.0.0", "description": "", "keywords": []} - - -def load_manifest(self, src): - try: - return BasePackageManager._load_manifest(self, src) - except MissingPackageManifestError: - # ignore all exceptions - pass - # get the installation temporary path - path = src.path if isinstance(src, PackageItem) else src - # raise the exception if this package is not from libretuya - if ( - not hasattr(self, "spec_map") - or path not in self.spec_map - or not libretuya_packages - ): - raise MissingPackageManifestError(", ".join(self.manifest_names)) - # get the saved spec - spec: PackageSpec = self.spec_map[path] - # read package data from platform.json - manifest: dict = libretuya_packages[spec.name] - # find additional manifest info - manifest = manifest.get("manifest", manifest_default) - # extract tag version - url = getattr(spec, "url", None) or getattr(spec, "uri", None) or "" - if "#" in url: - manifest["version"] = url.rpartition("#")[2].lstrip("v") - # put info from spec - manifest.update( - { - "name": spec.name, - "repository": { - "type": "git", - "url": url, - }, - } - ) - # save in cache - cache_key = "load_manifest-%s" % path - self.memcache_set(cache_key, manifest) - # result = ManifestParserFactory.new(json.dumps(manifest), ManifestFileType.PACKAGE_JSON).as_dict() - with open(join(path, self.manifest_names[0]), "w") as f: - json.dump(manifest, f) - return manifest - - -def find_pkg_root(self, path: str, spec: PackageSpec): - try: - return BasePackageManager._find_pkg_root(self, path, spec) - except MissingPackageManifestError as e: - # raise the exception if this package is not from libretuya - if not libretuya_packages or spec.name not in libretuya_packages: - raise e - # save the spec for later - if not hasattr(self, "spec_map"): - self.spec_map = {} - self.spec_map[path] = spec - return path - def get_os_specifiers(): system = platform.system().lower() @@ -164,41 +103,86 @@ def get_os_specifiers(): ] -class LibretuyaPlatform(PlatformBase): - boards_base: Dict[str, dict] = {} - custom_opts: Dict[str, object] = {} +class LibretinyPlatform(PlatformBase): + custom_opts: Dict[str, object] = None + versions: Dict[str, str] = None - def configure_default_packages(self, options, targets): - # patch find_pkg root to ignore missing manifests and save PackageSpec - if not hasattr(BasePackageManager, "_find_pkg_root"): - BasePackageManager._find_pkg_root = BasePackageManager.find_pkg_root - BasePackageManager.find_pkg_root = find_pkg_root - # patch load_manifest to generate manifests from PackageSpec - if not hasattr(BasePackageManager, "_load_manifest"): - BasePackageManager._load_manifest = BasePackageManager.load_manifest - BasePackageManager.load_manifest = load_manifest + def __init__(self, manifest_path): + super().__init__(manifest_path) + self.custom_opts = {} + self.versions = {} - pioframework = options.get("pioframework") + def print(self, *args, **kwargs): + if not self.verbose: + return + print(f"platform.py({os.getpid()}):", *args, **kwargs) + + def custom(self, key: str) -> object: + return self.custom_opts.get(key, None) + + def get_package_spec(self, name, version=None): + # make PlatformIO detach existing package versions instead of overwriting + # TODO this is an ugly hack, it moves old packages to dirs like "library-lwip@src-21d717f2feaca73533f129ce05c9f4d4" + # it should be fixed properly at some point. Maybe ask PIO to allow controlling that somehow? + spec = super().get_package_spec(name, version) + spec._name_is_custom = False + return spec + + def configure_default_packages(self, options: dict, targets: List[str]): + from ltchiptool.util.dict import RecursiveDict + + self.verbose = ( + "-v" in sys.argv or "--verbose" in sys.argv or "PIOVERBOSE=1" in sys.argv + ) + self.print(f"configure_default_packages(targets={targets})") + + pioframework = options.get("pioframework") or ["base"] if not pioframework: return - framework = pioframework[0] + framework: str = pioframework[0] - # allow using "arduino" as framework - if framework == "arduino": - board = self.get_boards(options.get("board")) - frameworks = board.get("frameworks") - framework = next(fw for fw in frameworks if framework in fw) - options.get("pioframework")[0] = framework + # save custom options from env + self.custom_opts = RecursiveDict() + for key, value in options.items(): + if not key.startswith("custom_"): + continue + key = key[7:] + parent, sep, child = key.partition(".") + if parent == "options": + # allow only one level of nesting ('child' may be a header name, which contains a dot) + child = child.replace(".", "#") + self.custom_opts[parent + sep + child] = value + self.print("Custom options:", json.dumps(self.custom_opts, indent="\t")) + + # update framework names to their new values since v1.0.0 + if framework.endswith("-sdk"): + click.secho( + f"Framework '{framework}' is now named 'base'. " + "Update your platformio.ini to use the new name, then try again.", + fg="red", + ) + exit(1) + if framework.endswith("-arduino"): + click.secho( + f"Framework '{framework}' is now named 'arduino'. " + "Update your platformio.ini to use the new name, then try again.", + fg="red", + ) + exit(1) # make ArduinoCore-API required - if "arduino" in framework: + if framework == "arduino": self.packages["framework-arduino-api"]["optional"] = False - framework_obj = self.frameworks[framework] - if "package" in framework_obj: - package_obj = self.packages[framework_obj["package"]] - else: - package_obj = {} + # get framework SDK package + board = self.get_boards(options.get("board")) + package = board.get("package") + package_obj = self.packages.get(package, {}) + # mark framework SDK as required + package_obj["optional"] = False + + # get user-chosen versions of libraries/toolchains + versions: RecursiveDict = self.custom("versions") or {} # set specific compiler versions if "toolchains" in package_obj: @@ -216,54 +200,85 @@ class LibretuyaPlatform(PlatformBase): (toolchain, version) = toolchain_version.split("@") self.packages[f"toolchain-{toolchain}"]["version"] = version - # mark framework SDK as required - package_obj["optional"] = False - # gather library dependencies - libraries = package_obj["libraries"] if "libraries" in package_obj else {} - for name, package in self.packages.items(): + pkg_versions = {} + for package in self.packages.values(): if "optional" in package and package["optional"]: continue if "libraries" not in package: continue - libraries.update(package["libraries"]) + for name, lib_versions in package["libraries"].items(): + package = f"library-{name}" + if isinstance(lib_versions, str): + # single version specified as string + if name in versions: + pkg_versions[package] = versions[name] + else: + pkg_versions[package] = lib_versions + continue + # mapping of versions to repo branches + if name in versions and versions[name] in lib_versions: + pkg_versions[package] = lib_versions[versions[name]] + continue + if "default" in lib_versions: + pkg_versions[package] = lib_versions["default"] - # use appropriate vendor library versions - packages_new = {} - for name, package in self.packages.items(): - if not name.startswith("library-"): + # gather custom (user-set) versions of other libraries + for name, version in versions.items(): + if name == "toolchain": continue - name = name[8:] # strip "library-" - if name not in libraries: + name = name.replace("_", "-") + version = version.lstrip("v") + # find the package by "library-xxx", "framework-xxx" or "tool-xxx" + package = f"library-{name}" + if package not in self.packages: + package = f"framework-{name}" + if package not in self.packages: + package = f"tool-{name}" + if package not in self.packages: + click.secho( + f"Library '{name}' couldn't be found. " + f"Remove 'custom_versions.{name}' from platformio.ini and try again.", + fg="red", + ) + exit(1) + if package in pkg_versions: + # skip already added libs continue - lib_version = libraries[name][-1] # get latest version tag - package = dict(**package) # clone the base package - package["version"] = ( - package["base_url"] + "#" + lib_version - ) # use the specific version - package["optional"] = False # make it required - lib_version = lib_version.lstrip("v") # strip "v" in target name - name = f"library-{name}@{lib_version}" - packages_new[name] = package # put the package under a new name - self.packages.update(packages_new) + pkg_versions[package] = version - # save platform packages for later - global libretuya_packages - libretuya_packages = self.packages + # enable packages required for framework libraries + for name, version in pkg_versions.items(): + if name not in self.packages: + raise ValueError(f"Library '{name}' doesn't exist") + package = self.packages[name] + if "base_url" not in package: + if "#" not in package.get("version", ""): + click.secho( + f"Property 'base_url' is missing for '{name}'. " + "The version of this package can't be changed by the user.", + fg="red", + ) + exit(1) + package["base_url"] = package["version"].partition("#")[0] + if package.get("version_prefix", False): + version = "v" + version + package["optional"] = False + package["version"] = package["base_url"] + "#" + version - # save custom options from env - self.custom_opts = {} - for key, value in options.items(): - if not key.startswith("custom_"): - continue - self.custom_opts[key[7:]] = value + # store version numbers of all used packages + for package in self.get_installed_packages(with_optional=False): + package: PackageItem + version = package.metadata.version + version = str(version).partition("sha.")[0] + version = version.strip("+.") + version = version.rpartition("+")[2] + self.versions[package.metadata.name] = version return super().configure_default_packages(options, targets) - def custom(self, key: str) -> object: - return self.custom_opts.get(key, None) - def get_boards(self, id_=None): + self.print(f"get_boards(id_={id_})") result = PlatformBase.get_boards(self, id_) if not result: return result @@ -277,11 +292,24 @@ class LibretuyaPlatform(PlatformBase): def update_board(self, board: PlatformBoardConfig): if "_base" in board: board._manifest = ltchiptool.Board.get_data(board._manifest) + board._manifest.pop("_base") - # add "arduino" framework - has_arduino = any("arduino" in fw for fw in board.manifest["frameworks"]) - if has_arduino: + if self.custom("board"): + from ltchiptool.util.dict import merge_dicts + + with open(self.custom("board"), "r") as f: + custom_board = json.load(f) + board._manifest = merge_dicts(board._manifest, custom_board) + + family = board.get("build.family") + family = ltchiptool.Family.get(short_name=family) + # add "frameworks" key with the default "base" + board.manifest["frameworks"] = ["base"] + # add "arduino" framework if supported + if family.has_arduino_core: board.manifest["frameworks"].append("arduino") + # add SDK package name + board.manifest["package"] = family.target_package # inspired by platform-ststm32/platform.py debug = board.manifest.get("debug", {}) @@ -293,7 +321,8 @@ class LibretuyaPlatform(PlatformBase): if "custom" not in debug["tools"]: debug["tools"]["custom"] = {} init = debug.get("gdb_init", []) - init += ["set mem inaccessible-by-default off"] + if "set mem inaccessible-by-default off" not in init: + init += ["set mem inaccessible-by-default off"] for link in protocols: if link == "openocd": @@ -334,7 +363,7 @@ class LibretuyaPlatform(PlatformBase): if debug_tool == "custom": return exc = DebugInvalidOptionsError( - f"[LibreTuya] Debug tool {debug_tool} is not supported by board {board}." + f"[LibreTiny] Debug tool {debug_tool} is not supported by board {board}." ) exc.MESSAGE = "" raise exc diff --git a/platform/common/fixups/WCharacterFixup.h b/platform/common/fixups/WCharacterFixup.h deleted file mode 100644 index e1333d4..0000000 --- a/platform/common/fixups/WCharacterFixup.h +++ /dev/null @@ -1,17 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-04-23. */ - -/* WCharacter.h uses deprecated isascii() and toascii(), - which are available in gnu++11 but not c++11 */ -#include - -#ifdef __STRICT_ANSI__ - -inline bool isascii(int c) { - return ((c & ~0x7f) != 0 ? false : true); -} - -inline bool toascii(int c) { - return (c & 0x7f); -} - -#endif diff --git a/platform/realtek-amb/config/main.h b/platform/realtek-amb/config/main.h deleted file mode 100644 index 2f996a9..0000000 --- a/platform/realtek-amb/config/main.h +++ /dev/null @@ -1,122 +0,0 @@ -#ifndef MAIN_H -#define MAIN_H - -#include - -#ifndef CONFIG_WLAN -#define CONFIG_WLAN 1 -#endif - -/* Header file declaration*/ -void wlan_network(); - -/* Interactive Mode */ -#define SERIAL_DEBUG_RX 1 - -/* WLAN and Netork */ -#define STA_MODE_SSID "ap" /* Set SSID here */ -#define AP_MODE_SSID "wlan_ap_ssid" /* Set SSID here */ -#define AP_DEFAULT_CH 6 -#define WLAN0_NAME "wlan0" -#define WLAN1_NAME "wlan1" -#define WPA_PASSPHRASE "1234567890" /* Max 32 cahracters */ -#define WEP40_KEY {0x12, 0x34, 0x56, 0x78, 0x90} - -#define ATVER_1 1 // For First AT command -#define ATVER_2 2 // For UART Module AT command - -#if CONFIG_EXAMPLE_UART_ATCMD -#define ATCMD_VER ATVER_2 -#else -#define ATCMD_VER ATVER_1 -#endif - -#if ATCMD_VER == ATVER_2 -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1 - -extern unsigned char sta_ip[4], sta_netmask[4], sta_gw[4]; -extern unsigned char ap_ip[4], ap_netmask[4], ap_gw[4]; - -/*Static IP ADDRESS*/ -#define IP_ADDR0 sta_ip[0] -#define IP_ADDR1 sta_ip[1] -#define IP_ADDR2 sta_ip[2] -#define IP_ADDR3 sta_ip[3] - -/*NETMASK*/ -#define NETMASK_ADDR0 sta_netmask[0] -#define NETMASK_ADDR1 sta_netmask[1] -#define NETMASK_ADDR2 sta_netmask[2] -#define NETMASK_ADDR3 sta_netmask[3] - -/*Gateway Address*/ -#define GW_ADDR0 sta_gw[0] -#define GW_ADDR1 sta_gw[1] -#define GW_ADDR2 sta_gw[2] -#define GW_ADDR3 sta_gw[3] - -/*******************************************/ - -/*Static IP ADDRESS*/ -#define AP_IP_ADDR0 ap_ip[0] -#define AP_IP_ADDR1 ap_ip[1] -#define AP_IP_ADDR2 ap_ip[2] -#define AP_IP_ADDR3 ap_ip[3] - -/*NETMASK*/ -#define AP_NETMASK_ADDR0 ap_netmask[0] -#define AP_NETMASK_ADDR1 ap_netmask[1] -#define AP_NETMASK_ADDR2 ap_netmask[2] -#define AP_NETMASK_ADDR3 ap_netmask[3] - -/*Gateway Address*/ -#define AP_GW_ADDR0 ap_gw[0] -#define AP_GW_ADDR1 ap_gw[1] -#define AP_GW_ADDR2 ap_gw[2] -#define AP_GW_ADDR3 ap_gw[3] - -#else - -/*Static IP ADDRESS*/ -#define IP_ADDR0 192 -#define IP_ADDR1 168 -#define IP_ADDR2 1 -#define IP_ADDR3 80 - -/*NETMASK*/ -#define NETMASK_ADDR0 255 -#define NETMASK_ADDR1 255 -#define NETMASK_ADDR2 255 -#define NETMASK_ADDR3 0 - -/*Gateway Address*/ -#define GW_ADDR0 192 -#define GW_ADDR1 168 -#define GW_ADDR2 1 -#define GW_ADDR3 1 - -/*******************************************/ - -/*Static IP ADDRESS*/ -#define AP_IP_ADDR0 192 -#define AP_IP_ADDR1 168 -#define AP_IP_ADDR2 43 -#define AP_IP_ADDR3 1 - -/*NETMASK*/ -#define AP_NETMASK_ADDR0 255 -#define AP_NETMASK_ADDR1 255 -#define AP_NETMASK_ADDR2 255 -#define AP_NETMASK_ADDR3 0 - -/*Gateway Address*/ -#define AP_GW_ADDR0 192 -#define AP_GW_ADDR1 168 -#define AP_GW_ADDR2 43 -#define AP_GW_ADDR3 1 - -#endif //#if ATCMD_VER == ATVER_2 - - -#endif diff --git a/platform/realtek-ambz/bin/descript.ion b/platform/realtek-ambz/bin/descript.ion deleted file mode 100644 index 4074cb3..0000000 --- a/platform/realtek-ambz/bin/descript.ion +++ /dev/null @@ -1 +0,0 @@ -boot_all_77F7.bin tysdk_for_rtl8710bn diff --git a/platform/realtek-ambz/config/FreeRTOSConfig.h b/platform/realtek-ambz/config/FreeRTOSConfig.h deleted file mode 100644 index d735e54..0000000 --- a/platform/realtek-ambz/config/FreeRTOSConfig.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - FreeRTOS V7.3.0 - Copyright (C) 2012 Real Time Engineers Ltd. - - FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT - http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. - - *************************************************************************** - * * - * FreeRTOS tutorial books are available in pdf and paperback. * - * Complete, revised, and edited pdf reference manuals are also * - * available. * - * * - * Purchasing FreeRTOS documentation will not only help you, by * - * ensuring you get running as quickly as possible and with an * - * in-depth knowledge of how to use FreeRTOS, it will also help * - * the FreeRTOS project to continue with its mission of providing * - * professional grade, cross platform, de facto standard solutions * - * for microcontrollers - completely free of charge! * - * * - * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * - * * - * Thank you for using FreeRTOS, and thank you for your support! * - * * - *************************************************************************** - - - This file is part of the FreeRTOS distribution. - - FreeRTOS is free software; you can redistribute it and/or modify it under - the terms of the GNU General Public License (version 2) as published by the - Free Software Foundation AND MODIFIED BY the FreeRTOS exception. - >>>NOTE<<< The modification to the GPL is included to allow you to - distribute a combined work that includes FreeRTOS without being obliged to - provide the source code for proprietary components outside of the FreeRTOS - kernel. FreeRTOS is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - more details. You should have received a copy of the GNU General Public - License and the FreeRTOS license exception along with FreeRTOS; if not it - can be viewed here: http://www.freertos.org/a00114.html and also obtained - by writing to Richard Barry, contact details for whom are available on the - FreeRTOS WEB site. - - 1 tab == 4 spaces! - - *************************************************************************** - * * - * Having a problem? Start by reading the FAQ "My application does * - * not run, what could be wrong?" * - * * - * http://www.FreeRTOS.org/FAQHelp.html * - * * - *************************************************************************** - - - http://www.FreeRTOS.org - Documentation, training, latest versions, license - and contact details. - - http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, - including FreeRTOS+Trace - an indispensable productivity tool. - - Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell - the code with commercial support, indemnification, and middleware, under - the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also - provide a safety engineered and independently SIL3 certified version under - the SafeRTOS brand: http://www.SafeRTOS.com. -*/ - -#ifndef FREERTOS_CONFIG_H -#define FREERTOS_CONFIG_H -#if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__) -#include -extern uint32_t SystemCoreClock; -#endif -#include "platform_autoconf.h" - -/*----------------------------------------------------------- - * Application specific definitions. - * - * These definitions should be adjusted for your particular hardware and - * application requirements. - * - * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE - * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. - * - * See http://www.freertos.org/a00110.html. - *----------------------------------------------------------*/ - -#define configUSE_PREEMPTION 1 -#define configUSE_IDLE_HOOK 1 -#define configUSE_TICK_HOOK 0 -#define configCPU_CLOCK_HZ ( SystemCoreClock ) -#define configTICK_RATE_HZ ( ( uint32_t ) 1000 ) -#define configSYSTICK_CLOCK_HZ 32768 -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 512 ) -#ifdef CONFIG_WIFI_EN -#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 160 * 1024 ) ) -#else -#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 20 * 1024 ) ) -#endif -#define configMAX_TASK_NAME_LEN ( 10 ) -#define configUSE_TRACE_FACILITY 0 -#define configUSE_16_BIT_TICKS 0 -#define configIDLE_SHOULD_YIELD 0 -#define configUSE_CO_ROUTINES 1 -#define configUSE_MUTEXES 1 -#define configUSE_TIMERS 1 - -#define configMAX_PRIORITIES ( 11 ) -#define PRIORITIE_OFFSET ( 4 ) - -#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) - -#define configUSE_COUNTING_SEMAPHORES 1 -#define configUSE_ALTERNATIVE_API 0 -#define configCHECK_FOR_STACK_OVERFLOW 2 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configQUEUE_REGISTRY_SIZE 0 -#define configGENERATE_RUN_TIME_STATS 0 -#if configGENERATE_RUN_TIME_STATS -#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() //( ulHighFrequencyTimerTicks = 0UL ) -#define portGET_RUN_TIME_COUNTER_VALUE() xTickCount //ulHighFrequencyTimerTicks -#undef configUSE_TRACE_FACILITY -#define configUSE_TRACE_FACILITY 1 -#define portCONFIGURE_STATS_PEROID_VALUE 1000 //unit Ticks -#endif - -#define configTIMER_TASK_PRIORITY ( 1 ) -#define configTIMER_QUEUE_LENGTH ( 10 ) -#define configTIMER_TASK_STACK_DEPTH ( 512 ) //USE_MIN_STACK_SIZE modify from 512 to 256 - -#if (__IASMARM__ != 1) - -extern void freertos_pre_sleep_processing(unsigned int *expected_idle_time); -extern void freertos_post_sleep_processing(unsigned int *expected_idle_time); -extern int freertos_ready_to_sleep(); - -/* Enable tickless power saving. */ -#define configUSE_TICKLESS_IDLE 1 - -/* In wlan usage, this value is suggested to use value less than 80 milliseconds */ -#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 - -/* It's magic trick that let us can use our own sleep function */ -#define configPRE_SLEEP_PROCESSING( x ) ( freertos_pre_sleep_processing(&x) ) - -#define configPOST_SLEEP_PROCESSING( x ) ( freertos_post_sleep_processing(&x) ) - -/* It's magic trick that let us can enable/disable tickless dynamically */ -#define traceLOW_POWER_IDLE_BEGIN(); do { \ - if (!freertos_ready_to_sleep()) { \ - mtCOVERAGE_TEST_MARKER(); \ - break; \ - } - - // portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); - -#define traceLOW_POWER_IDLE_END(); } while (0); - -/* It's FreeRTOS related feature but it's not included in FreeRTOS design. */ -#define configUSE_WAKELOCK_PMU 1 - -#endif // #if (__IASMARM__ != 1) - -/* 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 0 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_pcTaskGetTaskName 1 -#define INCLUDE_xTimerPendFunctionCall 1 - -/* Cortex-M specific definitions. */ -#ifdef __NVIC_PRIO_BITS - /* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */ - #define configPRIO_BITS __NVIC_PRIO_BITS -#else - #define configPRIO_BITS 4 /* 15 priority levels */ -#endif - - -/* The lowest interrupt priority that can be used in a call to a "set priority" -function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 0x0f - -/* The highest interrupt priority that can be used by any interrupt service -routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL -INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER -PRIORITY THAN THIS! (higher priorities are lower numeric values. */ -#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 - - -/* Interrupt priorities used by the kernel port layer itself. These are generic -to all Cortex-M ports, and do not rely on any particular library functions. */ -#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) -/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! -See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ -#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) - -//#define RTK_MODE_TIMER - - -#endif /* FREERTOS_CONFIG_H */ diff --git a/platform/realtek-ambz/config/autoconf.h b/platform/realtek-ambz/config/autoconf.h deleted file mode 100644 index ad291e9..0000000 --- a/platform/realtek-ambz/config/autoconf.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-20. */ - -#pragma once - -#include_next "autoconf.h" diff --git a/platform/realtek-ambz/config/lwipopts.h b/platform/realtek-ambz/config/lwipopts.h deleted file mode 100644 index 3ccc9f1..0000000 --- a/platform/realtek-ambz/config/lwipopts.h +++ /dev/null @@ -1,333 +0,0 @@ -// CHANGES: -// - 2022-05-08 undefine LWIP_PROVIDE_ERRNO -// - 2022-05-23 enable LWIP_MDNS_RESPONDER -// - 2022-05-23 set LWIP_NUM_NETIF_CLIENT_DATA to 1 -// - 2022-05-23 set MEMP_NUM_UDP_PCB to 7 - - -/** - ****************************************************************************** - * @file lwipopts.h - * @author MCD Application Team - * @version V1.1.0 - * @date 07-October-2011 - * @brief lwIP Options Configuration. - * This file is based on Utilities\lwip_v1.3.2\src\include\lwip\opt.h - * and contains the lwIP configuration for the STM32F2x7 demonstration. - ****************************************************************************** - * @attention - * - * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS - * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE - * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY - * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING - * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE - * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. - * - *

© COPYRIGHT 2011 STMicroelectronics

- ****************************************************************************** - */ - -#ifndef __LWIPOPTS_H__ -#define __LWIPOPTS_H__ - -#include_next "lwipopts.h" - -#include -#include "platform_opts.h" -#define WIFI_LOGO_CERTIFICATION_CONFIG 0 //for ping 10k test buffer setting - -/** - * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain - * critical regions during buffer allocation, deallocation and memory - * allocation and deallocation. - */ -#define SYS_LIGHTWEIGHT_PROT 1 - -/* Define LWIP_COMPAT_MUTEX if the port has no mutexes and binary semaphores - should be used instead */ -#define LWIP_COMPAT_MUTEX 1 -#define LWIP_COMPAT_MUTEX_ALLOWED 1 - -#define LWIP_TCPIP_TIMEOUT 1 - -#define ETHARP_TRUST_IP_MAC 0 -#define IP_REASSEMBLY 1 -#define IP_FRAG 1 -#define ARP_QUEUEING 0 - -/** - * NO_SYS==1: Provides VERY minimal functionality. Otherwise, - * use lwIP facilities. - */ -#define NO_SYS 0 - -#ifndef CONFIG_DYNAMIC_TICKLESS -#define CONFIG_DYNAMIC_TICKLESS 0 -#endif - -/* ---------- Memory options ---------- */ -/* MEM_ALIGNMENT: should be set to the alignment of the CPU for which - lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2 - byte alignment -> define MEM_ALIGNMENT to 2. */ -#define MEM_ALIGNMENT 4 - -/* MEM_SIZE: the size of the heap memory. If the application will send -a lot of data that needs to be copied, this should be set high. */ -#if WIFI_LOGO_CERTIFICATION_CONFIG - #define MEM_SIZE (10*1024) //for ping 10k test -#elif CONFIG_ETHERNET - #define MEM_SIZE (6*1024) //for iperf test -#else - #define MEM_SIZE (5*1024) -#endif - -/* MEMP_NUM_PBUF: the number of memp struct pbufs. If the application - sends a lot of data out of ROM (or other static memory), this - should be set high. */ -#define MEMP_NUM_PBUF 100 -/* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One - per active UDP "connection". */ -#define MEMP_NUM_UDP_PCB 7 -/* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP - connections. */ -#define MEMP_NUM_TCP_PCB 10 -/* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP - connections. */ -#define MEMP_NUM_TCP_PCB_LISTEN 5 -/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP - segments. */ -#define MEMP_NUM_TCP_SEG 20 -/* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active - timeouts. */ -#define MEMP_NUM_SYS_TIMEOUT 10 - - -/* ---------- Pbuf options ---------- */ -/* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ -#if WIFI_LOGO_CERTIFICATION_CONFIG - #define PBUF_POOL_SIZE 30 //for ping 10k test -#else - #define PBUF_POOL_SIZE 20 -#endif - -/* IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled.*/ -#if WIFI_LOGO_CERTIFICATION_CONFIG - #define IP_REASS_MAX_PBUFS 30 //for ping 10k test -#else - #define IP_REASS_MAX_PBUFS 10 -#endif - -/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ -#define PBUF_POOL_BUFSIZE 500 - - -/* ---------- TCP options ---------- */ -#define LWIP_TCP 1 -#define TCP_TTL 255 - -/* Controls if TCP should queue segments that arrive out of - order. Define to 0 if your device is low on memory. */ -#define TCP_QUEUE_OOSEQ 1 - -/* TCP Maximum segment size. */ -#define TCP_MSS (1500 - 40) /* TCP_MSS = (Ethernet MTU - IP header size - TCP header size) */ - -/* TCP sender buffer space (bytes). */ -#define TCP_SND_BUF (5*TCP_MSS) - -/* TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least - as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. */ - -#define TCP_SND_QUEUELEN (4* TCP_SND_BUF/TCP_MSS) - -/* TCP receive window. */ -#define TCP_WND (2*TCP_MSS) - - -/* ---------- ICMP options ---------- */ -#define LWIP_ICMP 1 - -/* ---------- ARP options ----------- */ -#define LWIP_ARP 1 - -/* ---------- DHCP options ---------- */ -/* Define LWIP_DHCP to 1 if you want DHCP configuration of - interfaces. DHCP is not implemented in lwIP 0.5.1, however, so - turning this on does currently not work. */ -#define LWIP_DHCP 1 - - -/* ---------- UDP options ---------- */ -#define LWIP_UDP 1 -#define UDP_TTL 255 -/* ---------- DNS options ---------- */ -#define LWIP_DNS 1 - -/* ---------- UPNP options --------- */ -#define LWIP_UPNP 0 - -/* Support Multicast */ -#define LWIP_IGMP 1 -#define LWIP_RAND() rand() -#define LWIP_SRAND() srand(sys_now()) - -/* Support TCP Keepalive */ -#define LWIP_TCP_KEEPALIVE 1 - -/*LWIP_UART_ADAPTER==1: Enable LWIP_UART_ADAPTER when CONFIG_GAGENT is enabled, - because some GAGENT functions denpond on the following macro definitions.*/ -#define LWIP_UART_ADAPTER 0 - -#if LWIP_UART_ADAPTER || CONFIG_ETHERNET -#undef LWIP_SO_SNDTIMEO -#define LWIP_SO_SNDTIMEO 1 - -#undef SO_REUSE -#define SO_REUSE 1 - -#undef MEMP_NUM_NETCONN -#define MEMP_NUM_NETCONN 10 - -#undef TCP_WND -#define TCP_WND (4*TCP_MSS) - -#define TCP_KEEPIDLE_DEFAULT 10000UL -#define TCP_KEEPINTVL_DEFAULT 1000UL -#define TCP_KEEPCNT_DEFAULT 10U -#endif - -#if CONFIG_EXAMPLE_UART_ATCMD || CONFIG_EXAMPLE_SPI_ATCMD -#undef LWIP_SO_SNDTIMEO -#define LWIP_SO_SNDTIMEO 1 - -#undef SO_REUSE -#define SO_REUSE 1 - -#undef SO_REUSE_RXTOALL -#define SO_REUSE_RXTOALL 1 - -#undef MEMP_NUM_NETCONN -#define MEMP_NUM_NETCONN 10 - -#undef MEMP_NUM_TCP_PCB -#define MEMP_NUM_TCP_PCB (MEMP_NUM_NETCONN) - -#undef MEMP_NUM_UDP_PCB -#define MEMP_NUM_UDP_PCB (MEMP_NUM_NETCONN) - -#undef TCP_WND -#define TCP_WND (4*TCP_MSS) - -#define TCP_KEEPIDLE_DEFAULT 10000UL -#define TCP_KEEPINTVL_DEFAULT 1000UL -#define TCP_KEEPCNT_DEFAULT 10U - -#define ERRNO 1 - -#endif - -/* ---------- Statistics options ---------- */ -#define LWIP_STATS 0 - - -/* - -------------------------------------- - ---------- Checksum options ---------- - -------------------------------------- -*/ - -/* -The STM32F2x7 allows computing and verifying the IP, UDP, TCP and ICMP checksums by hardware: - - To use this feature let the following define uncommented. - - To disable it and process by CPU comment the the checksum. -*/ -//Do checksum by lwip - WLAN nic does not support Checksum offload -//#define CHECKSUM_BY_HARDWARE - - -#ifdef CHECKSUM_BY_HARDWARE - /* CHECKSUM_GEN_IP==0: Generate checksums by hardware for outgoing IP packets.*/ - #define CHECKSUM_GEN_IP 0 - /* CHECKSUM_GEN_UDP==0: Generate checksums by hardware for outgoing UDP packets.*/ - #define CHECKSUM_GEN_UDP 0 - /* CHECKSUM_GEN_TCP==0: Generate checksums by hardware for outgoing TCP packets.*/ - #define CHECKSUM_GEN_TCP 0 - /* CHECKSUM_CHECK_IP==0: Check checksums by hardware for incoming IP packets.*/ - #define CHECKSUM_CHECK_IP 0 - /* CHECKSUM_CHECK_UDP==0: Check checksums by hardware for incoming UDP packets.*/ - #define CHECKSUM_CHECK_UDP 0 - /* CHECKSUM_CHECK_TCP==0: Check checksums by hardware for incoming TCP packets.*/ - #define CHECKSUM_CHECK_TCP 0 -#else - /* CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets.*/ - #define CHECKSUM_GEN_IP 1 - /* CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets.*/ - #define CHECKSUM_GEN_UDP 1 - /* CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets.*/ - #define CHECKSUM_GEN_TCP 1 - /* CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets.*/ - #define CHECKSUM_CHECK_IP 1 - /* CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets.*/ - #define CHECKSUM_CHECK_UDP 1 - /* CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets.*/ - #define CHECKSUM_CHECK_TCP 1 -#endif - - -/* - ---------------------------------------------- - ---------- Sequential layer options ---------- - ---------------------------------------------- -*/ -/** - * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) - */ -#define LWIP_NETCONN 1 - -/* - ------------------------------------ - ---------- Socket options ---------- - ------------------------------------ -*/ -/** - * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) - */ -#define LWIP_SOCKET 1 - -/* - ----------------------------------- - ---------- DEBUG options ---------- - ----------------------------------- -*/ - -#define LWIP_DEBUG 0 - - -/* - --------------------------------- - ---------- OS options ---------- - --------------------------------- -*/ - -#define TCPIP_THREAD_STACKSIZE 1000 -#define TCPIP_MBOX_SIZE 6 -#define DEFAULT_UDP_RECVMBOX_SIZE 6 -#define DEFAULT_TCP_RECVMBOX_SIZE 6 -#define DEFAULT_RAW_RECVMBOX_SIZE 6 -#define DEFAULT_ACCEPTMBOX_SIZE 6 -#define DEFAULT_THREAD_STACKSIZE 500 -#define TCPIP_THREAD_PRIO (configMAX_PRIORITIES - 2) - -/* Added by Realtek */ -#ifndef DNS_IGNORE_REPLY_ERR -#define DNS_IGNORE_REPLY_ERR 1 -#endif /* DNS_IGNORE_REPLY_ERR */ - -// for mDNS support -#define LWIP_MDNS_RESPONDER 1 -#define LWIP_NUM_NETIF_CLIENT_DATA 1 - -#endif /* __LWIPOPTS_H__ */ - -/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/ diff --git a/platform/realtek-ambz/config/platform_autoconf.h b/platform/realtek-ambz/config/platform_autoconf.h deleted file mode 100644 index 3f95890..0000000 --- a/platform/realtek-ambz/config/platform_autoconf.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Automatically generated by make menuconfig: don't edit - */ -#define AUTOCONF_INCLUDED - -/* - * < MENUCONFIG FOR CHIP CONFIG - */ - -/* - * < CONFIG CHIP - */ -#define CONFIG_RTL8711B 1 -#undef ARM_CORE_CM3 -#define ARM_CORE_CM4 1 -#define CONFIG_CHIP_A_CUT 1 -#undef CONFIG_FPGA - -/* - * < CONFIG CPU CLK - */ -#define CONFIG_CPU_CLK 1 -#define CONFIG_CPU_125MHZ 1 -#undef CONFIG_CPU_62_5MHZ -#undef CONFIG_CPU_31_25MHZ -#undef CONFIG_CPU_15_625MHZ -#undef CONFIG_CPU_7_8125MHZ -#undef CONFIG_CPU_4MHZ -#undef CONFIG_FPGA_CLK -#define PLATFORM_CLOCK (125000000) -#define CPU_CLOCK_SEL_VALUE (0) - -/* - * < CONFIG OSC8M CLK - */ -#define CONFIG_OSC8M_CLK 1 -#define CONFIG_OSC8M_8388608HZ 1 -#undef CONFIG_OSC8M_8192000HZ -#undef CONFIG_OSC8M_8000000HZ -#undef CONFIG_OSC8M_16777216HZ -#define OSC8M_CLOCK (8388608) - -/* - * < CONFIG TEST MODE - */ -#undef CONFIG_MP -#undef CONFIG_CP -#undef CONFIG_FT -#undef CONFIG_EQC -#undef CONFIG_RTL_SIM -#undef CONFIG_POST_SIM - -/* - * < CONFIG OS - */ -#define CONFIG_KERNEL 1 -#define PLATFORM_FREERTOS 1 -#undef PLATFORM_UCOSII -#undef PLATFORM_ECOS -#undef CONFIG_TASK_SCHEDUL_DIS -#define TASK_SCHEDULER_DISABLED (0) - -/* - * < CONFIG GTIMER - */ -#define CONFIG_TIMER_EN 1 -#define CONFIG_TIMER_MODULE 1 - -/* - * < CONFIG WDG - */ -#define CONFIG_WDG 1 -#define CONFIG_WDG_MODULE 1 - -/* - * < CONFIG GDMA - */ -#define CONFIG_GDMA_EN 1 -#define CONFIG_GDMA_MODULE 1 - -/* - * < CONFIG GPIO - */ -#define CONFIG_GPIO_EN 1 -#define CONFIG_GPIO_MODULE 1 - -/* - * < CONFIG SPI - */ -#define CONFIG_SPI_COM_EN 1 -#define CONFIG_SPI_COM_MODULE 1 - -/* - * < CONFIG UART - */ -#define CONFIG_UART_EN 1 -#define CONFIG_UART_MODULE 1 - -/* - * < CONFIG I2C - */ -#define CONFIG_I2C_EN 1 -#define CONFIG_I2C_MODULE 1 - -/* - * < CONFIG I2S - */ -#define CONFIG_I2S_EN 1 -#define CONFIG_I2S_MODULE 1 - -/* - * < CONFIG SOC PS - */ -#define CONFIG_SOC_PS_EN 1 -#define CONFIG_SOC_PS_MODULE 1 - -/* - * < CONFIG CRYPTO - */ -#define CONFIG_CRYPTO_EN 1 -#define CONFIG_CRYPTO_MODULE 1 - -/* - * < CONFIG PWM - */ -#define CONFIG_PWM_EN 1 - -/* - * < CONFIG EFUSE - */ -#define CONFIG_EFUSE_EN 1 -#define CONFIG_EFUSE_MODULE 1 - -/* - * < CONFIG SPIC - */ -#define CONFIG_SPIC_EN 1 -#define CONFIG_SPIC_MODULE 1 -#define CONFIG_SPIC_PHASE_CALIBATION 1 -#undef CONFIG_SPIC_4BYTES_ADDRESS - -/* - * < CONFIG ADC - */ -#define CONFIG_ADC_EN 1 -#define CONFIG_ADC_MODULE 1 - -/* - * < CONFIG SDIO Device - */ -#define CONFIG_SDIO_DEVICE_EN 1 -#define CONFIG_SDIO_DEVICE_NORMAL 1 -#define CONFIG_SDIO_DEVICE_MODULE 1 - -/* - * < CONFIG USB - */ -#define CONFIG_USB_EN 1 -#define CONFIG_USB_MODULE 1 - -/* - * < CONFIG RDP - */ -#define CONFIG_RDP_ENABLE 1 - -/* - * < CONFIG PINMUX - */ -#undef CONFIG_PINMAP_ENABLE - -/* - * < CONFIG PER TEST - */ -#undef CONFIG_PER_TEST - -/* - * < CONFIG WIFI - */ -#define CONFIG_WIFI_EN 1 -#define CONFIG_WIFI_NORMAL 1 -#undef CONFIG_WIFI_TEST -#define CONFIG_WIFI_MODULE 1 - -/* - * < CONFIG NETWORK - */ -#define CONFIG_NETWORK 1 - -/* - * < CONFIG INIC - */ -#undef CONFIG_INIC_EN - -/* - * < CONFIG USB_NIC - */ -#undef CONFIG_USB_DONGLE_NIC_EN - -/* - * < RTK STD lib - */ -#define CONFIG_RTLIB_EN 1 -#define CONFIG_RTLIB_MODULE 1 -#undef CONFIG_RTLIB_VERIFY - -/* - * < Add MBED SDK - */ -#undef CONFIG_MBED_ENABLED - -/* - * < Build App Demo - */ -#undef CONFIG_APP_DEMO - -/* - * < Dhrystone - */ -#undef CONFIG_DHRYSTONE_TEST - -/* - * < SSL - */ -#undef CONFIG_SSL_ROM_TEST - -/* - * < System Debug Message Config - */ -#define CONFIG_UART_LOG_HISTORY 1 -#define CONFIG_DEBUG_LOG 1 -#define CONFIG_DEBUG_ERR_MSG 1 -#undef CONFIG_DEBUG_WARN_MSG -#undef CONFIG_DEBUG_INFO_MSG - -/* - * < Build Option - */ -#define CONFIG_TOOLCHAIN_ASDK 1 -#undef CONFIG_TOOLCHAIN_ARM_GCC -#define CONFIG_LINK_ROM_LIB 1 -#undef CONFIG_LINK_ROM_SYMB diff --git a/platform/realtek-ambz/config/platform_opts.h b/platform/realtek-ambz/config/platform_opts.h deleted file mode 100644 index 4a338f0..0000000 --- a/platform/realtek-ambz/config/platform_opts.h +++ /dev/null @@ -1,345 +0,0 @@ -// CHANGES: -// - 2022-05-08 change CONFIG_USE_POLARSSL to CONFIG_USE_MBEDTLS -// - 2022-05-08 use static int errno -// - 2022-05-18 include lwip/init.h -// - 2022-06-13 extract errno to common/fixups/errno.h - - -/** - ****************************************************************************** - *This file contains general configurations for ameba platform - ****************************************************************************** -*/ - -#ifndef __PLATFORM_OPTS_H__ -#define __PLATFORM_OPTS_H__ - -#include "platform_autoconf.h" - -#include - -/*For MP mode setting*/ -//#define SUPPORT_MP_MODE 1 - -/** - * For AT cmd Log service configurations - */ -#define SUPPORT_LOG_SERVICE 1 -#if SUPPORT_LOG_SERVICE -#define LOG_SERVICE_BUFLEN 100 //can't larger than UART_LOG_CMD_BUFLEN(127) -#define CONFIG_LOG_HISTORY 0 -#if CONFIG_LOG_HISTORY -#define LOG_HISTORY_LEN 5 -#endif -#define SUPPORT_INTERACTIVE_MODE 0//on/off wifi_interactive_mode -#define CONFIG_LOG_SERVICE_LOCK 0 -#endif - -/* For DCT example*/ -#define CONFIG_EXAMPLE_DCT 0 - -/** - * For interactive mode configurations, depents on log service - */ -#if SUPPORT_INTERACTIVE_MODE -#define CONFIG_INTERACTIVE_MODE 1 -#define CONFIG_INTERACTIVE_EXT 0 -#else -#define CONFIG_INTERACTIVE_MODE 0 -#define CONFIG_INTERACTIVE_EXT 0 -#endif - -/** - * For FreeRTOS tickless configurations - */ -#define FREERTOS_PMU_TICKLESS_SUSPEND_SDRAM 1 // In sleep mode, 1: suspend SDRAM, 0: no act - -/******************************************************************************/ - -/** -* For common flash usage -*/ -#define AP_SETTING_SECTOR 0x000FE000 -#define UART_SETTING_SECTOR 0x000FC000 -#define SPI_SETTING_SECTOR 0x000FC000 -#define FAST_RECONNECT_DATA (0x80000 - 0x1000) -#define FLASH_SECTOR_SIZE 0x1000 - -#define CONFIG_ENABLE_RDP 0 - -/** - * For Wlan configurations - */ -#define CONFIG_WLAN 1 -#if CONFIG_WLAN -#define CONFIG_LWIP_LAYER 1 -#define CONFIG_INIT_NET 1 //init lwip layer when start up -#define CONFIG_WIFI_IND_USE_THREAD 0 // wifi indicate worker thread - -//on/off relative commands in log service -#define CONFIG_SSL_CLIENT 0 -#define CONFIG_WEBSERVER 0 -#define CONFIG_OTA_UPDATE 1 -#define CONFIG_BSD_TCP 1//NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size -#define CONFIG_AIRKISS 0//on or off tencent airkiss -#define CONFIG_UART_SOCKET 0 -#define CONFIG_UART_XMODEM 0//support uart xmodem upgrade or not -#define CONFIG_TRANSPORT 0//on or off the at command for transport socket - -/* For WPS and P2P */ -#define CONFIG_ENABLE_WPS 0 -#define CONFIG_ENABLE_WPS_DISCOVERY 0 -#if CONFIG_ENABLE_P2P -#define CONFIG_ENABLE_WPS_AP 1 -#undef CONFIG_WIFI_IND_USE_THREAD -#define CONFIG_WIFI_IND_USE_THREAD 1 -#endif -#if (CONFIG_ENABLE_P2P && ((CONFIG_ENABLE_WPS_AP == 0) || (CONFIG_ENABLE_WPS == 0))) -#error "If CONFIG_ENABLE_P2P, need to define CONFIG_ENABLE_WPS_AP 1" -#endif - -/* For SSL/TLS */ -#define CONFIG_USE_POLARSSL 0 -#define CONFIG_USE_MBEDTLS 1 -#if ((CONFIG_USE_POLARSSL == 0) && (CONFIG_USE_MBEDTLS == 0)) || ((CONFIG_USE_POLARSSL == 1) && (CONFIG_USE_MBEDTLS == 1)) -#undef CONFIG_USE_POLARSSL -#define CONFIG_USE_POLARSSL 1 -#undef CONFIG_USE_MBEDTLS -#define CONFIG_USE_MBEDTLS 0 -#endif - -/* For Simple Link */ -#define CONFIG_INCLUDE_SIMPLE_CONFIG 1 - -/*For fast reconnection*/ -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 - - -#define CONFIG_GAGENT 0 -/*Disable CONFIG_EXAMPLE_WLAN_FAST_CONNECT when CONFIG_GAGENT is enabled,because - reconnect to previous AP is not suitable when re-configuration. -*/ -#if CONFIG_GAGENT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - - -#endif //end of #if CONFIG_WLAN -/*******************************************************************************/ - -/** - * For Ethernet configurations - */ -#define CONFIG_ETHERNET 0 -#if CONFIG_ETHERNET - -#define CONFIG_LWIP_LAYER 1 -#define CONFIG_INIT_NET 1 //init lwip layer when start up - -//on/off relative commands in log service -#define CONFIG_SSL_CLIENT 0 -#define CONFIG_BSD_TCP 0//NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size - -#endif - -/** - * For user to adjust SLEEP_INTERVAL - */ -#define CONFIG_DYNAMIC_TICKLESS 1 - -/*******************************************************************************/ - -/** - * For iNIC configurations - */ -//#define CONFIG_INIC_EN 0//enable iNIC mode -#if CONFIG_INIC_EN -#ifndef CONFIG_LWIP_LAYER -#define CONFIG_LWIP_LAYER 0 -#endif -#ifndef CONFIG_INIC_SDIO_HCI -#define CONFIG_INIC_SDIO_HCI 0 //for SDIO or USB iNIC -#endif -#ifndef CONFIG_INIC_CMD_RSP -#define CONFIG_INIC_CMD_RSP 0 -#endif -#ifndef CONFIG_INIC_USB_HCI -#define CONFIG_INIC_USB_HCI 0 -#endif -#endif -/******************End of iNIC configurations*******************/ - - -/* For WIFI GET BEACON FRAME example */ -#define CONFIG_EXAMPLE_GET_BEACON_FRAME 0 - -/* For WIFI MAC MONITOR example */ -#define CONFIG_EXAMPLE_WIFI_MAC_MONITOR 0 - -/* For HTTP CLIENT example */ -#define CONFIG_EXAMPLE_HTTP_CLIENT 0 - -/* For MQTT example */ -#define CONFIG_EXAMPLE_MQTT 0 - -/* For mDNS example */ -#define CONFIG_EXAMPLE_MDNS 0 - -/* For multicast example */ -#define CONFIG_EXAMPLE_MCAST 0 - -/* For XML example */ -#define CONFIG_EXAMPLE_XML 0 - -/* For socket select example */ -#define CONFIG_EXAMPLE_SOCKET_SELECT 0 - -/* For socket nonblocking connect example */ -#define CONFIG_EXAMPLE_NONBLOCK_CONNECT 0 - -/* For socket TCP bidirectional transmission example */ -#define CONFIG_EXAMPLE_SOCKET_TCP_TRX 0 - -/* For ssl download example */ -#define CONFIG_EXAMPLE_SSL_DOWNLOAD 0 - -/* For http download example */ -#define CONFIG_EXAMPLE_HTTP_DOWNLOAD 0 - -/* For httpc example */ -#define CONFIG_EXAMPLE_HTTPC 0 - -/* For httpd example */ -#define CONFIG_EXAMPLE_HTTPD 0 - -/* For tcp keepalive example */ -#define CONFIG_EXAMPLE_TCP_KEEPALIVE 0 - -/* For sntp show time example */ -#define CONFIG_EXAMPLE_SNTP_SHOWTIME 0 - - -/* For websocket client example */ -#define CONFIG_EXAMPLE_WEBSOCKET 0 - - -/* For UART Module AT command example */ -#define CONFIG_EXAMPLE_UART_ATCMD 0 -#if CONFIG_EXAMPLE_UART_ATCMD -#undef CONFIG_OTA_UPDATE -#define CONFIG_OTA_UPDATE 1 -#undef CONFIG_TRANSPORT -#define CONFIG_TRANSPORT 1 -#undef LOG_SERVICE_BUFLEN -#define LOG_SERVICE_BUFLEN 1600 -#undef CONFIG_LOG_SERVICE_LOCK -#define CONFIG_LOG_SERVICE_LOCK 1 -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - - - -/****************** For EAP method example *******************/ -#define CONFIG_EXAMPLE_EAP 0 - -// on/off specified eap method -#define CONFIG_ENABLE_PEAP 0 -#define CONFIG_ENABLE_TLS 0 -#define CONFIG_ENABLE_TTLS 0 - -// optional feature: whether to verify the cert of radius server -#define ENABLE_EAP_SSL_VERIFY_SERVER 0 - -#if CONFIG_ENABLE_PEAP || CONFIG_ENABLE_TLS || CONFIG_ENABLE_TTLS -#define CONFIG_ENABLE_EAP -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - -#if CONFIG_ENABLE_TLS -#define ENABLE_EAP_SSL_VERIFY_CLIENT 1 -#else -#define ENABLE_EAP_SSL_VERIFY_CLIENT 0 -#endif -/******************End of EAP configurations*******************/ - - -/* For iNIC host example*/ -#ifdef CONFIG_INIC_GSPI_HOST //this flag is defined in IAR project -#define CONFIG_EXAMPLE_INIC_GSPI_HOST 1 -#if CONFIG_EXAMPLE_INIC_GSPI_HOST - -#define CONFIG_INIC_HOST 1 - -#undef CONFIG_WLAN -#define CONFIG_WLAN 0 -#undef CONFIG_INCLUDE_SIMPLE_CONFIG -#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#undef CONFIG_LWIP_LAYER -#define CONFIG_LWIP_LAYER 1 -#undef CONFIG_BSD_TCP -#define CONFIG_BSD_TCP 1 - -#endif -#endif - -/*For uart update example*/ -#define CONFIG_UART_UPDATE 0 -#if CONFIG_UART_UPDATE -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - -/* For uart adapter example */ -/* Please also configure LWIP_UART_ADAPTER to 1 -in lwip_opt.h for support uart adapter*/ -#define CONFIG_EXAMPLE_UART_ADAPTER 0 -#if CONFIG_EXAMPLE_UART_ADAPTER -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1 -#undef CONFIG_EXAMPLE_MDNS -#define CONFIG_EXAMPLE_MDNS 1 -#endif - -/* For wifi scenarios example (Wi-Fi, WPS enrollee, P2P GO) */ -// also need to enable WPS and P2P -#define CONFIG_EXAMPLE_WLAN_SCENARIO 0 - -/* For broadcast example */ -#define CONFIG_EXAMPLE_BCAST 0 - -/* For high-load memory use case memory usage */ -#define CONFIG_EXAMPLE_HIGH_LOAD_MEMORY_USE 0 - -/* For rarp example */ -#define CONFIG_EXAMPLE_RARP 0 - -/* For ssl server example */ -#define CONFIG_EXAMPLE_SSL_SERVER 0 - -#if CONFIG_QQ_LINK -#define FATFS_R_10C -#define FATFS_DISK_USB 0 -#define FATFS_DISK_SD 1 -#endif - -#if CONFIG_ENABLE_WPS -#define WPS_CONNECT_RETRY_COUNT 4 -#define WPS_CONNECT_RETRY_INTERVAL 5000 // in ms -#endif - -#define AUTO_RECONNECT_COUNT 8 -#define AUTO_RECONNECT_INTERVAL 5 // in sec - -#if CONFIG_INIC_EN -#undef CONFIG_INCLUDE_SIMPLE_CONFIG -#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 -#define SUPPORT_INTERACTIVE_MODE 0 -#define CONFIG_INTERACTIVE_MODE 0 -#define CONFIG_INTERACTIVE_EXT 0 -#define CONFIG_OTA_UPDATE 0 -#endif - -#endif diff --git a/platform/realtek-ambz/fixups/inc/strproc.h b/platform/realtek-ambz/fixups/inc/strproc.h deleted file mode 100644 index 21e8b45..0000000 --- a/platform/realtek-ambz/fixups/inc/strproc.h +++ /dev/null @@ -1,22 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-11-26. */ - -// make not #define isprint, isdigit, isxdigit, islower and isspace -// this conflicts with stdlib , if is included before it - -// include before to get all its macros -#include - -// make 'static inline int _tolower' unused -#undef _tolower -#define _tolower _tolower_dummy - -#include_next - -// restore _tolower to ctype's macro -#undef _tolower -#define _tolower(__c) ((unsigned char)(__c) - 'A' + 'a') - -// dirty fix for compiling mbedTLS which uses _B as variable name -#ifdef CONFIG_SSL_RSA -#undef _B -#endif \ No newline at end of file diff --git a/platform/realtek-ambz/fixups/ssl_tls.c b/platform/realtek-ambz/fixups/ssl_tls.c deleted file mode 100644 index da23094..0000000 --- a/platform/realtek-ambz/fixups/ssl_tls.c +++ /dev/null @@ -1,7688 +0,0 @@ -/* - * SSLv3/TLSv1 shared functions - * - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - * - * 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 is part of mbed TLS (https://tls.mbed.org) - */ -/* - * The SSL 3.0 specification was drafted by Netscape in 1996, - * and became an IETF standard in 1999. - * - * http://wp.netscape.com/eng/ssl3/ - * http://www.ietf.org/rfc/rfc2246.txt - * http://www.ietf.org/rfc/rfc4346.txt - */ - -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif - -#ifdef RTL_HW_CRYPTO -#include -#endif - -#if defined(MBEDTLS_SSL_TLS_C) - -#if defined(MBEDTLS_PLATFORM_C) -#include "mbedtls/platform.h" -#else -#include -#define mbedtls_calloc calloc -#define mbedtls_free free -#endif - -#include "mbedtls/debug.h" -#include "mbedtls/ssl.h" -#include "mbedtls/ssl_internal.h" - -#include - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -#include "mbedtls/oid.h" -#endif - -/* Implementation that should never be optimized out by the compiler */ -static void mbedtls_zeroize( void *v, size_t n ) { - volatile unsigned char *p = v; while( n-- ) *p++ = 0; -} - -/* Length of the "epoch" field in the record header */ -static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl ) -{ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - return( 2 ); -#else - ((void) ssl); -#endif - return( 0 ); -} - -/* - * Start a timer. - * Passing millisecs = 0 cancels a running timer. - */ -static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ) -{ - if( ssl->f_set_timer == NULL ) - return; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) ); - ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs ); -} - -/* - * Return -1 is timer is expired, 0 if it isn't. - */ -static int ssl_check_timer( mbedtls_ssl_context *ssl ) -{ - if( ssl->f_get_timer == NULL ) - return( 0 ); - - if( ssl->f_get_timer( ssl->p_timer ) == 2 ) - { - MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) ); - return( -1 ); - } - - return( 0 ); -} - -#if defined(MBEDTLS_SSL_PROTO_DTLS) -/* - * Double the retransmit timeout value, within the allowed range, - * returning -1 if the maximum value has already been reached. - */ -static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) -{ - uint32_t new_timeout; - - if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max ) - return( -1 ); - - new_timeout = 2 * ssl->handshake->retransmit_timeout; - - /* Avoid arithmetic overflow and range overflow */ - if( new_timeout < ssl->handshake->retransmit_timeout || - new_timeout > ssl->conf->hs_timeout_max ) - { - new_timeout = ssl->conf->hs_timeout_max; - } - - ssl->handshake->retransmit_timeout = new_timeout; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", - ssl->handshake->retransmit_timeout ) ); - - return( 0 ); -} - -static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl ) -{ - ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min; - MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", - ssl->handshake->retransmit_timeout ) ); -} -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - -#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) -/* - * Convert max_fragment_length codes to length. - * RFC 6066 says: - * enum{ - * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255) - * } MaxFragmentLength; - * and we add 0 -> extension unused - */ -static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] = -{ - MBEDTLS_SSL_MAX_CONTENT_LEN, /* MBEDTLS_SSL_MAX_FRAG_LEN_NONE */ - 512, /* MBEDTLS_SSL_MAX_FRAG_LEN_512 */ - 1024, /* MBEDTLS_SSL_MAX_FRAG_LEN_1024 */ - 2048, /* MBEDTLS_SSL_MAX_FRAG_LEN_2048 */ - 4096, /* MBEDTLS_SSL_MAX_FRAG_LEN_4096 */ -}; -#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ - -#if defined(MBEDTLS_SSL_CLI_C) -static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src ) -{ - mbedtls_ssl_session_free( dst ); - memcpy( dst, src, sizeof( mbedtls_ssl_session ) ); - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - if( src->peer_cert != NULL ) - { - int ret; - - dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) ); - if( dst->peer_cert == NULL ) - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - - mbedtls_x509_crt_init( dst->peer_cert ); - - if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p, - src->peer_cert->raw.len ) ) != 0 ) - { - mbedtls_free( dst->peer_cert ); - dst->peer_cert = NULL; - return( ret ); - } - } -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) - if( src->ticket != NULL ) - { - dst->ticket = mbedtls_calloc( 1, src->ticket_len ); - if( dst->ticket == NULL ) - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - - memcpy( dst->ticket, src->ticket, src->ticket_len ); - } -#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ - - return( 0 ); -} -#endif /* MBEDTLS_SSL_CLI_C */ - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) -int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl, - const unsigned char *key_enc, const unsigned char *key_dec, - size_t keylen, - const unsigned char *iv_enc, const unsigned char *iv_dec, - size_t ivlen, - const unsigned char *mac_enc, const unsigned char *mac_dec, - size_t maclen ) = NULL; -int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL; -int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL; -int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL; -int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; -int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; -#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ - -/* - * Key material generation - */ -#if defined(MBEDTLS_SSL_PROTO_SSL3) -static int ssl3_prf( const unsigned char *secret, size_t slen, - const char *label, - const unsigned char *random, size_t rlen, - unsigned char *dstbuf, size_t dlen ) -{ - size_t i; - mbedtls_md5_context md5; - mbedtls_sha1_context sha1; - unsigned char padding[16]; - unsigned char sha1sum[20]; - ((void)label); - - mbedtls_md5_init( &md5 ); - mbedtls_sha1_init( &sha1 ); - - /* - * SSLv3: - * block = - * MD5( secret + SHA1( 'A' + secret + random ) ) + - * MD5( secret + SHA1( 'BB' + secret + random ) ) + - * MD5( secret + SHA1( 'CCC' + secret + random ) ) + - * ... - */ - for( i = 0; i < dlen / 16; i++ ) - { - memset( padding, (unsigned char) ('A' + i), 1 + i ); - - mbedtls_sha1_starts( &sha1 ); - mbedtls_sha1_update( &sha1, padding, 1 + i ); - mbedtls_sha1_update( &sha1, secret, slen ); - mbedtls_sha1_update( &sha1, random, rlen ); - mbedtls_sha1_finish( &sha1, sha1sum ); - - mbedtls_md5_starts( &md5 ); - mbedtls_md5_update( &md5, secret, slen ); - mbedtls_md5_update( &md5, sha1sum, 20 ); - mbedtls_md5_finish( &md5, dstbuf + i * 16 ); - } - - mbedtls_md5_free( &md5 ); - mbedtls_sha1_free( &sha1 ); - - mbedtls_zeroize( padding, sizeof( padding ) ); - mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); - - return( 0 ); -} -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) -static int tls1_prf( const unsigned char *secret, size_t slen, - const char *label, - const unsigned char *random, size_t rlen, - unsigned char *dstbuf, size_t dlen ) -{ - size_t nb, hs; - size_t i, j, k; - const unsigned char *_S1, *_S2; - unsigned char tmp[128]; - unsigned char h_i[20]; - const mbedtls_md_info_t *md_info; - mbedtls_md_context_t md_ctx; - int ret; - - mbedtls_md_init( &md_ctx ); - - if( sizeof( tmp ) < 20 + strlen( label ) + rlen ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - hs = ( slen + 1 ) / 2; - _S1 = secret; - _S2 = secret + slen - hs; - - nb = strlen( label ); - memcpy( tmp + 20, label, nb ); - memcpy( tmp + 20 + nb, random, rlen ); - nb += rlen; - - /* - * First compute P_md5(secret,label+random)[0..dlen] - */ - if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL ) - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - - if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) - return( ret ); - - mbedtls_md_hmac_starts( &md_ctx, _S1, hs ); - mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); - mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); - - for( i = 0; i < dlen; i += 16 ) - { - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb ); - mbedtls_md_hmac_finish( &md_ctx, h_i ); - - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 ); - mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); - - k = ( i + 16 > dlen ) ? dlen % 16 : 16; - - for( j = 0; j < k; j++ ) - dstbuf[i + j] = h_i[j]; - } - - mbedtls_md_free( &md_ctx ); - - /* - * XOR out with P_sha1(secret,label+random)[0..dlen] - */ - if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL ) - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - - if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) - return( ret ); - - mbedtls_md_hmac_starts( &md_ctx, _S2, hs ); - mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); - mbedtls_md_hmac_finish( &md_ctx, tmp ); - - for( i = 0; i < dlen; i += 20 ) - { - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb ); - mbedtls_md_hmac_finish( &md_ctx, h_i ); - - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, tmp, 20 ); - mbedtls_md_hmac_finish( &md_ctx, tmp ); - - k = ( i + 20 > dlen ) ? dlen % 20 : 20; - - for( j = 0; j < k; j++ ) - dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] ); - } - - mbedtls_md_free( &md_ctx ); - - mbedtls_zeroize( tmp, sizeof( tmp ) ); - mbedtls_zeroize( h_i, sizeof( h_i ) ); - - return( 0 ); -} -#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -static int tls_prf_generic( mbedtls_md_type_t md_type, - const unsigned char *secret, size_t slen, - const char *label, - const unsigned char *random, size_t rlen, - unsigned char *dstbuf, size_t dlen ) -{ - size_t nb; - size_t i, j, k, md_len; - unsigned char tmp[128]; - unsigned char h_i[MBEDTLS_MD_MAX_SIZE]; - const mbedtls_md_info_t *md_info; - mbedtls_md_context_t md_ctx; - int ret; - - mbedtls_md_init( &md_ctx ); - - if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL ) - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - - md_len = mbedtls_md_get_size( md_info ); - - if( sizeof( tmp ) < md_len + strlen( label ) + rlen ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - nb = strlen( label ); - memcpy( tmp + md_len, label, nb ); - memcpy( tmp + md_len + nb, random, rlen ); - nb += rlen; - - /* - * Compute P_(secret, label + random)[0..dlen] - */ - if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) - return( ret ); - - mbedtls_md_hmac_starts( &md_ctx, secret, slen ); - mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb ); - mbedtls_md_hmac_finish( &md_ctx, tmp ); - - for( i = 0; i < dlen; i += md_len ) - { - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb ); - mbedtls_md_hmac_finish( &md_ctx, h_i ); - - mbedtls_md_hmac_reset ( &md_ctx ); - mbedtls_md_hmac_update( &md_ctx, tmp, md_len ); - mbedtls_md_hmac_finish( &md_ctx, tmp ); - - k = ( i + md_len > dlen ) ? dlen % md_len : md_len; - - for( j = 0; j < k; j++ ) - dstbuf[i + j] = h_i[j]; - } - - mbedtls_md_free( &md_ctx ); - - mbedtls_zeroize( tmp, sizeof( tmp ) ); - mbedtls_zeroize( h_i, sizeof( h_i ) ); - - return( 0 ); -} - -#if defined(MBEDTLS_SHA256_C) -static int tls_prf_sha256( const unsigned char *secret, size_t slen, - const char *label, - const unsigned char *random, size_t rlen, - unsigned char *dstbuf, size_t dlen ) -{ - return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen, - label, random, rlen, dstbuf, dlen ) ); -} -#endif /* MBEDTLS_SHA256_C */ - -#if defined(MBEDTLS_SHA512_C) -static int tls_prf_sha384( const unsigned char *secret, size_t slen, - const char *label, - const unsigned char *random, size_t rlen, - unsigned char *dstbuf, size_t dlen ) -{ - return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen, - label, random, rlen, dstbuf, dlen ) ); -} -#endif /* MBEDTLS_SHA512_C */ -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t ); - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) -static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t ); -#endif - -#if defined(MBEDTLS_SSL_PROTO_SSL3) -static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * ); -static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int ); -#endif - -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) -static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * ); -static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int ); -#endif - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) -static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t ); -static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * ); -static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int ); -#endif - -#if defined(MBEDTLS_SHA512_C) -static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t ); -static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * ); -static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int ); -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) -{ - int ret = 0; - unsigned char tmp[64]; - unsigned char keyblk[256]; - unsigned char *key1; - unsigned char *key2; - unsigned char *mac_enc; - unsigned char *mac_dec; - size_t iv_copy_len; - const mbedtls_cipher_info_t *cipher_info; - const mbedtls_md_info_t *md_info; - - mbedtls_ssl_session *session = ssl->session_negotiate; - mbedtls_ssl_transform *transform = ssl->transform_negotiate; - mbedtls_ssl_handshake_params *handshake = ssl->handshake; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) ); - - cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher ); - if( cipher_info == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found", - transform->ciphersuite_info->cipher ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac ); - if( md_info == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found", - transform->ciphersuite_info->mac ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - /* - * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions - */ -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - handshake->tls_prf = ssl3_prf; - handshake->calc_verify = ssl_calc_verify_ssl; - handshake->calc_finished = ssl_calc_finished_ssl; - } - else -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) - if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) - { - handshake->tls_prf = tls1_prf; - handshake->calc_verify = ssl_calc_verify_tls; - handshake->calc_finished = ssl_calc_finished_tls; - } - else -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA512_C) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && - transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) - { - handshake->tls_prf = tls_prf_sha384; - handshake->calc_verify = ssl_calc_verify_tls_sha384; - handshake->calc_finished = ssl_calc_finished_tls_sha384; - } - else -#endif -#if defined(MBEDTLS_SHA256_C) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) - { - handshake->tls_prf = tls_prf_sha256; - handshake->calc_verify = ssl_calc_verify_tls_sha256; - handshake->calc_finished = ssl_calc_finished_tls_sha256; - } - else -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - /* - * SSLv3: - * master = - * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) + - * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) + - * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) ) - * - * TLSv1+: - * master = PRF( premaster, "master secret", randbytes )[0..47] - */ - if( handshake->resume == 0 ) - { - MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, - handshake->pmslen ); - -#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) - if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED ) - { - unsigned char session_hash[48]; - size_t hash_len; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) ); - - ssl->handshake->calc_verify( ssl, session_hash ); - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) - { -#if defined(MBEDTLS_SHA512_C) - if( ssl->transform_negotiate->ciphersuite_info->mac == - MBEDTLS_MD_SHA384 ) - { - hash_len = 48; - } - else -#endif - hash_len = 32; - } - else -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - hash_len = 36; - - MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len ); - - ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, - "extended master secret", - session_hash, hash_len, - session->master, 48 ); - if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); - return( ret ); - } - - } - else -#endif - ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, - "master secret", - handshake->randbytes, 64, - session->master, 48 ); - if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); - return( ret ); - } - - mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) ); - } - else - MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); - - /* - * Swap the client and server random values. - */ - memcpy( tmp, handshake->randbytes, 64 ); - memcpy( handshake->randbytes, tmp + 32, 32 ); - memcpy( handshake->randbytes + 32, tmp, 32 ); - mbedtls_zeroize( tmp, sizeof( tmp ) ); - - /* - * SSLv3: - * key block = - * MD5( master + SHA1( 'A' + master + randbytes ) ) + - * MD5( master + SHA1( 'BB' + master + randbytes ) ) + - * MD5( master + SHA1( 'CCC' + master + randbytes ) ) + - * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) + - * ... - * - * TLSv1: - * key block = PRF( master, "key expansion", randbytes ) - */ - ret = handshake->tls_prf( session->master, 48, "key expansion", - handshake->randbytes, 64, keyblk, 256 ); - if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s", - mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) ); - MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 ); - MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 ); - MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); - - mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) ); - - /* - * Determine the appropriate key, IV and MAC length. - */ - - transform->keylen = cipher_info->key_bitlen / 8; - - if( cipher_info->mode == MBEDTLS_MODE_GCM || - cipher_info->mode == MBEDTLS_MODE_CCM ) - { - transform->maclen = 0; - - transform->ivlen = 12; - transform->fixed_ivlen = 4; - - /* Minimum length is expicit IV + tag */ - transform->minlen = transform->ivlen - transform->fixed_ivlen - + ( transform->ciphersuite_info->flags & - MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16 ); - } - else - { - /* Initialize HMAC contexts */ - if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 || - ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); - return( ret ); - } - - /* Get MAC length */ - transform->maclen = mbedtls_md_get_size( md_info ); - -#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) - /* - * If HMAC is to be truncated, we shall keep the leftmost bytes, - * (rfc 6066 page 13 or rfc 2104 section 4), - * so we only need to adjust the length here. - */ - if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) - transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN; -#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ - - /* IV length */ - transform->ivlen = cipher_info->iv_size; - - /* Minimum length */ - if( cipher_info->mode == MBEDTLS_MODE_STREAM ) - transform->minlen = transform->maclen; - else - { - /* - * GenericBlockCipher: - * 1. if EtM is in use: one block plus MAC - * otherwise: * first multiple of blocklen greater than maclen - * 2. IV except for SSL3 and TLS 1.0 - */ -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) - { - transform->minlen = transform->maclen - + cipher_info->block_size; - } - else -#endif - { - transform->minlen = transform->maclen - + cipher_info->block_size - - transform->maclen % cipher_info->block_size; - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || - ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 ) - ; /* No need to adjust minlen */ - else -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 || - ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) - { - transform->minlen += transform->ivlen; - } - else -#endif - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - } - } - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d", - transform->keylen, transform->minlen, transform->ivlen, - transform->maclen ) ); - - /* - * Finally setup the cipher contexts, IVs and MAC secrets. - */ -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - { - key1 = keyblk + transform->maclen * 2; - key2 = keyblk + transform->maclen * 2 + transform->keylen; - - mac_enc = keyblk; - mac_dec = keyblk + transform->maclen; - - /* - * This is not used in TLS v1.1. - */ - iv_copy_len = ( transform->fixed_ivlen ) ? - transform->fixed_ivlen : transform->ivlen; - memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len ); - memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len, - iv_copy_len ); - } - else -#endif /* MBEDTLS_SSL_CLI_C */ -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - { - key1 = keyblk + transform->maclen * 2 + transform->keylen; - key2 = keyblk + transform->maclen * 2; - - mac_enc = keyblk + transform->maclen; - mac_dec = keyblk; - - /* - * This is not used in TLS v1.1. - */ - iv_copy_len = ( transform->fixed_ivlen ) ? - transform->fixed_ivlen : transform->ivlen; - memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len ); - memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len, - iv_copy_len ); - } - else -#endif /* MBEDTLS_SSL_SRV_C */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - if( transform->maclen > sizeof transform->mac_enc ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - memcpy( transform->mac_enc, mac_enc, transform->maclen ); - memcpy( transform->mac_dec, mac_dec, transform->maclen ); - } - else -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) - { - mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen ); - mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen ); - } - else -#endif - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_init != NULL ) - { - int ret = 0; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) ); - - if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen, - transform->iv_enc, transform->iv_dec, - iv_copy_len, - mac_enc, mac_dec, - transform->maclen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - } -#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ - -#if defined(MBEDTLS_SSL_EXPORT_KEYS) - if( ssl->conf->f_export_keys != NULL ) - { - ssl->conf->f_export_keys( ssl->conf->p_export_keys, - session->master, keyblk, - transform->maclen, transform->keylen, - iv_copy_len ); - } -#endif - - if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc, - cipher_info ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); - return( ret ); - } - - if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec, - cipher_info ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); - return( ret ); - } - - if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1, - cipher_info->key_bitlen, - MBEDTLS_ENCRYPT ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); - return( ret ); - } - - if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2, - cipher_info->key_bitlen, - MBEDTLS_DECRYPT ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); - return( ret ); - } - -#if defined(MBEDTLS_CIPHER_MODE_CBC) - if( cipher_info->mode == MBEDTLS_MODE_CBC ) - { - if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc, - MBEDTLS_PADDING_NONE ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); - return( ret ); - } - - if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec, - MBEDTLS_PADDING_NONE ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); - return( ret ); - } - } -#endif /* MBEDTLS_CIPHER_MODE_CBC */ - - mbedtls_zeroize( keyblk, sizeof( keyblk ) ); - -#if defined(MBEDTLS_ZLIB_SUPPORT) - // Initialize compression - // - if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) - { - if( ssl->compress_buf == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) ); - ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN ); - if( ssl->compress_buf == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", - MBEDTLS_SSL_BUFFER_LEN ) ); - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - } - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) ); - - memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) ); - memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) ); - - if( deflateInit( &transform->ctx_deflate, - Z_DEFAULT_COMPRESSION ) != Z_OK || - inflateInit( &transform->ctx_inflate ) != Z_OK ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) ); - return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); - } - } -#endif /* MBEDTLS_ZLIB_SUPPORT */ - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) ); - - return( 0 ); -} - -#if defined(MBEDTLS_SSL_PROTO_SSL3) -void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] ) -{ - mbedtls_md5_context md5; - mbedtls_sha1_context sha1; - unsigned char pad_1[48]; - unsigned char pad_2[48]; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) ); - - mbedtls_md5_init( &md5 ); - mbedtls_sha1_init( &sha1 ); - - mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); - mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); - - memset( pad_1, 0x36, 48 ); - memset( pad_2, 0x5C, 48 ); - - mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 ); - mbedtls_md5_update( &md5, pad_1, 48 ); - mbedtls_md5_finish( &md5, hash ); - - mbedtls_md5_starts( &md5 ); - mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 ); - mbedtls_md5_update( &md5, pad_2, 48 ); - mbedtls_md5_update( &md5, hash, 16 ); - mbedtls_md5_finish( &md5, hash ); - - mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 ); - mbedtls_sha1_update( &sha1, pad_1, 40 ); - mbedtls_sha1_finish( &sha1, hash + 16 ); - - mbedtls_sha1_starts( &sha1 ); - mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 ); - mbedtls_sha1_update( &sha1, pad_2, 40 ); - mbedtls_sha1_update( &sha1, hash + 16, 20 ); - mbedtls_sha1_finish( &sha1, hash + 16 ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); - - mbedtls_md5_free( &md5 ); - mbedtls_sha1_free( &sha1 ); - - return; -} -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) -void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] ) -{ - mbedtls_md5_context md5; - mbedtls_sha1_context sha1; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) ); - - mbedtls_md5_init( &md5 ); - mbedtls_sha1_init( &sha1 ); - - mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); - mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); - - mbedtls_md5_finish( &md5, hash ); - mbedtls_sha1_finish( &sha1, hash + 16 ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); - - mbedtls_md5_free( &md5 ); - mbedtls_sha1_free( &sha1 ); - - return; -} -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) -void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] ) -{ - mbedtls_sha256_context sha256; - - mbedtls_sha256_init( &sha256 ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) ); - - mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); - mbedtls_sha256_finish( &sha256, hash ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 ); - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); - - mbedtls_sha256_free( &sha256 ); - - return; -} -#endif /* MBEDTLS_SHA256_C */ - -#if defined(MBEDTLS_SHA512_C) -void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] ) -{ - mbedtls_sha512_context sha512; - - mbedtls_sha512_init( &sha512 ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) ); - - mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); - mbedtls_sha512_finish( &sha512, hash ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 ); - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); - - mbedtls_sha512_free( &sha512 ); - - return; -} -#endif /* MBEDTLS_SHA512_C */ -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) -int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ) -{ - unsigned char *p = ssl->handshake->premaster; - unsigned char *end = p + sizeof( ssl->handshake->premaster ); - const unsigned char *psk = ssl->conf->psk; - size_t psk_len = ssl->conf->psk_len; - - /* If the psk callback was called, use its result */ - if( ssl->handshake->psk != NULL ) - { - psk = ssl->handshake->psk; - psk_len = ssl->handshake->psk_len; - } - - /* - * PMS = struct { - * opaque other_secret<0..2^16-1>; - * opaque psk<0..2^16-1>; - * }; - * with "other_secret" depending on the particular key exchange - */ -#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) - if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK ) - { - if( end - p < 2 ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - *(p++) = (unsigned char)( psk_len >> 8 ); - *(p++) = (unsigned char)( psk_len ); - - if( end < p || (size_t)( end - p ) < psk_len ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - memset( p, 0, psk_len ); - p += psk_len; - } - else -#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ -#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) - if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) - { - /* - * other_secret already set by the ClientKeyExchange message, - * and is 48 bytes long - */ - *p++ = 0; - *p++ = 48; - p += 48; - } - else -#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ -#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) - if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) - { - int ret; - size_t len; - - /* Write length only when we know the actual value */ - if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, - p + 2, end - ( p + 2 ), &len, - ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); - return( ret ); - } - *(p++) = (unsigned char)( len >> 8 ); - *(p++) = (unsigned char)( len ); - p += len; - - MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); - } - else -#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ -#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) - if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) - { - int ret; - size_t zlen; - - if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen, - p + 2, end - ( p + 2 ), - ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); - return( ret ); - } - - *(p++) = (unsigned char)( zlen >> 8 ); - *(p++) = (unsigned char)( zlen ); - p += zlen; - - MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z ); - } - else -#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - /* opaque psk<0..2^16-1>; */ - if( end - p < 2 ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - *(p++) = (unsigned char)( psk_len >> 8 ); - *(p++) = (unsigned char)( psk_len ); - - if( end < p || (size_t)( end - p ) < psk_len ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - memcpy( p, psk, psk_len ); - p += psk_len; - - ssl->handshake->pmslen = p - ssl->handshake->premaster; - - return( 0 ); -} -#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ - -#if defined(MBEDTLS_SSL_PROTO_SSL3) -/* - * SSLv3.0 MAC functions - */ -static void ssl_mac( mbedtls_md_context_t *md_ctx, unsigned char *secret, - unsigned char *buf, size_t len, - unsigned char *ctr, int type ) -{ - unsigned char header[11]; - unsigned char padding[48]; - int padlen; - int md_size = mbedtls_md_get_size( md_ctx->md_info ); - int md_type = mbedtls_md_get_type( md_ctx->md_info ); - - /* Only MD5 and SHA-1 supported */ - if( md_type == MBEDTLS_MD_MD5 ) - padlen = 48; - else - padlen = 40; - - memcpy( header, ctr, 8 ); - header[ 8] = (unsigned char) type; - header[ 9] = (unsigned char)( len >> 8 ); - header[10] = (unsigned char)( len ); - - memset( padding, 0x36, padlen ); - mbedtls_md_starts( md_ctx ); - mbedtls_md_update( md_ctx, secret, md_size ); - mbedtls_md_update( md_ctx, padding, padlen ); - mbedtls_md_update( md_ctx, header, 11 ); - mbedtls_md_update( md_ctx, buf, len ); - mbedtls_md_finish( md_ctx, buf + len ); - - memset( padding, 0x5C, padlen ); - mbedtls_md_starts( md_ctx ); - mbedtls_md_update( md_ctx, secret, md_size ); - mbedtls_md_update( md_ctx, padding, padlen ); - mbedtls_md_update( md_ctx, buf + len, md_size ); - mbedtls_md_finish( md_ctx, buf + len ); -} -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - -#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ - ( defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) ) -#define SSL_SOME_MODES_USE_MAC -#endif - -/* - * Encryption/decryption functions - */ -static int ssl_encrypt_buf( mbedtls_ssl_context *ssl ) -{ - mbedtls_cipher_mode_t mode; - int auth_done = 0; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); - - if( ssl->session_out == NULL || ssl->transform_out == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload", - ssl->out_msg, ssl->out_msglen ); - - /* - * Add MAC before if needed - */ -#if defined(SSL_SOME_MODES_USE_MAC) - if( mode == MBEDTLS_MODE_STREAM || - ( mode == MBEDTLS_MODE_CBC -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED -#endif - ) ) - { -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - ssl_mac( &ssl->transform_out->md_ctx_enc, - ssl->transform_out->mac_enc, - ssl->out_msg, ssl->out_msglen, - ssl->out_ctr, ssl->out_msgtype ); - } - else -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) - { - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 ); - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 ); - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 ); - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, - ssl->out_msg, ssl->out_msglen ); - mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, - ssl->out_msg + ssl->out_msglen ); - mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc ); - } - else -#endif - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", - ssl->out_msg + ssl->out_msglen, - ssl->transform_out->maclen ); - - ssl->out_msglen += ssl->transform_out->maclen; - auth_done++; - } -#endif /* AEAD not the only option */ - - /* - * Encrypt - */ -#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) - if( mode == MBEDTLS_MODE_STREAM ) - { - int ret; - size_t olen = 0; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " - "including %d bytes of padding", - ssl->out_msglen, 0 ) ); - - if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc, - ssl->transform_out->iv_enc, - ssl->transform_out->ivlen, - ssl->out_msg, ssl->out_msglen, - ssl->out_msg, &olen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); - return( ret ); - } - - if( ssl->out_msglen != olen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - } - else -#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ -#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) - if( mode == MBEDTLS_MODE_GCM || - mode == MBEDTLS_MODE_CCM ) - { - int ret; - size_t enc_msglen, olen; - unsigned char *enc_msg; - unsigned char add_data[13]; - unsigned char taglen = ssl->transform_out->ciphersuite_info->flags & - MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; - - memcpy( add_data, ssl->out_ctr, 8 ); - add_data[8] = ssl->out_msgtype; - mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, - ssl->conf->transport, add_data + 9 ); - add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF; - add_data[12] = ssl->out_msglen & 0xFF; - - MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", - add_data, 13 ); - - /* - * Generate IV - */ - if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 ) - { - /* Reminder if we ever add an AEAD mode with a different size */ - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen, - ssl->out_ctr, 8 ); - memcpy( ssl->out_iv, ssl->out_ctr, 8 ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv, - ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen ); - - /* - * Fix pointer positions and message length with added IV - */ - enc_msg = ssl->out_msg; - enc_msglen = ssl->out_msglen; - ssl->out_msglen += ssl->transform_out->ivlen - - ssl->transform_out->fixed_ivlen; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " - "including %d bytes of padding", - ssl->out_msglen, 0 ) ); - - /* - * Encrypt and authenticate - */ - if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc, - ssl->transform_out->iv_enc, - ssl->transform_out->ivlen, - add_data, 13, - enc_msg, enc_msglen, - enc_msg, &olen, - enc_msg + enc_msglen, taglen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); - return( ret ); - } - - if( olen != enc_msglen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - ssl->out_msglen += taglen; - auth_done++; - - MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen ); - } - else -#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ -#if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) - if( mode == MBEDTLS_MODE_CBC ) - { - int ret; - unsigned char *enc_msg; - size_t enc_msglen, padlen, olen = 0, i; - - padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) % - ssl->transform_out->ivlen; - if( padlen == ssl->transform_out->ivlen ) - padlen = 0; - - for( i = 0; i <= padlen; i++ ) - ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen; - - ssl->out_msglen += padlen + 1; - - enc_msglen = ssl->out_msglen; - enc_msg = ssl->out_msg; - -#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) - /* - * Prepend per-record IV for block cipher in TLS v1.1 and up as per - * Method 1 (6.2.3.2. in RFC4346 and RFC5246) - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - /* - * Generate IV - */ - ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc, - ssl->transform_out->ivlen ); - if( ret != 0 ) - return( ret ); - - memcpy( ssl->out_iv, ssl->transform_out->iv_enc, - ssl->transform_out->ivlen ); - - /* - * Fix pointer positions and message length with added IV - */ - enc_msg = ssl->out_msg; - enc_msglen = ssl->out_msglen; - ssl->out_msglen += ssl->transform_out->ivlen; - } -#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " - "including %d bytes of IV and %d bytes of padding", - ssl->out_msglen, ssl->transform_out->ivlen, - padlen + 1 ) ); - - if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc, - ssl->transform_out->iv_enc, - ssl->transform_out->ivlen, - enc_msg, enc_msglen, - enc_msg, &olen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); - return( ret ); - } - - if( enc_msglen != olen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) - if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) - { - /* - * Save IV in SSL3 and TLS1 - */ - memcpy( ssl->transform_out->iv_enc, - ssl->transform_out->cipher_ctx_enc.iv, - ssl->transform_out->ivlen ); - } -#endif - -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - if( auth_done == 0 ) - { - /* - * MAC(MAC_write_key, seq_num + - * TLSCipherText.type + - * TLSCipherText.version + - * length_of( (IV +) ENC(...) ) + - * IV + // except for TLS 1.0 - * ENC(content + padding + padding_length)); - */ - unsigned char pseudo_hdr[13]; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); - - memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 ); - memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 ); - pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF ); - pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 ); - - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 ); - mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, - ssl->out_iv, ssl->out_msglen ); - mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, - ssl->out_iv + ssl->out_msglen ); - mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc ); - - ssl->out_msglen += ssl->transform_out->maclen; - auth_done++; - } -#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ - } - else -#endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - /* Make extra sure authentication was performed, exactly once */ - if( auth_done != 1 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); - - return( 0 ); -} - -#define SSL_MAX_MAC_SIZE 48 - -static int ssl_decrypt_buf( mbedtls_ssl_context *ssl ) -{ - size_t i; - mbedtls_cipher_mode_t mode; - int auth_done = 0; -#if defined(SSL_SOME_MODES_USE_MAC) - size_t padlen = 0, correct = 1; -#endif - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); - - if( ssl->session_in == NULL || ssl->transform_in == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec ); - - if( ssl->in_msglen < ssl->transform_in->minlen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)", - ssl->in_msglen, ssl->transform_in->minlen ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - -#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) - if( mode == MBEDTLS_MODE_STREAM ) - { - int ret; - size_t olen = 0; - - padlen = 0; - - if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec, - ssl->transform_in->iv_dec, - ssl->transform_in->ivlen, - ssl->in_msg, ssl->in_msglen, - ssl->in_msg, &olen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); - return( ret ); - } - - if( ssl->in_msglen != olen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - } - else -#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ -#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) - if( mode == MBEDTLS_MODE_GCM || - mode == MBEDTLS_MODE_CCM ) - { - int ret; - size_t dec_msglen, olen; - unsigned char *dec_msg; - unsigned char *dec_msg_result; - unsigned char add_data[13]; - unsigned char taglen = ssl->transform_in->ciphersuite_info->flags & - MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; - size_t explicit_iv_len = ssl->transform_in->ivlen - - ssl->transform_in->fixed_ivlen; - - if( ssl->in_msglen < explicit_iv_len + taglen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) " - "+ taglen (%d)", ssl->in_msglen, - explicit_iv_len, taglen ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - dec_msglen = ssl->in_msglen - explicit_iv_len - taglen; - - dec_msg = ssl->in_msg; - dec_msg_result = ssl->in_msg; - ssl->in_msglen = dec_msglen; - - memcpy( add_data, ssl->in_ctr, 8 ); - add_data[8] = ssl->in_msgtype; - mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, - ssl->conf->transport, add_data + 9 ); - add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF; - add_data[12] = ssl->in_msglen & 0xFF; - - MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", - add_data, 13 ); - - memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen, - ssl->in_iv, - ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec, - ssl->transform_in->ivlen ); - MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen ); - - /* - * Decrypt and authenticate - */ - if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec, - ssl->transform_in->iv_dec, - ssl->transform_in->ivlen, - add_data, 13, - dec_msg, dec_msglen, - dec_msg_result, &olen, - dec_msg + dec_msglen, taglen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret ); - - if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - - return( ret ); - } - auth_done++; - - if( olen != dec_msglen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - } - else -#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ -#if defined(MBEDTLS_CIPHER_MODE_CBC) && \ - ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) - if( mode == MBEDTLS_MODE_CBC ) - { - /* - * Decrypt and check the padding - */ - int ret; - unsigned char *dec_msg; - unsigned char *dec_msg_result; - size_t dec_msglen; - size_t minlen = 0; - size_t olen = 0; - - /* - * Check immediate ciphertext sanity - */ -#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - minlen += ssl->transform_in->ivlen; -#endif - - if( ssl->in_msglen < minlen + ssl->transform_in->ivlen || - ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) " - "+ 1 ) ( + expl IV )", ssl->in_msglen, - ssl->transform_in->ivlen, - ssl->transform_in->maclen ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - - dec_msglen = ssl->in_msglen; - dec_msg = ssl->in_msg; - dec_msg_result = ssl->in_msg; - - /* - * Authenticate before decrypt if enabled - */ -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) - { - unsigned char computed_mac[SSL_MAX_MAC_SIZE]; - unsigned char pseudo_hdr[13]; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); - - dec_msglen -= ssl->transform_in->maclen; - ssl->in_msglen -= ssl->transform_in->maclen; - - memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 ); - memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 ); - pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF ); - pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 ); - - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 ); - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, - ssl->in_iv, ssl->in_msglen ); - mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac ); - mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen, - ssl->transform_in->maclen ); - MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", computed_mac, - ssl->transform_in->maclen ); - - if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac, - ssl->transform_in->maclen ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); - - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - auth_done++; - } -#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ - - /* - * Check length sanity - */ - if( ssl->in_msglen % ssl->transform_in->ivlen != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0", - ssl->in_msglen, ssl->transform_in->ivlen ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - -#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) - /* - * Initialize for prepended IV for block cipher in TLS v1.1 and up - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - dec_msglen -= ssl->transform_in->ivlen; - ssl->in_msglen -= ssl->transform_in->ivlen; - - for( i = 0; i < ssl->transform_in->ivlen; i++ ) - ssl->transform_in->iv_dec[i] = ssl->in_iv[i]; - } -#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ - - if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec, - ssl->transform_in->iv_dec, - ssl->transform_in->ivlen, - dec_msg, dec_msglen, - dec_msg_result, &olen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); - return( ret ); - } - - if( dec_msglen != olen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) - if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) - { - /* - * Save IV in SSL3 and TLS1 - */ - memcpy( ssl->transform_in->iv_dec, - ssl->transform_in->cipher_ctx_dec.iv, - ssl->transform_in->ivlen ); - } -#endif - - padlen = 1 + ssl->in_msg[ssl->in_msglen - 1]; - - if( ssl->in_msglen < ssl->transform_in->maclen + padlen && - auth_done == 0 ) - { -#if defined(MBEDTLS_SSL_DEBUG_ALL) - MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)", - ssl->in_msglen, ssl->transform_in->maclen, padlen ) ); -#endif - padlen = 0; - correct = 0; - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - if( padlen > ssl->transform_in->ivlen ) - { -#if defined(MBEDTLS_SSL_DEBUG_ALL) - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, " - "should be no more than %d", - padlen, ssl->transform_in->ivlen ) ); -#endif - correct = 0; - } - } - else -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) - { - /* - * TLSv1+: always check the padding up to the first failure - * and fake check up to 256 bytes of padding - */ - size_t pad_count = 0, real_count = 1; - size_t padding_idx = ssl->in_msglen - padlen - 1; - - /* - * Padding is guaranteed to be incorrect if: - * 1. padlen >= ssl->in_msglen - * - * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN + - * ssl->transform_in->maclen - * - * In both cases we reset padding_idx to a safe value (0) to - * prevent out-of-buffer reads. - */ - correct &= ( ssl->in_msglen >= padlen + 1 ); - correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN + - ssl->transform_in->maclen ); - - padding_idx *= correct; - - for( i = 1; i <= 256; i++ ) - { - real_count &= ( i <= padlen ); - pad_count += real_count * - ( ssl->in_msg[padding_idx + i] == padlen - 1 ); - } - - correct &= ( pad_count == padlen ); /* Only 1 on correct padding */ - -#if defined(MBEDTLS_SSL_DEBUG_ALL) - if( padlen > 0 && correct == 0 ) - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); -#endif - padlen &= correct * 0x1FF; - } - else -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ - MBEDTLS_SSL_PROTO_TLS1_2 */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - ssl->in_msglen -= padlen; - } - else -#endif /* MBEDTLS_CIPHER_MODE_CBC && - ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption", - ssl->in_msg, ssl->in_msglen ); - - /* - * Authenticate if not done yet. - * Compute the MAC regardless of the padding result (RFC4346, CBCTIME). - */ -#if defined(SSL_SOME_MODES_USE_MAC) - if( auth_done == 0 ) - { - unsigned char tmp[SSL_MAX_MAC_SIZE]; - - ssl->in_msglen -= ssl->transform_in->maclen; - - ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 ); - ssl->in_len[1] = (unsigned char)( ssl->in_msglen ); - - memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ); - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - ssl_mac( &ssl->transform_in->md_ctx_dec, - ssl->transform_in->mac_dec, - ssl->in_msg, ssl->in_msglen, - ssl->in_ctr, ssl->in_msgtype ); - } - else -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) - { - /* - * Process MAC and always update for padlen afterwards to make - * total time independent of padlen - * - * extra_run compensates MAC check for padlen - * - * Known timing attacks: - * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf) - * - * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values - * correctly. (We round down instead of up, so -56 is the correct - * value for our calculations instead of -55) - */ - size_t j, extra_run = 0; - extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 - - ( 13 + ssl->in_msglen + 8 ) / 64; - - extra_run &= correct * 0xFF; - - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 ); - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 ); - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 ); - mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg, - ssl->in_msglen ); - mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, - ssl->in_msg + ssl->in_msglen ); - /* Call mbedtls_md_process at least once due to cache attacks */ - for( j = 0; j < extra_run + 1; j++ ) - mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg ); - - mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec ); - } - else -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ - MBEDTLS_SSL_PROTO_TLS1_2 */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen ); - MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen, - ssl->transform_in->maclen ); - - if( mbedtls_ssl_safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen, - ssl->transform_in->maclen ) != 0 ) - { -#if defined(MBEDTLS_SSL_DEBUG_ALL) - MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); -#endif - correct = 0; - } - auth_done++; - - /* - * Finally check the correct flag - */ - if( correct == 0 ) - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } -#endif /* SSL_SOME_MODES_USE_MAC */ - - /* Make extra sure authentication was performed, exactly once */ - if( auth_done != 1 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - if( ssl->in_msglen == 0 ) - { - ssl->nb_zero++; - - /* - * Three or more empty messages may be a DoS attack - * (excessive CPU consumption). - */ - if( ssl->nb_zero > 3 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty " - "messages, possible DoS attack" ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } - } - else - ssl->nb_zero = 0; - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - ; /* in_ctr read from peer, not maintained internally */ - } - else -#endif - { - for( i = 8; i > ssl_ep_len( ssl ); i-- ) - if( ++ssl->in_ctr[i - 1] != 0 ) - break; - - /* The loop goes to its end iff the counter is wrapping */ - if( i == ssl_ep_len( ssl ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) ); - return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); - } - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); - - return( 0 ); -} - -#undef MAC_NONE -#undef MAC_PLAINTEXT -#undef MAC_CIPHERTEXT - -#if defined(MBEDTLS_ZLIB_SUPPORT) -/* - * Compression/decompression functions - */ -static int ssl_compress_buf( mbedtls_ssl_context *ssl ) -{ - int ret; - unsigned char *msg_post = ssl->out_msg; - size_t len_pre = ssl->out_msglen; - unsigned char *msg_pre = ssl->compress_buf; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); - - if( len_pre == 0 ) - return( 0 ); - - memcpy( msg_pre, ssl->out_msg, len_pre ); - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ", - ssl->out_msglen ) ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload", - ssl->out_msg, ssl->out_msglen ); - - ssl->transform_out->ctx_deflate.next_in = msg_pre; - ssl->transform_out->ctx_deflate.avail_in = len_pre; - ssl->transform_out->ctx_deflate.next_out = msg_post; - ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN; - - ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); - if( ret != Z_OK ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); - return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); - } - - ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN - - ssl->transform_out->ctx_deflate.avail_out; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ", - ssl->out_msglen ) ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload", - ssl->out_msg, ssl->out_msglen ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); - - return( 0 ); -} - -static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) -{ - int ret; - unsigned char *msg_post = ssl->in_msg; - size_t len_pre = ssl->in_msglen; - unsigned char *msg_pre = ssl->compress_buf; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); - - if( len_pre == 0 ) - return( 0 ); - - memcpy( msg_pre, ssl->in_msg, len_pre ); - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ", - ssl->in_msglen ) ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload", - ssl->in_msg, ssl->in_msglen ); - - ssl->transform_in->ctx_inflate.next_in = msg_pre; - ssl->transform_in->ctx_inflate.avail_in = len_pre; - ssl->transform_in->ctx_inflate.next_out = msg_post; - ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN; - - ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); - if( ret != Z_OK ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); - return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); - } - - ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN - - ssl->transform_in->ctx_inflate.avail_out; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ", - ssl->in_msglen ) ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload", - ssl->in_msg, ssl->in_msglen ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); - - return( 0 ); -} -#endif /* MBEDTLS_ZLIB_SUPPORT */ - -#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) -static int ssl_write_hello_request( mbedtls_ssl_context *ssl ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) -static int ssl_resend_hello_request( mbedtls_ssl_context *ssl ) -{ - /* If renegotiation is not enforced, retransmit until we would reach max - * timeout if we were using the usual handshake doubling scheme */ - if( ssl->conf->renego_max_records < 0 ) - { - uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1; - unsigned char doublings = 1; - - while( ratio != 0 ) - { - ++doublings; - ratio >>= 1; - } - - if( ++ssl->renego_records_seen > doublings ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) ); - return( 0 ); - } - } - - return( ssl_write_hello_request( ssl ) ); -} -#endif -#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ - -/* - * Fill the input message buffer by appending data to it. - * The amount of data already fetched is in ssl->in_left. - * - * If we return 0, is it guaranteed that (at least) nb_want bytes are - * available (from this read and/or a previous one). Otherwise, an error code - * is returned (possibly EOF or WANT_READ). - * - * With stream transport (TLS) on success ssl->in_left == nb_want, but - * with datagram transport (DTLS) on success ssl->in_left >= nb_want, - * since we always read a whole datagram at once. - * - * For DTLS, it is up to the caller to set ssl->next_record_offset when - * they're done reading a record. - */ -int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) -{ - int ret; - size_t len; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); - - if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " - "or mbedtls_ssl_set_bio()" ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - uint32_t timeout; - - /* Just to be sure */ - if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use " - "mbedtls_ssl_set_timer_cb() for DTLS" ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - /* - * The point is, we need to always read a full datagram at once, so we - * sometimes read more then requested, and handle the additional data. - * It could be the rest of the current record (while fetching the - * header) and/or some other records in the same datagram. - */ - - /* - * Move to the next record in the already read datagram if applicable - */ - if( ssl->next_record_offset != 0 ) - { - if( ssl->in_left < ssl->next_record_offset ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - ssl->in_left -= ssl->next_record_offset; - - if( ssl->in_left != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d", - ssl->next_record_offset ) ); - memmove( ssl->in_hdr, - ssl->in_hdr + ssl->next_record_offset, - ssl->in_left ); - } - - ssl->next_record_offset = 0; - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", - ssl->in_left, nb_want ) ); - - /* - * Done if we already have enough data. - */ - if( nb_want <= ssl->in_left) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); - return( 0 ); - } - - /* - * A record can't be split accross datagrams. If we need to read but - * are not at the beginning of a new record, the caller did something - * wrong. - */ - if( ssl->in_left != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - /* - * Don't even try to read if time's out already. - * This avoids by-passing the timer when repeatedly receiving messages - * that will end up being dropped. - */ - if( ssl_check_timer( ssl ) != 0 ) - ret = MBEDTLS_ERR_SSL_TIMEOUT; - else - { - len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf ); - - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - timeout = ssl->handshake->retransmit_timeout; - else - timeout = ssl->conf->read_timeout; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) ); - - if( ssl->f_recv_timeout != NULL ) - ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len, - timeout ); - else - ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len ); - - MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); - - if( ret == 0 ) - return( MBEDTLS_ERR_SSL_CONN_EOF ); - } - - if( ret == MBEDTLS_ERR_SSL_TIMEOUT ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) ); - ssl_set_timer( ssl, 0 ); - - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - { - if( ssl_double_retransmit_timeout( ssl ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) ); - return( MBEDTLS_ERR_SSL_TIMEOUT ); - } - - if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); - return( ret ); - } - - return( MBEDTLS_ERR_SSL_WANT_READ ); - } -#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) - else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) - { - if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret ); - return( ret ); - } - - return( MBEDTLS_ERR_SSL_WANT_READ ); - } -#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ - } - - if( ret < 0 ) - return( ret ); - - ssl->in_left = ret; - } - else -#endif - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", - ssl->in_left, nb_want ) ); - - while( ssl->in_left < nb_want ) - { - len = nb_want - ssl->in_left; - - if( ssl_check_timer( ssl ) != 0 ) - ret = MBEDTLS_ERR_SSL_TIMEOUT; - else - { - if( ssl->f_recv_timeout != NULL ) - { - ret = ssl->f_recv_timeout( ssl->p_bio, - ssl->in_hdr + ssl->in_left, len, - ssl->conf->read_timeout ); - } - else - { - ret = ssl->f_recv( ssl->p_bio, - ssl->in_hdr + ssl->in_left, len ); - } - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", - ssl->in_left, nb_want ) ); - MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); - - if( ret == 0 ) - return( MBEDTLS_ERR_SSL_CONN_EOF ); - - if( ret < 0 ) - return( ret ); - - ssl->in_left += ret; - } - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); - - return( 0 ); -} - -/* - * Flush any data not yet written - */ -int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) -{ - int ret; - unsigned char *buf, i; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); - - if( ssl->f_send == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " - "or mbedtls_ssl_set_bio()" ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - /* Avoid incrementing counter if data is flushed */ - if( ssl->out_left == 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); - return( 0 ); - } - - while( ssl->out_left > 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d", - mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) ); - - buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) + - ssl->out_msglen - ssl->out_left; - ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left ); - - MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret ); - - if( ret <= 0 ) - return( ret ); - - ssl->out_left -= ret; - } - - for( i = 8; i > ssl_ep_len( ssl ); i-- ) - if( ++ssl->out_ctr[i - 1] != 0 ) - break; - - /* The loop goes to its end iff the counter is wrapping */ - if( i == ssl_ep_len( ssl ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) ); - return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); - - return( 0 ); -} - -/* - * Functions to handle the DTLS retransmission state machine - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) -/* - * Append current handshake message to current outgoing flight - */ -static int ssl_flight_append( mbedtls_ssl_context *ssl ) -{ - mbedtls_ssl_flight_item *msg; - - /* Allocate space for current message */ - if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", - sizeof( mbedtls_ssl_flight_item ) ) ); - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) ); - mbedtls_free( msg ); - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - /* Copy current handshake message with headers */ - memcpy( msg->p, ssl->out_msg, ssl->out_msglen ); - msg->len = ssl->out_msglen; - msg->type = ssl->out_msgtype; - msg->next = NULL; - - /* Append to the current flight */ - if( ssl->handshake->flight == NULL ) - ssl->handshake->flight = msg; - else - { - mbedtls_ssl_flight_item *cur = ssl->handshake->flight; - while( cur->next != NULL ) - cur = cur->next; - cur->next = msg; - } - - return( 0 ); -} - -/* - * Free the current flight of handshake messages - */ -static void ssl_flight_free( mbedtls_ssl_flight_item *flight ) -{ - mbedtls_ssl_flight_item *cur = flight; - mbedtls_ssl_flight_item *next; - - while( cur != NULL ) - { - next = cur->next; - - mbedtls_free( cur->p ); - mbedtls_free( cur ); - - cur = next; - } -} - -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) -static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ); -#endif - -/* - * Swap transform_out and out_ctr with the alternative ones - */ -static void ssl_swap_epochs( mbedtls_ssl_context *ssl ) -{ - mbedtls_ssl_transform *tmp_transform; - unsigned char tmp_out_ctr[8]; - - if( ssl->transform_out == ssl->handshake->alt_transform_out ) - { - MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) ); - return; - } - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) ); - - /* Swap transforms */ - tmp_transform = ssl->transform_out; - ssl->transform_out = ssl->handshake->alt_transform_out; - ssl->handshake->alt_transform_out = tmp_transform; - - /* Swap epoch + sequence_number */ - memcpy( tmp_out_ctr, ssl->out_ctr, 8 ); - memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 ); - memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 ); - - /* Adjust to the newly activated transform */ - if( ssl->transform_out != NULL && - ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen - - ssl->transform_out->fixed_ivlen; - } - else - ssl->out_msg = ssl->out_iv; - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_activate != NULL ) - { - if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - } -#endif -} - -/* - * Retransmit the current flight of messages. - * - * Need to remember the current message in case flush_output returns - * WANT_WRITE, causing us to exit this function and come back later. - * This function must be called until state is no longer SENDING. - */ -int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ) -{ - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) ); - - if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) ); - - ssl->handshake->cur_msg = ssl->handshake->flight; - ssl_swap_epochs( ssl ); - - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING; - } - - while( ssl->handshake->cur_msg != NULL ) - { - int ret; - mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg; - - /* Swap epochs before sending Finished: we can't do it after - * sending ChangeCipherSpec, in case write returns WANT_READ. - * Must be done before copying, may change out_msg pointer */ - if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE && - cur->p[0] == MBEDTLS_SSL_HS_FINISHED ) - { - ssl_swap_epochs( ssl ); - } - - memcpy( ssl->out_msg, cur->p, cur->len ); - ssl->out_msglen = cur->len; - ssl->out_msgtype = cur->type; - - ssl->handshake->cur_msg = cur->next; - - MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 ); - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - } - - if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; - else - { - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; - ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) ); - - return( 0 ); -} - -/* - * To be called when the last message of an incoming flight is received. - */ -void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ) -{ - /* We won't need to resend that one any more */ - ssl_flight_free( ssl->handshake->flight ); - ssl->handshake->flight = NULL; - ssl->handshake->cur_msg = NULL; - - /* The next incoming flight will start with this msg_seq */ - ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq; - - /* Cancel timer */ - ssl_set_timer( ssl, 0 ); - - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) - { - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; - } - else - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; -} - -/* - * To be called when the last message of an outgoing flight is send. - */ -void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ) -{ - ssl_reset_retransmit_timeout( ssl ); - ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); - - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) - { - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; - } - else - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; -} -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - -/* - * Record layer functions - */ - -/* - * Write current record. - * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg. - */ -int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl ) -{ - int ret, done = 0, out_msg_type; - size_t len = ssl->out_msglen; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake != NULL && - ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) - { - ; /* Skip special handshake treatment when resending */ - } - else -#endif - if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) - { - out_msg_type = ssl->out_msg[0]; - - if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST && - ssl->handshake == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 ); - ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 ); - ssl->out_msg[3] = (unsigned char)( ( len - 4 ) ); - - /* - * DTLS has additional fields in the Handshake layer, - * between the length field and the actual payload: - * uint16 message_seq; - * uint24 fragment_offset; - * uint24 fragment_length; - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - /* Make room for the additional DTLS fields */ - memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 ); - ssl->out_msglen += 8; - len += 8; - - /* Write message_seq and update it, except for HelloRequest */ - if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) - { - ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF; - ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF; - ++( ssl->handshake->out_msg_seq ); - } - else - { - ssl->out_msg[4] = 0; - ssl->out_msg[5] = 0; - } - - /* We don't fragment, so frag_offset = 0 and frag_len = len */ - memset( ssl->out_msg + 6, 0x00, 3 ); - memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 ); - } -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - - if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) - ssl->handshake->update_checksum( ssl, ssl->out_msg, len ); - } - - /* Save handshake and CCS messages for resending */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake != NULL && - ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING && - ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC || - ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) ) - { - if( ( ret = ssl_flight_append( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret ); - return( ret ); - } - } -#endif - -#if defined(MBEDTLS_ZLIB_SUPPORT) - if( ssl->transform_out != NULL && - ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) - { - if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); - return( ret ); - } - - len = ssl->out_msglen; - } -#endif /*MBEDTLS_ZLIB_SUPPORT */ - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_write != NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) ); - - ret = mbedtls_ssl_hw_record_write( ssl ); - if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - - if( ret == 0 ) - done = 1; - } -#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ - if( !done ) - { - ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; - mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, - ssl->conf->transport, ssl->out_hdr + 1 ); - - ssl->out_len[0] = (unsigned char)( len >> 8 ); - ssl->out_len[1] = (unsigned char)( len ); - - if( ssl->transform_out != NULL ) - { - if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); - return( ret ); - } - - len = ssl->out_msglen; - ssl->out_len[0] = (unsigned char)( len >> 8 ); - ssl->out_len[1] = (unsigned char)( len ); - } - - ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, " - "version = [%d:%d], msglen = %d", - ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2], - ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", - ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen ); - } - - if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) ); - - return( 0 ); -} - -#if defined(MBEDTLS_SSL_PROTO_DTLS) -/* - * Mark bits in bitmask (used for DTLS HS reassembly) - */ -static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len ) -{ - unsigned int start_bits, end_bits; - - start_bits = 8 - ( offset % 8 ); - if( start_bits != 8 ) - { - size_t first_byte_idx = offset / 8; - - /* Special case */ - if( len <= start_bits ) - { - for( ; len != 0; len-- ) - mask[first_byte_idx] |= 1 << ( start_bits - len ); - - /* Avoid potential issues with offset or len becoming invalid */ - return; - } - - offset += start_bits; /* Now offset % 8 == 0 */ - len -= start_bits; - - for( ; start_bits != 0; start_bits-- ) - mask[first_byte_idx] |= 1 << ( start_bits - 1 ); - } - - end_bits = len % 8; - if( end_bits != 0 ) - { - size_t last_byte_idx = ( offset + len ) / 8; - - len -= end_bits; /* Now len % 8 == 0 */ - - for( ; end_bits != 0; end_bits-- ) - mask[last_byte_idx] |= 1 << ( 8 - end_bits ); - } - - memset( mask + offset / 8, 0xFF, len / 8 ); -} - -/* - * Check that bitmask is full - */ -static int ssl_bitmask_check( unsigned char *mask, size_t len ) -{ - size_t i; - - for( i = 0; i < len / 8; i++ ) - if( mask[i] != 0xFF ) - return( -1 ); - - for( i = 0; i < len % 8; i++ ) - if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 ) - return( -1 ); - - return( 0 ); -} - -/* - * Reassemble fragmented DTLS handshake messages. - * - * Use a temporary buffer for reassembly, divided in two parts: - * - the first holds the reassembled message (including handshake header), - * - the second holds a bitmask indicating which parts of the message - * (excluding headers) have been received so far. - */ -static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl ) -{ - unsigned char *msg, *bitmask; - size_t frag_len, frag_off; - size_t msg_len = ssl->in_hslen - 12; /* Without headers */ - - if( ssl->handshake == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) ); - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); - } - - /* - * For first fragment, check size and allocate buffer - */ - if( ssl->handshake->hs_msg == NULL ) - { - size_t alloc_len; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d", - msg_len ) ); - - if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) ); - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); - } - - /* The bitmask needs one bit per byte of message excluding header */ - alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 ); - - ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len ); - if( ssl->handshake->hs_msg == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) ); - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - /* Prepare final header: copy msg_type, length and message_seq, - * then add standardised fragment_offset and fragment_length */ - memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 ); - memset( ssl->handshake->hs_msg + 6, 0, 3 ); - memcpy( ssl->handshake->hs_msg + 9, - ssl->handshake->hs_msg + 1, 3 ); - } - else - { - /* Make sure msg_type and length are consistent */ - if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - } - - msg = ssl->handshake->hs_msg + 12; - bitmask = msg + msg_len; - - /* - * Check and copy current fragment - */ - frag_off = ( ssl->in_msg[6] << 16 ) | - ( ssl->in_msg[7] << 8 ) | - ssl->in_msg[8]; - frag_len = ( ssl->in_msg[9] << 16 ) | - ( ssl->in_msg[10] << 8 ) | - ssl->in_msg[11]; - - if( frag_off + frag_len > msg_len ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d", - frag_off, frag_len, msg_len ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - if( frag_len + 12 > ssl->in_msglen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d", - frag_len, ssl->in_msglen ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d", - frag_off, frag_len ) ); - - memcpy( msg + frag_off, ssl->in_msg + 12, frag_len ); - ssl_bitmask_set( bitmask, frag_off, frag_len ); - - /* - * Do we have the complete message by now? - * If yes, finalize it, else ask to read the next record. - */ - if( ssl_bitmask_check( bitmask, msg_len ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) ); - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) ); - - if( frag_len + 12 < ssl->in_msglen ) - { - /* - * We'got more handshake messages in the same record. - * This case is not handled now because no know implementation does - * that and it's hard to test, so we prefer to fail cleanly for now. - */ - MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) ); - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); - } - - if( ssl->in_left > ssl->next_record_offset ) - { - /* - * We've got more data in the buffer after the current record, - * that we don't want to overwrite. Move it before writing the - * reassembled message, and adjust in_left and next_record_offset. - */ - unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset; - unsigned char *new_remain = ssl->in_msg + ssl->in_hslen; - size_t remain_len = ssl->in_left - ssl->next_record_offset; - - /* First compute and check new lengths */ - ssl->next_record_offset = new_remain - ssl->in_hdr; - ssl->in_left = ssl->next_record_offset + remain_len; - - if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN - - (size_t)( ssl->in_hdr - ssl->in_buf ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) ); - return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); - } - - memmove( new_remain, cur_remain, remain_len ); - } - - memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen ); - - mbedtls_free( ssl->handshake->hs_msg ); - ssl->handshake->hs_msg = NULL; - - MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message", - ssl->in_msg, ssl->in_hslen ); - - return( 0 ); -} -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - -int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) -{ - if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d", - ssl->in_msglen ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ( - ( ssl->in_msg[1] << 16 ) | - ( ssl->in_msg[2] << 8 ) | - ssl->in_msg[3] ); - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" - " %d, type = %d, hslen = %d", - ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - int ret; - unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; - - /* ssl->handshake is NULL when receiving ClientHello for renego */ - if( ssl->handshake != NULL && - recv_msg_seq != ssl->handshake->in_msg_seq ) - { - /* Retransmit only on last message from previous flight, to avoid - * too many retransmissions. - * Besides, No sane server ever retransmits HelloVerifyRequest */ - if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 && - ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, " - "message_seq = %d, start_of_flight = %d", - recv_msg_seq, - ssl->handshake->in_flight_start_seq ) ); - - if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); - return( ret ); - } - } - else - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: " - "message_seq = %d, expected = %d", - recv_msg_seq, - ssl->handshake->in_msg_seq ) ); - } - - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - /* Wait until message completion to increment in_msg_seq */ - - /* Reassemble if current message is fragmented or reassembly is - * already in progress */ - if( ssl->in_msglen < ssl->in_hslen || - memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 || - memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 || - ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) ); - - if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_reassemble_dtls_handshake", ret ); - return( ret ); - } - } - } - else -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - /* With TLS we don't handle fragmentation (for now) */ - if( ssl->in_msglen < ssl->in_hslen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) ); - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); - } - - return( 0 ); -} - -void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ) -{ - - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && - ssl->handshake != NULL ) - { - ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); - } - - /* Handshake message is complete, increment counter */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake != NULL ) - { - ssl->handshake->in_msg_seq++; - } -#endif -} - -/* - * DTLS anti-replay: RFC 6347 4.1.2.6 - * - * in_window is a field of bits numbered from 0 (lsb) to 63 (msb). - * Bit n is set iff record number in_window_top - n has been seen. - * - * Usually, in_window_top is the last record number seen and the lsb of - * in_window is set. The only exception is the initial state (record number 0 - * not seen yet). - */ -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) -static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ) -{ - ssl->in_window_top = 0; - ssl->in_window = 0; -} - -static inline uint64_t ssl_load_six_bytes( unsigned char *buf ) -{ - return( ( (uint64_t) buf[0] << 40 ) | - ( (uint64_t) buf[1] << 32 ) | - ( (uint64_t) buf[2] << 24 ) | - ( (uint64_t) buf[3] << 16 ) | - ( (uint64_t) buf[4] << 8 ) | - ( (uint64_t) buf[5] ) ); -} - -/* - * Return 0 if sequence number is acceptable, -1 otherwise - */ -int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl ) -{ - uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); - uint64_t bit; - - if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) - return( 0 ); - - if( rec_seqnum > ssl->in_window_top ) - return( 0 ); - - bit = ssl->in_window_top - rec_seqnum; - - if( bit >= 64 ) - return( -1 ); - - if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 ) - return( -1 ); - - return( 0 ); -} - -/* - * Update replay window on new validated record - */ -void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ) -{ - uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); - - if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) - return; - - if( rec_seqnum > ssl->in_window_top ) - { - /* Update window_top and the contents of the window */ - uint64_t shift = rec_seqnum - ssl->in_window_top; - - if( shift >= 64 ) - ssl->in_window = 1; - else - { - ssl->in_window <<= shift; - ssl->in_window |= 1; - } - - ssl->in_window_top = rec_seqnum; - } - else - { - /* Mark that number as seen in the current window */ - uint64_t bit = ssl->in_window_top - rec_seqnum; - - if( bit < 64 ) /* Always true, but be extra sure */ - ssl->in_window |= (uint64_t) 1 << bit; - } -} -#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ - -#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) -/* Forward declaration */ -static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ); - -/* - * Without any SSL context, check if a datagram looks like a ClientHello with - * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message. - * Both input and output include full DTLS headers. - * - * - if cookie is valid, return 0 - * - if ClientHello looks superficially valid but cookie is not, - * fill obuf and set olen, then - * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED - * - otherwise return a specific error code - */ -static int ssl_check_dtls_clihlo_cookie( - mbedtls_ssl_cookie_write_t *f_cookie_write, - mbedtls_ssl_cookie_check_t *f_cookie_check, - void *p_cookie, - const unsigned char *cli_id, size_t cli_id_len, - const unsigned char *in, size_t in_len, - unsigned char *obuf, size_t buf_len, size_t *olen ) -{ - size_t sid_len, cookie_len; - unsigned char *p; - - if( f_cookie_write == NULL || f_cookie_check == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - /* - * Structure of ClientHello with record and handshake headers, - * and expected values. We don't need to check a lot, more checks will be - * done when actually parsing the ClientHello - skipping those checks - * avoids code duplication and does not make cookie forging any easier. - * - * 0-0 ContentType type; copied, must be handshake - * 1-2 ProtocolVersion version; copied - * 3-4 uint16 epoch; copied, must be 0 - * 5-10 uint48 sequence_number; copied - * 11-12 uint16 length; (ignored) - * - * 13-13 HandshakeType msg_type; (ignored) - * 14-16 uint24 length; (ignored) - * 17-18 uint16 message_seq; copied - * 19-21 uint24 fragment_offset; copied, must be 0 - * 22-24 uint24 fragment_length; (ignored) - * - * 25-26 ProtocolVersion client_version; (ignored) - * 27-58 Random random; (ignored) - * 59-xx SessionID session_id; 1 byte len + sid_len content - * 60+ opaque cookie<0..2^8-1>; 1 byte len + content - * ... - * - * Minimum length is 61 bytes. - */ - if( in_len < 61 || - in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || - in[3] != 0 || in[4] != 0 || - in[19] != 0 || in[20] != 0 || in[21] != 0 ) - { - return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); - } - - sid_len = in[59]; - if( sid_len > in_len - 61 ) - return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); - - cookie_len = in[60 + sid_len]; - if( cookie_len > in_len - 60 ) - return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); - - if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len, - cli_id, cli_id_len ) == 0 ) - { - /* Valid cookie */ - return( 0 ); - } - - /* - * If we get here, we've got an invalid cookie, let's prepare HVR. - * - * 0-0 ContentType type; copied - * 1-2 ProtocolVersion version; copied - * 3-4 uint16 epoch; copied - * 5-10 uint48 sequence_number; copied - * 11-12 uint16 length; olen - 13 - * - * 13-13 HandshakeType msg_type; hello_verify_request - * 14-16 uint24 length; olen - 25 - * 17-18 uint16 message_seq; copied - * 19-21 uint24 fragment_offset; copied - * 22-24 uint24 fragment_length; olen - 25 - * - * 25-26 ProtocolVersion server_version; 0xfe 0xff - * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie - * - * Minimum length is 28. - */ - if( buf_len < 28 ) - return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); - - /* Copy most fields and adapt others */ - memcpy( obuf, in, 25 ); - obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; - obuf[25] = 0xfe; - obuf[26] = 0xff; - - /* Generate and write actual cookie */ - p = obuf + 28; - if( f_cookie_write( p_cookie, - &p, obuf + buf_len, cli_id, cli_id_len ) != 0 ) - { - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - *olen = p - obuf; - - /* Go back and fill length fields */ - obuf[27] = (unsigned char)( *olen - 28 ); - - obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 ); - obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 ); - obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) ); - - obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 ); - obuf[12] = (unsigned char)( ( *olen - 13 ) ); - - return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); -} - -/* - * Handle possible client reconnect with the same UDP quadruplet - * (RFC 6347 Section 4.2.8). - * - * Called by ssl_parse_record_header() in case we receive an epoch 0 record - * that looks like a ClientHello. - * - * - if the input looks like a ClientHello without cookies, - * send back HelloVerifyRequest, then - * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED - * - if the input looks like a ClientHello with a valid cookie, - * reset the session of the current context, and - * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT - * - if anything goes wrong, return a specific error code - * - * mbedtls_ssl_read_record() will ignore the record if anything else than - * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function - * cannot not return 0. - */ -static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl ) -{ - int ret; - size_t len; - - ret = ssl_check_dtls_clihlo_cookie( - ssl->conf->f_cookie_write, - ssl->conf->f_cookie_check, - ssl->conf->p_cookie, - ssl->cli_id, ssl->cli_id_len, - ssl->in_buf, ssl->in_left, - ssl->out_buf, MBEDTLS_SSL_MAX_CONTENT_LEN, &len ); - - MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret ); - - if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ) - { - /* Dont check write errors as we can't do anything here. - * If the error is permanent we'll catch it later, - * if it's not, then hopefully it'll work next time. */ - (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len ); - - return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); - } - - if( ret == 0 ) - { - /* Got a valid cookie, partially reset context */ - if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret ); - return( ret ); - } - - return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT ); - } - - return( ret ); -} -#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ - -/* - * ContentType type; - * ProtocolVersion version; - * uint16 epoch; // DTLS only - * uint48 sequence_number; // DTLS only - * uint16 length; - * - * Return 0 if header looks sane (and, for DTLS, the record is expected) - * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad, - * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected. - * - * With DTLS, mbedtls_ssl_read_record() will: - * 1. proceed with the record if this function returns 0 - * 2. drop only the current record if this function returns UNEXPECTED_RECORD - * 3. return CLIENT_RECONNECT if this function return that value - * 4. drop the whole datagram if this function returns anything else. - * Point 2 is needed when the peer is resending, and we have already received - * the first record from a datagram but are still waiting for the others. - */ -static int ssl_parse_record_header( mbedtls_ssl_context *ssl ) -{ - int ret; - int major_ver, minor_ver; - - MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) ); - - ssl->in_msgtype = ssl->in_hdr[0]; - ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; - mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 ); - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, " - "version = [%d:%d], msglen = %d", - ssl->in_msgtype, - major_ver, minor_ver, ssl->in_msglen ) ); - - /* Check record type */ - if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT && - ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && - ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); - - if( ( ret = mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 ) - { - return( ret ); - } - - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - /* Check version */ - if( major_ver != ssl->major_ver ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - if( minor_ver > ssl->conf->max_minor_ver ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - /* Check length against the size of our buffer */ - if( ssl->in_msglen > MBEDTLS_SSL_BUFFER_LEN - - (size_t)( ssl->in_msg - ssl->in_buf ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - - /* Check length against bounds of the current transform and version */ - if( ssl->transform_in == NULL ) - { - if( ssl->in_msglen < 1 || - ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - } - else - { - if( ssl->in_msglen < ssl->transform_in->minlen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && - ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - /* - * TLS encrypted messages can have up to 256 bytes of padding - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 && - ssl->in_msglen > ssl->transform_in->minlen + - MBEDTLS_SSL_MAX_CONTENT_LEN + 256 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } -#endif - } - - /* - * DTLS-related tests done last, because most of them may result in - * silently dropping the record (but not the whole datagram), and we only - * want to consider that after ensuring that the "basic" fields (type, - * version, length) are sane. - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; - - /* Drop unexpected ChangeCipherSpec messages */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && - ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && - ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } - - /* Drop unexpected ApplicationData records, - * except at the beginning of renegotiations */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && - ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER -#if defined(MBEDTLS_SSL_RENEGOTIATION) - && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && - ssl->state == MBEDTLS_SSL_SERVER_HELLO ) -#endif - ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } - - /* Check epoch (and sequence number) with DTLS */ - if( rec_epoch != ssl->in_epoch ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: " - "expected %d, received %d", - ssl->in_epoch, rec_epoch ) ); - -#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) - /* - * Check for an epoch 0 ClientHello. We can't use in_msg here to - * access the first byte of record content (handshake type), as we - * have an active transform (possibly iv_len != 0), so use the - * fact that the record header len is 13 instead. - */ - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && - rec_epoch == 0 && - ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_left > 13 && - ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect " - "from the same port" ) ); - return( ssl_handle_possible_reconnect( ssl ) ); - } - else -#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } - -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) - /* Replay detection only works for the current epoch */ - if( rec_epoch == ssl->in_epoch && - mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); - } -#endif - } -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - - return( 0 ); -} - -/* - * If applicable, decrypt (and decompress) record content - */ -static int ssl_prepare_record_content( mbedtls_ssl_context *ssl ) -{ - int ret, done = 0; - - MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network", - ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ); - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_read != NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) ); - - ret = mbedtls_ssl_hw_record_read( ssl ); - if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - - if( ret == 0 ) - done = 1; - } -#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ - if( !done && ssl->transform_in != NULL ) - { - if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt", - ssl->in_msg, ssl->in_msglen ); - - if( ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); - return( MBEDTLS_ERR_SSL_INVALID_RECORD ); - } - } - -#if defined(MBEDTLS_ZLIB_SUPPORT) - if( ssl->transform_in != NULL && - ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) - { - if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); - return( ret ); - } - } -#endif /* MBEDTLS_ZLIB_SUPPORT */ - -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - mbedtls_ssl_dtls_replay_update( ssl ); - } -#endif - - return( 0 ); -} - -static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ); - -/* - * Read a record. - * - * Silently ignore non-fatal alert (and for DTLS, invalid records as well, - * RFC 6347 4.1.2.7) and continue reading until a valid record is found. - * - */ -int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) ); - - do { - - if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret ); - return( ret ); - } - - ret = mbedtls_ssl_handle_message_type( ssl ); - - } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ); - - if( 0 != ret ) - { - MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); - return( ret ); - } - - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) - { - mbedtls_ssl_update_handshake_status( ssl ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) ); - - return( 0 ); -} - -int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ) -{ - int ret; - - if( ssl->in_hslen != 0 && ssl->in_hslen < ssl->in_msglen ) - { - /* - * Get next Handshake message in the current record - */ - ssl->in_msglen -= ssl->in_hslen; - - memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, - ssl->in_msglen ); - - MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record", - ssl->in_msg, ssl->in_msglen ); - - return( 0 ); - } - - ssl->in_hslen = 0; - - /* - * Read the record header and parse it - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) -read_record_header: -#endif - - if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); - return( ret ); - } - - if( ( ret = ssl_parse_record_header( ssl ) ) != 0 ) - { -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT ) - { - if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ) - { - /* Skip unexpected record (but not whole datagram) */ - ssl->next_record_offset = ssl->in_msglen - + mbedtls_ssl_hdr_len( ssl ); - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record " - "(header)" ) ); - } - else - { - /* Skip invalid record and the rest of the datagram */ - ssl->next_record_offset = 0; - ssl->in_left = 0; - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record " - "(header)" ) ); - } - - /* Get next record */ - goto read_record_header; - } -#endif - return( ret ); - } - - /* - * Read and optionally decrypt the message contents - */ - if( ( ret = mbedtls_ssl_fetch_input( ssl, - mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); - return( ret ); - } - - /* Done reading this record, get ready for the next one */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl ); - else -#endif - ssl->in_left = 0; - - if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 ) - { -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - /* Silently discard invalid records */ - if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD || - ret == MBEDTLS_ERR_SSL_INVALID_MAC ) - { - /* Except when waiting for Finished as a bad mac here - * probably means something went wrong in the handshake - * (eg wrong psk used, mitm downgrade attempt, etc.) */ - if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED || - ssl->state == MBEDTLS_SSL_SERVER_FINISHED ) - { -#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) - if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) - { - mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); - } -#endif - return( ret ); - } - -#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) - if( ssl->conf->badmac_limit != 0 && - ++ssl->badmac_seen >= ssl->conf->badmac_limit ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) ); - return( MBEDTLS_ERR_SSL_INVALID_MAC ); - } -#endif - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); - goto read_record_header; - } - - return( ret ); - } - else -#endif - { - /* Error out (and send alert) on invalid records */ -#if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) - if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) - { - mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); - } -#endif - return( ret ); - } - } - - /* - * When we sent the last flight of the handshake, we MUST respond to a - * retransmit of the peer's previous flight with a retransmit. (In - * practice, only the Finished message will make it, other messages - * including CCS use the old transform so they're dropped as invalid.) - * - * If the record we received is not a handshake message, however, it - * means the peer received our last flight so we can clean up - * handshake info. - * - * This check needs to be done before prepare_handshake() due to an edge - * case: if the client immediately requests renegotiation, this - * finishes the current handshake first, avoiding the new ClientHello - * being mistaken for an ancient message in the current handshake. - */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake != NULL && - ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) - { - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) ); - - if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); - return( ret ); - } - - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - else - { - ssl_handshake_wrapup_free_hs_transform( ssl ); - } - } -#endif - - return( 0 ); -} - -int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) -{ - int ret; - - /* - * Handle particular types of records - */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) - { - if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 ) - { - return( ret ); - } - } - - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]", - ssl->in_msg[0], ssl->in_msg[1] ) ); - - /* - * Ignore non-fatal alerts, except close_notify and no_renegotiation - */ - if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)", - ssl->in_msg[1] ) ); - return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE ); - } - - if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && - ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); - return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ); - } - -#if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED) - if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && - ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); - /* Will be handled when trying to parse ServerHello */ - return( 0 ); - } -#endif - -#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && - ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && - ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); - /* Will be handled in mbedtls_ssl_parse_certificate() */ - return( 0 ); - } -#endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ - - /* Silently ignore: fetch new message */ - return MBEDTLS_ERR_SSL_NON_FATAL; - } - - return( 0 ); -} - -int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ) -{ - int ret; - - if( ( ret = mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_FATAL, - MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 ) - { - return( ret ); - } - - return( 0 ); -} - -int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, - unsigned char level, - unsigned char message ) -{ - int ret; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); - - ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; - ssl->out_msglen = 2; - ssl->out_msg[0] = level; - ssl->out_msg[1] = message; - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); - - return( 0 ); -} - -/* - * Handshake functions - */ -#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ - !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) -int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) -{ - const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); - - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); - ssl->state++; - return( 0 ); - } - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); -} - -int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) -{ - const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); - - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); -} -#else -int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) -{ - int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; - size_t i, n; - const mbedtls_x509_crt *crt; - const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); - - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - { - if( ssl->client_auth == 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - /* - * If using SSLv3 and got no cert, send an Alert message - * (otherwise an empty Certificate message will be sent). - */ - if( mbedtls_ssl_own_cert( ssl ) == NULL && - ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - ssl->out_msglen = 2; - ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; - ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING; - ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) ); - goto write_msg; - } -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - } -#endif /* MBEDTLS_SSL_CLI_C */ -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - { - if( mbedtls_ssl_own_cert( ssl ) == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) ); - return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED ); - } - } -#endif - - MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) ); - - /* - * 0 . 0 handshake type - * 1 . 3 handshake length - * 4 . 6 length of all certs - * 7 . 9 length of cert. 1 - * 10 . n-1 peer certificate - * n . n+2 length of cert. 2 - * n+3 . ... upper level cert, etc. - */ - i = 7; - crt = mbedtls_ssl_own_cert( ssl ); - - while( crt != NULL ) - { - n = crt->raw.len; - if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d", - i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) ); - return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE ); - } - - ssl->out_msg[i ] = (unsigned char)( n >> 16 ); - ssl->out_msg[i + 1] = (unsigned char)( n >> 8 ); - ssl->out_msg[i + 2] = (unsigned char)( n ); - - i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n ); - i += n; crt = crt->next; - } - - ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 ); - ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 ); - ssl->out_msg[6] = (unsigned char)( ( i - 7 ) ); - - ssl->out_msglen = i; - ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; - ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE; - -#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) -write_msg: -#endif - - ssl->state++; - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) ); - - return( ret ); -} - -int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) -{ - int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; - size_t i, n; - const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; - int authmode = ssl->conf->authmode; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); - - if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) - authmode = ssl->handshake->sni_authmode; -#endif - - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - authmode == MBEDTLS_SSL_VERIFY_NONE ) - { - ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); - ssl->state++; - return( 0 ); - } -#endif - - if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - - ssl->state++; - -#if defined(MBEDTLS_SSL_SRV_C) -#if defined(MBEDTLS_SSL_PROTO_SSL3) - /* - * Check if the client sent an empty certificate - */ - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - if( ssl->in_msglen == 2 && - ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT && - ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && - ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); - - ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - return( 0 ); - else - return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); - } - } -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) - { - if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) && - ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && - ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE && - memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); - - ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - return( 0 ); - else - return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); - } - } -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ - MBEDTLS_SSL_PROTO_TLS1_2 */ -#endif /* MBEDTLS_SSL_SRV_C */ - - if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - - if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE || - ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - - i = mbedtls_ssl_hs_hdr_len( ssl ); - - /* - * Same message structure as in mbedtls_ssl_write_certificate() - */ - n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2]; - - if( ssl->in_msg[i] != 0 || - ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - - /* In case we tried to reuse a session but it failed */ - if( ssl->session_negotiate->peer_cert != NULL ) - { - mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert ); - mbedtls_free( ssl->session_negotiate->peer_cert ); - } - - if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1, - sizeof( mbedtls_x509_crt ) ) ) == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", - sizeof( mbedtls_x509_crt ) ) ); - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert ); - - i += 3; - - while( i < ssl->in_hslen ) - { - if( ssl->in_msg[i] != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - - n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) - | (unsigned int) ssl->in_msg[i + 2]; - i += 3; - - if( n < 128 || i + n > ssl->in_hslen ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - - ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert, - ssl->in_msg + i, n ); - if( 0 != ret && ( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND ) != ret ) - { - MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret ); - return( ret ); - } - - i += n; - } - - MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert ); - - /* - * On client, make sure the server cert doesn't change during renego to - * avoid "triple handshake" attack: https://secure-resumption.com/ - */ -#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && - ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) - { - if( ssl->session->peer_cert == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - - if( ssl->session->peer_cert->raw.len != - ssl->session_negotiate->peer_cert->raw.len || - memcmp( ssl->session->peer_cert->raw.p, - ssl->session_negotiate->peer_cert->raw.p, - ssl->session->peer_cert->raw.len ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); - } - } -#endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ - - if( authmode != MBEDTLS_SSL_VERIFY_NONE ) - { - mbedtls_x509_crt *ca_chain; - mbedtls_x509_crl *ca_crl; - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - if( ssl->handshake->sni_ca_chain != NULL ) - { - ca_chain = ssl->handshake->sni_ca_chain; - ca_crl = ssl->handshake->sni_ca_crl; - } - else -#endif - { - ca_chain = ssl->conf->ca_chain; - ca_crl = ssl->conf->ca_crl; - } - - if( ca_chain == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); - return( MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED ); - } - - /* - * Main check: verify certificate - */ - ret = mbedtls_x509_crt_verify_with_profile( - ssl->session_negotiate->peer_cert, - ca_chain, ca_crl, - ssl->conf->cert_profile, - ssl->hostname, - &ssl->session_negotiate->verify_result, - ssl->conf->f_vrfy, ssl->conf->p_vrfy ); - - if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); - } - - /* - * Secondary checks: always done, but change 'ret' only if it was 0 - */ - -#if defined(MBEDTLS_ECP_C) - { - const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk; - - /* If certificate uses an EC key, make sure the curve is OK */ - if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) && - mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) ); - if( ret == 0 ) - ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; - } - } -#endif /* MBEDTLS_ECP_C */ - - if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert, - ciphersuite_info, - ! ssl->conf->endpoint, - &ssl->session_negotiate->verify_result ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) ); - if( ret == 0 ) - ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; - } - - if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) - ret = 0; - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); - - return( ret ); -} -#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED - !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED - !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED - !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED - !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED - !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED - !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ - -int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); - - ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; - ssl->out_msglen = 1; - ssl->out_msg[0] = 1; - - ssl->state++; - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); - - return( 0 ); -} - -int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); - - if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - - if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - - if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); - } - - /* - * Switch to our negotiated transform and session parameters for inbound - * data. - */ - MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); - ssl->transform_in = ssl->transform_negotiate; - ssl->session_in = ssl->session_negotiate; - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) - ssl_dtls_replay_reset( ssl ); -#endif - - /* Increment epoch */ - if( ++ssl->in_epoch == 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); - return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); - } - } - else -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - memset( ssl->in_ctr, 0, 8 ); - - /* - * Set the in_msg pointer to the correct location based on IV length - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen - - ssl->transform_negotiate->fixed_ivlen; - } - else - ssl->in_msg = ssl->in_iv; - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_activate != NULL ) - { - if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - } -#endif - - ssl->state++; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); - - return( 0 ); -} - -void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, - const mbedtls_ssl_ciphersuite_t *ciphersuite_info ) -{ - ((void) ciphersuite_info); - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) - if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) - ssl->handshake->update_checksum = ssl_update_checksum_md5sha1; - else -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA512_C) - if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) - ssl->handshake->update_checksum = ssl_update_checksum_sha384; - else -#endif -#if defined(MBEDTLS_SHA256_C) - if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 ) - ssl->handshake->update_checksum = ssl_update_checksum_sha256; - else -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return; - } -} - -void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ) -{ -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) - mbedtls_md5_starts( &ssl->handshake->fin_md5 ); - mbedtls_sha1_starts( &ssl->handshake->fin_sha1 ); -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) - mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 ); -#endif -#if defined(MBEDTLS_SHA512_C) - mbedtls_sha512_starts( &ssl->handshake->fin_sha512, 1 ); -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ -} - -static void ssl_update_checksum_start( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) - mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len ); - mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len ); -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) - mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len ); -#endif -#if defined(MBEDTLS_SHA512_C) - mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len ); -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ -} - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) -static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ - mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len ); - mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len ); -} -#endif - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) -static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ - mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len ); -} -#endif - -#if defined(MBEDTLS_SHA512_C) -static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ - mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len ); -} -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -#if defined(MBEDTLS_SSL_PROTO_SSL3) -static void ssl_calc_finished_ssl( - mbedtls_ssl_context *ssl, unsigned char *buf, int from ) -{ - const char *sender; - mbedtls_md5_context md5; - mbedtls_sha1_context sha1; - - unsigned char padbuf[48]; - unsigned char md5sum[16]; - unsigned char sha1sum[20]; - - mbedtls_ssl_session *session = ssl->session_negotiate; - if( !session ) - session = ssl->session; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); - - mbedtls_md5_init( &md5 ); - mbedtls_sha1_init( &sha1 ); - - mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); - mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); - - /* - * SSLv3: - * hash = - * MD5( master + pad2 + - * MD5( handshake + sender + master + pad1 ) ) - * + SHA1( master + pad2 + - * SHA1( handshake + sender + master + pad1 ) ) - */ - -#if !defined(MBEDTLS_MD5_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) - md5.state, sizeof( md5.state ) ); -#endif - -#if !defined(MBEDTLS_SHA1_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) - sha1.state, sizeof( sha1.state ) ); -#endif - - sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT" - : "SRVR"; - - memset( padbuf, 0x36, 48 ); - - mbedtls_md5_update( &md5, (const unsigned char *) sender, 4 ); - mbedtls_md5_update( &md5, session->master, 48 ); - mbedtls_md5_update( &md5, padbuf, 48 ); - mbedtls_md5_finish( &md5, md5sum ); - - mbedtls_sha1_update( &sha1, (const unsigned char *) sender, 4 ); - mbedtls_sha1_update( &sha1, session->master, 48 ); - mbedtls_sha1_update( &sha1, padbuf, 40 ); - mbedtls_sha1_finish( &sha1, sha1sum ); - - memset( padbuf, 0x5C, 48 ); - - mbedtls_md5_starts( &md5 ); - mbedtls_md5_update( &md5, session->master, 48 ); - mbedtls_md5_update( &md5, padbuf, 48 ); - mbedtls_md5_update( &md5, md5sum, 16 ); - mbedtls_md5_finish( &md5, buf ); - - mbedtls_sha1_starts( &sha1 ); - mbedtls_sha1_update( &sha1, session->master, 48 ); - mbedtls_sha1_update( &sha1, padbuf , 40 ); - mbedtls_sha1_update( &sha1, sha1sum, 20 ); - mbedtls_sha1_finish( &sha1, buf + 16 ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); - - mbedtls_md5_free( &md5 ); - mbedtls_sha1_free( &sha1 ); - - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); - mbedtls_zeroize( md5sum, sizeof( md5sum ) ); - mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); -} -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) -static void ssl_calc_finished_tls( - mbedtls_ssl_context *ssl, unsigned char *buf, int from ) -{ - int len = 12; - const char *sender; - mbedtls_md5_context md5; - mbedtls_sha1_context sha1; - unsigned char padbuf[36]; - - mbedtls_ssl_session *session = ssl->session_negotiate; - if( !session ) - session = ssl->session; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) ); - - mbedtls_md5_init( &md5 ); - mbedtls_sha1_init( &sha1 ); - - mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); - mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); - - /* - * TLSv1: - * hash = PRF( master, finished_label, - * MD5( handshake ) + SHA1( handshake ) )[0..11] - */ - -#if !defined(MBEDTLS_MD5_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) - md5.state, sizeof( md5.state ) ); -#endif - -#if !defined(MBEDTLS_SHA1_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) - sha1.state, sizeof( sha1.state ) ); -#endif - - sender = ( from == MBEDTLS_SSL_IS_CLIENT ) - ? "client finished" - : "server finished"; - - mbedtls_md5_finish( &md5, padbuf ); - mbedtls_sha1_finish( &sha1, padbuf + 16 ); - - ssl->handshake->tls_prf( session->master, 48, sender, - padbuf, 36, buf, len ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); - - mbedtls_md5_free( &md5 ); - mbedtls_sha1_free( &sha1 ); - - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); -} -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ - -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) -static void ssl_calc_finished_tls_sha256( - mbedtls_ssl_context *ssl, unsigned char *buf, int from ) -{ - int len = 12; - const char *sender; - mbedtls_sha256_context sha256; - unsigned char padbuf[32]; - - mbedtls_ssl_session *session = ssl->session_negotiate; - if( !session ) - session = ssl->session; - - mbedtls_sha256_init( &sha256 ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) ); - - mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); - - /* - * TLSv1.2: - * hash = PRF( master, finished_label, - * Hash( handshake ) )[0.11] - */ - -#if !defined(MBEDTLS_SHA256_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *) - sha256.state, sizeof( sha256.state ) ); -#endif - - sender = ( from == MBEDTLS_SSL_IS_CLIENT ) - ? "client finished" - : "server finished"; - - mbedtls_sha256_finish( &sha256, padbuf ); - - ssl->handshake->tls_prf( session->master, 48, sender, - padbuf, 32, buf, len ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); - - mbedtls_sha256_free( &sha256 ); - - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); -} -#endif /* MBEDTLS_SHA256_C */ - -#if defined(MBEDTLS_SHA512_C) -static void ssl_calc_finished_tls_sha384( - mbedtls_ssl_context *ssl, unsigned char *buf, int from ) -{ - int len = 12; - const char *sender; - mbedtls_sha512_context sha512; - unsigned char padbuf[48]; - - mbedtls_ssl_session *session = ssl->session_negotiate; - if( !session ) - session = ssl->session; - - mbedtls_sha512_init( &sha512 ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) ); - - mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); - - /* - * TLSv1.2: - * hash = PRF( master, finished_label, - * Hash( handshake ) )[0.11] - */ - -#if !defined(MBEDTLS_SHA512_ALT) - MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *) - sha512.state, sizeof( sha512.state ) ); -#endif - - sender = ( from == MBEDTLS_SSL_IS_CLIENT ) - ? "client finished" - : "server finished"; - - mbedtls_sha512_finish( &sha512, padbuf ); - - ssl->handshake->tls_prf( session->master, 48, sender, - padbuf, 48, buf, len ); - - MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); - - mbedtls_sha512_free( &sha512 ); - - mbedtls_zeroize( padbuf, sizeof( padbuf ) ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); -} -#endif /* MBEDTLS_SHA512_C */ -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ) -{ - MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) ); - - /* - * Free our handshake params - */ - mbedtls_ssl_handshake_free( ssl->handshake ); - mbedtls_free( ssl->handshake ); - ssl->handshake = NULL; - - /* - * Free the previous transform and swith in the current one - */ - if( ssl->transform ) - { - mbedtls_ssl_transform_free( ssl->transform ); - mbedtls_free( ssl->transform ); - } - ssl->transform = ssl->transform_negotiate; - ssl->transform_negotiate = NULL; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) ); -} - -void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl ) -{ - int resume = ssl->handshake->resume; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) ); - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) - { - ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE; - ssl->renego_records_seen = 0; - } -#endif - - /* - * Free the previous session and switch in the current one - */ - if( ssl->session ) - { -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - /* RFC 7366 3.1: keep the EtM state */ - ssl->session_negotiate->encrypt_then_mac = - ssl->session->encrypt_then_mac; -#endif - - mbedtls_ssl_session_free( ssl->session ); - mbedtls_free( ssl->session ); - } - ssl->session = ssl->session_negotiate; - ssl->session_negotiate = NULL; - - /* - * Add cache entry - */ - if( ssl->conf->f_set_cache != NULL && - ssl->session->id_len != 0 && - resume == 0 ) - { - if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 ) - MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) ); - } - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->handshake->flight != NULL ) - { - /* Cancel handshake timer */ - ssl_set_timer( ssl, 0 ); - - /* Keep last flight around in case we need to resend it: - * we need the handshake and transform structures for that */ - MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) ); - } - else -#endif - ssl_handshake_wrapup_free_hs_transform( ssl ); - - ssl->state++; - - MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) ); -} - -int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl ) -{ - int ret, hash_len; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) ); - - /* - * Set the out_msg pointer to the correct location based on IV length - */ - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) - { - ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen - - ssl->transform_negotiate->fixed_ivlen; - } - else - ssl->out_msg = ssl->out_iv; - - ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint ); - - /* - * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites - * may define some other value. Currently (early 2016), no defined - * ciphersuite does this (and this is unlikely to change as activity has - * moved to TLS 1.3 now) so we can keep the hardcoded 12 here. - */ - hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12; - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - ssl->verify_data_len = hash_len; - memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len ); -#endif - - ssl->out_msglen = 4 + hash_len; - ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; - ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED; - - /* - * In case of session resuming, invert the client and server - * ChangeCipherSpec messages order. - */ - if( ssl->handshake->resume != 0 ) - { -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; -#endif -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; -#endif - } - else - ssl->state++; - - /* - * Switch to our negotiated transform and session parameters for outbound - * data. - */ - MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - unsigned char i; - - /* Remember current epoch settings for resending */ - ssl->handshake->alt_transform_out = ssl->transform_out; - memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 ); - - /* Set sequence_number to zero */ - memset( ssl->out_ctr + 2, 0, 6 ); - - /* Increment epoch */ - for( i = 2; i > 0; i-- ) - if( ++ssl->out_ctr[i - 1] != 0 ) - break; - - /* The loop goes to its end iff the counter is wrapping */ - if( i == 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); - return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); - } - } - else -#endif /* MBEDTLS_SSL_PROTO_DTLS */ - memset( ssl->out_ctr, 0, 8 ); - - ssl->transform_out = ssl->transform_negotiate; - ssl->session_out = ssl->session_negotiate; - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_activate != NULL ) - { - if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - } -#endif - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - mbedtls_ssl_send_flight_completed( ssl ); -#endif - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) ); - - return( 0 ); -} - -#if defined(MBEDTLS_SSL_PROTO_SSL3) -#define SSL_MAX_HASH_LEN 36 -#else -#define SSL_MAX_HASH_LEN 12 -#endif - -int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl ) -{ - int ret; - unsigned int hash_len; - unsigned char buf[SSL_MAX_HASH_LEN]; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) ); - - ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 ); - - if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - - if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - - /* There is currently no ciphersuite using another length with TLS 1.2 */ -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - hash_len = 36; - else -#endif - hash_len = 12; - - if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED || - ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); - } - - if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), - buf, hash_len ) != 0 ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); - return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); - } - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - ssl->verify_data_len = hash_len; - memcpy( ssl->peer_verify_data, buf, hash_len ); -#endif - - if( ssl->handshake->resume != 0 ) - { -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; -#endif -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; -#endif - } - else - ssl->state++; - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - mbedtls_ssl_recv_flight_completed( ssl ); -#endif - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) ); - - return( 0 ); -} - -static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake ) -{ - memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) ); - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) - mbedtls_md5_init( &handshake->fin_md5 ); - mbedtls_sha1_init( &handshake->fin_sha1 ); - mbedtls_md5_starts( &handshake->fin_md5 ); - mbedtls_sha1_starts( &handshake->fin_sha1 ); -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) - mbedtls_sha256_init( &handshake->fin_sha256 ); - mbedtls_sha256_starts( &handshake->fin_sha256, 0 ); -#endif -#if defined(MBEDTLS_SHA512_C) - mbedtls_sha512_init( &handshake->fin_sha512 ); - mbedtls_sha512_starts( &handshake->fin_sha512, 1 ); -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - - handshake->update_checksum = ssl_update_checksum_start; - handshake->sig_alg = MBEDTLS_SSL_HASH_SHA1; - -#if defined(MBEDTLS_DHM_C) - mbedtls_dhm_init( &handshake->dhm_ctx ); -#endif -#if defined(MBEDTLS_ECDH_C) - mbedtls_ecdh_init( &handshake->ecdh_ctx ); -#endif -#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) - mbedtls_ecjpake_init( &handshake->ecjpake_ctx ); -#if defined(MBEDTLS_SSL_CLI_C) - handshake->ecjpake_cache = NULL; - handshake->ecjpake_cache_len = 0; -#endif -#endif - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET; -#endif -} - -static void ssl_transform_init( mbedtls_ssl_transform *transform ) -{ - memset( transform, 0, sizeof(mbedtls_ssl_transform) ); - - mbedtls_cipher_init( &transform->cipher_ctx_enc ); - mbedtls_cipher_init( &transform->cipher_ctx_dec ); - - mbedtls_md_init( &transform->md_ctx_enc ); - mbedtls_md_init( &transform->md_ctx_dec ); -} - -void mbedtls_ssl_session_init( mbedtls_ssl_session *session ) -{ - memset( session, 0, sizeof(mbedtls_ssl_session) ); -} - -static int ssl_handshake_init( mbedtls_ssl_context *ssl ) -{ - /* Clear old handshake information if present */ - if( ssl->transform_negotiate ) - mbedtls_ssl_transform_free( ssl->transform_negotiate ); - if( ssl->session_negotiate ) - mbedtls_ssl_session_free( ssl->session_negotiate ); - if( ssl->handshake ) - mbedtls_ssl_handshake_free( ssl->handshake ); - - /* - * Either the pointers are now NULL or cleared properly and can be freed. - * Now allocate missing structures. - */ - if( ssl->transform_negotiate == NULL ) - { - ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) ); - } - - if( ssl->session_negotiate == NULL ) - { - ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) ); - } - - if( ssl->handshake == NULL ) - { - ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) ); - } - - /* All pointers should exist and can be directly freed without issue */ - if( ssl->handshake == NULL || - ssl->transform_negotiate == NULL || - ssl->session_negotiate == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) ); - - mbedtls_free( ssl->handshake ); - mbedtls_free( ssl->transform_negotiate ); - mbedtls_free( ssl->session_negotiate ); - - ssl->handshake = NULL; - ssl->transform_negotiate = NULL; - ssl->session_negotiate = NULL; - - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - /* Initialize structures */ - mbedtls_ssl_session_init( ssl->session_negotiate ); - ssl_transform_init( ssl->transform_negotiate ); - ssl_handshake_params_init( ssl->handshake ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - ssl->handshake->alt_transform_out = ssl->transform_out; - - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; - else - ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; - - ssl_set_timer( ssl, 0 ); - } -#endif - - return( 0 ); -} - -#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) -/* Dummy cookie callbacks for defaults */ -static int ssl_cookie_write_dummy( void *ctx, - unsigned char **p, unsigned char *end, - const unsigned char *cli_id, size_t cli_id_len ) -{ - ((void) ctx); - ((void) p); - ((void) end); - ((void) cli_id); - ((void) cli_id_len); - - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); -} - -static int ssl_cookie_check_dummy( void *ctx, - const unsigned char *cookie, size_t cookie_len, - const unsigned char *cli_id, size_t cli_id_len ) -{ - ((void) ctx); - ((void) cookie); - ((void) cookie_len); - ((void) cli_id); - ((void) cli_id_len); - - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); -} -#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ - -/* - * Initialize an SSL context - */ -void mbedtls_ssl_init( mbedtls_ssl_context *ssl ) -{ - memset( ssl, 0, sizeof( mbedtls_ssl_context ) ); - -#ifdef RTL_HW_CRYPTO - if(rom_ssl_ram_map.use_hw_crypto_func) - rtl_cryptoEngine_init(); -#endif /* RTL_HW_CRYPTO */ -} - -/* - * Setup an SSL context - */ -int mbedtls_ssl_setup( mbedtls_ssl_context *ssl, - const mbedtls_ssl_config *conf ) -{ - int ret; - const size_t len = MBEDTLS_SSL_BUFFER_LEN; - - ssl->conf = conf; - - /* - * Prepare base structures - */ - if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL || - ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) ); - mbedtls_free( ssl->in_buf ); - ssl->in_buf = NULL; - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - ssl->out_hdr = ssl->out_buf; - ssl->out_ctr = ssl->out_buf + 3; - ssl->out_len = ssl->out_buf + 11; - ssl->out_iv = ssl->out_buf + 13; - ssl->out_msg = ssl->out_buf + 13; - - ssl->in_hdr = ssl->in_buf; - ssl->in_ctr = ssl->in_buf + 3; - ssl->in_len = ssl->in_buf + 11; - ssl->in_iv = ssl->in_buf + 13; - ssl->in_msg = ssl->in_buf + 13; - } - else -#endif - { - ssl->out_ctr = ssl->out_buf; - ssl->out_hdr = ssl->out_buf + 8; - ssl->out_len = ssl->out_buf + 11; - ssl->out_iv = ssl->out_buf + 13; - ssl->out_msg = ssl->out_buf + 13; - - ssl->in_ctr = ssl->in_buf; - ssl->in_hdr = ssl->in_buf + 8; - ssl->in_len = ssl->in_buf + 11; - ssl->in_iv = ssl->in_buf + 13; - ssl->in_msg = ssl->in_buf + 13; - } - - if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) - return( ret ); - - return( 0 ); -} - -/* - * Reset an initialized and used SSL context for re-use while retaining - * all application-set variables, function pointers and data. - * - * If partial is non-zero, keep data in the input buffer and client ID. - * (Use when a DTLS client reconnects from the same port.) - */ -static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ) -{ - int ret; - - ssl->state = MBEDTLS_SSL_HELLO_REQUEST; - - /* Cancel any possibly running timer */ - ssl_set_timer( ssl, 0 ); - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE; - ssl->renego_records_seen = 0; - - ssl->verify_data_len = 0; - memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); - memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); -#endif - ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION; - - ssl->in_offt = NULL; - - ssl->in_msg = ssl->in_buf + 13; - ssl->in_msgtype = 0; - ssl->in_msglen = 0; - if( partial == 0 ) - ssl->in_left = 0; -#if defined(MBEDTLS_SSL_PROTO_DTLS) - ssl->next_record_offset = 0; - ssl->in_epoch = 0; -#endif -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) - ssl_dtls_replay_reset( ssl ); -#endif - - ssl->in_hslen = 0; - ssl->nb_zero = 0; - ssl->record_read = 0; - - ssl->out_msg = ssl->out_buf + 13; - ssl->out_msgtype = 0; - ssl->out_msglen = 0; - ssl->out_left = 0; -#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) - if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ) - ssl->split_done = 0; -#endif - - ssl->transform_in = NULL; - ssl->transform_out = NULL; - - memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN ); - if( partial == 0 ) - memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN ); - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_reset != NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) ); - if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret ); - return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); - } - } -#endif - - if( ssl->transform ) - { - mbedtls_ssl_transform_free( ssl->transform ); - mbedtls_free( ssl->transform ); - ssl->transform = NULL; - } - - if( ssl->session ) - { - mbedtls_ssl_session_free( ssl->session ); - mbedtls_free( ssl->session ); - ssl->session = NULL; - } - -#if defined(MBEDTLS_SSL_ALPN) - ssl->alpn_chosen = NULL; -#endif - -#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) - if( partial == 0 ) - { - mbedtls_free( ssl->cli_id ); - ssl->cli_id = NULL; - ssl->cli_id_len = 0; - } -#endif - - if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) - return( ret ); - - return( 0 ); -} - -/* - * Reset an initialized and used SSL context for re-use while retaining - * all application-set variables, function pointers and data. - */ -int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ) -{ - return( ssl_session_reset_int( ssl, 0 ) ); -} - -/* - * SSL set accessors - */ -void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint ) -{ - conf->endpoint = endpoint; -} - -void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport ) -{ - conf->transport = transport; -} - -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) -void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode ) -{ - conf->anti_replay = mode; -} -#endif - -#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) -void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit ) -{ - conf->badmac_limit = limit; -} -#endif - -#if defined(MBEDTLS_SSL_PROTO_DTLS) -void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max ) -{ - conf->hs_timeout_min = min; - conf->hs_timeout_max = max; -} -#endif - -void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode ) -{ - conf->authmode = authmode; -} - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf, - int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), - void *p_vrfy ) -{ - conf->f_vrfy = f_vrfy; - conf->p_vrfy = p_vrfy; -} -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf, - int (*f_rng)(void *, unsigned char *, size_t), - void *p_rng ) -{ - conf->f_rng = f_rng; - conf->p_rng = p_rng; -} - -void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf, - void (*f_dbg)(void *, int, const char *, int, const char *), - void *p_dbg ) -{ - conf->f_dbg = f_dbg; - conf->p_dbg = p_dbg; -} - -void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, - void *p_bio, - mbedtls_ssl_send_t *f_send, - mbedtls_ssl_recv_t *f_recv, - mbedtls_ssl_recv_timeout_t *f_recv_timeout ) -{ - ssl->p_bio = p_bio; - ssl->f_send = f_send; - ssl->f_recv = f_recv; - ssl->f_recv_timeout = f_recv_timeout; -} - -void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout ) -{ - conf->read_timeout = timeout; -} - -void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl, - void *p_timer, - mbedtls_ssl_set_timer_t *f_set_timer, - mbedtls_ssl_get_timer_t *f_get_timer ) -{ - ssl->p_timer = p_timer; - ssl->f_set_timer = f_set_timer; - ssl->f_get_timer = f_get_timer; - - /* Make sure we start with no timer running */ - ssl_set_timer( ssl, 0 ); -} - -#if defined(MBEDTLS_SSL_SRV_C) -void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf, - void *p_cache, - int (*f_get_cache)(void *, mbedtls_ssl_session *), - int (*f_set_cache)(void *, const mbedtls_ssl_session *) ) -{ - conf->p_cache = p_cache; - conf->f_get_cache = f_get_cache; - conf->f_set_cache = f_set_cache; -} -#endif /* MBEDTLS_SSL_SRV_C */ - -#if defined(MBEDTLS_SSL_CLI_C) -int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session ) -{ - int ret; - - if( ssl == NULL || - session == NULL || - ssl->session_negotiate == NULL || - ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) - { - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 ) - return( ret ); - - ssl->handshake->resume = 1; - - return( 0 ); -} -#endif /* MBEDTLS_SSL_CLI_C */ - -void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf, - const int *ciphersuites ) -{ - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites; - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites; - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites; - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites; -} - -void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf, - const int *ciphersuites, - int major, int minor ) -{ - if( major != MBEDTLS_SSL_MAJOR_VERSION_3 ) - return; - - if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 ) - return; - - conf->ciphersuite_list[minor] = ciphersuites; -} - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, - const mbedtls_x509_crt_profile *profile ) -{ - conf->cert_profile = profile; -} - -/* Append a new keycert entry to a (possibly empty) list */ -static int ssl_append_key_cert( mbedtls_ssl_key_cert **head, - mbedtls_x509_crt *cert, - mbedtls_pk_context *key ) -{ - mbedtls_ssl_key_cert *new; - - new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) ); - if( new == NULL ) - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - - new->cert = cert; - new->key = key; - new->next = NULL; - - /* Update head is the list was null, else add to the end */ - if( *head == NULL ) - { - *head = new; - } - else - { - mbedtls_ssl_key_cert *cur = *head; - while( cur->next != NULL ) - cur = cur->next; - cur->next = new; - } - - return( 0 ); -} - -int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, - mbedtls_x509_crt *own_cert, - mbedtls_pk_context *pk_key ) -{ - return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) ); -} - -void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf, - mbedtls_x509_crt *ca_chain, - mbedtls_x509_crl *ca_crl ) -{ - conf->ca_chain = ca_chain; - conf->ca_crl = ca_crl; -} -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) -int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl, - mbedtls_x509_crt *own_cert, - mbedtls_pk_context *pk_key ) -{ - return( ssl_append_key_cert( &ssl->handshake->sni_key_cert, - own_cert, pk_key ) ); -} - -void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl, - mbedtls_x509_crt *ca_chain, - mbedtls_x509_crl *ca_crl ) -{ - ssl->handshake->sni_ca_chain = ca_chain; - ssl->handshake->sni_ca_crl = ca_crl; -} - -void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl, - int authmode ) -{ - ssl->handshake->sni_authmode = authmode; -} -#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ - -#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) -/* - * Set EC J-PAKE password for current handshake - */ -int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, - const unsigned char *pw, - size_t pw_len ) -{ - mbedtls_ecjpake_role role; - - if( ssl->handshake == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - role = MBEDTLS_ECJPAKE_SERVER; - else - role = MBEDTLS_ECJPAKE_CLIENT; - - return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx, - role, - MBEDTLS_MD_SHA256, - MBEDTLS_ECP_DP_SECP256R1, - pw, pw_len ) ); -} -#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ - -#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) -int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, - const unsigned char *psk, size_t psk_len, - const unsigned char *psk_identity, size_t psk_identity_len ) -{ - if( psk == NULL || psk_identity == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( psk_len > MBEDTLS_PSK_MAX_LEN ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - /* Identity len will be encoded on two bytes */ - if( ( psk_identity_len >> 16 ) != 0 || - psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - if( conf->psk != NULL || conf->psk_identity != NULL ) - { - mbedtls_free( conf->psk ); - mbedtls_free( conf->psk_identity ); - conf->psk = NULL; - conf->psk_identity = NULL; - } - - if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL || - ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL ) - { - mbedtls_free( conf->psk ); - mbedtls_free( conf->psk_identity ); - conf->psk = NULL; - conf->psk_identity = NULL; - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - } - - conf->psk_len = psk_len; - conf->psk_identity_len = psk_identity_len; - - memcpy( conf->psk, psk, conf->psk_len ); - memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len ); - - return( 0 ); -} - -int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, - const unsigned char *psk, size_t psk_len ) -{ - if( psk == NULL || ssl->handshake == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( psk_len > MBEDTLS_PSK_MAX_LEN ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( ssl->handshake->psk != NULL ) - mbedtls_free( ssl->handshake->psk ); - - if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - - ssl->handshake->psk_len = psk_len; - memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len ); - - return( 0 ); -} - -void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, - int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, - size_t), - void *p_psk ) -{ - conf->f_psk = f_psk; - conf->p_psk = p_psk; -} -#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ - -#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) -int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G ) -{ - int ret; - - if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 || - ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 ) - { - mbedtls_mpi_free( &conf->dhm_P ); - mbedtls_mpi_free( &conf->dhm_G ); - return( ret ); - } - - return( 0 ); -} - -int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx ) -{ - int ret; - - if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 || - ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 ) - { - mbedtls_mpi_free( &conf->dhm_P ); - mbedtls_mpi_free( &conf->dhm_G ); - return( ret ); - } - - return( 0 ); -} -#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */ - -#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) -/* - * Set the minimum length for Diffie-Hellman parameters - */ -void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf, - unsigned int bitlen ) -{ - conf->dhm_min_bitlen = bitlen; -} -#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */ - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) -/* - * Set allowed/preferred hashes for handshake signatures - */ -void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, - const int *hashes ) -{ - conf->sig_hashes = hashes; -} -#endif - -#if defined(MBEDTLS_ECP_C) -/* - * Set the allowed elliptic curves - */ -void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf, - const mbedtls_ecp_group_id *curve_list ) -{ - conf->curve_list = curve_list; -} -#endif - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) -{ - size_t hostname_len; - - if( hostname == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - hostname_len = strlen( hostname ); - - if( hostname_len + 1 == 0 ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 ); - - if( ssl->hostname == NULL ) - return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); - - memcpy( ssl->hostname, hostname, hostname_len ); - - ssl->hostname[hostname_len] = '\0'; - - return( 0 ); -} -#endif - -#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) -void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, - int (*f_sni)(void *, mbedtls_ssl_context *, - const unsigned char *, size_t), - void *p_sni ) -{ - conf->f_sni = f_sni; - conf->p_sni = p_sni; -} -#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ - -#if defined(MBEDTLS_SSL_ALPN) -int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos ) -{ - size_t cur_len, tot_len; - const char **p; - - /* - * "Empty strings MUST NOT be included and byte strings MUST NOT be - * truncated". Check lengths now rather than later. - */ - tot_len = 0; - for( p = protos; *p != NULL; p++ ) - { - cur_len = strlen( *p ); - tot_len += cur_len; - - if( cur_len == 0 || cur_len > 255 || tot_len > 65535 ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - conf->alpn_list = protos; - - return( 0 ); -} - -const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl ) -{ - return( ssl->alpn_chosen ); -} -#endif /* MBEDTLS_SSL_ALPN */ - -void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ) -{ - conf->max_major_ver = major; - conf->max_minor_ver = minor; -} - -void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ) -{ - conf->min_major_ver = major; - conf->min_minor_ver = minor; -} - -#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) -void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback ) -{ - conf->fallback = fallback; -} -#endif - -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) -void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm ) -{ - conf->encrypt_then_mac = etm; -} -#endif - -#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) -void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems ) -{ - conf->extended_ms = ems; -} -#endif - -#if defined(MBEDTLS_ARC4_C) -void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 ) -{ - conf->arc4_disabled = arc4; -} -#endif - -#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) -int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code ) -{ - if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID || - mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN ) - { - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - conf->mfl_code = mfl_code; - - return( 0 ); -} -#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ - -#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) -void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate ) -{ - conf->trunc_hmac = truncate; -} -#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ - -#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) -void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split ) -{ - conf->cbc_record_splitting = split; -} -#endif - -void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy ) -{ - conf->allow_legacy_renegotiation = allow_legacy; -} - -#if defined(MBEDTLS_SSL_RENEGOTIATION) -void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation ) -{ - conf->disable_renegotiation = renegotiation; -} - -void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records ) -{ - conf->renego_max_records = max_records; -} - -void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, - const unsigned char period[8] ) -{ - memcpy( conf->renego_period, period, 8 ); -} -#endif /* MBEDTLS_SSL_RENEGOTIATION */ - -#if defined(MBEDTLS_SSL_SESSION_TICKETS) -#if defined(MBEDTLS_SSL_CLI_C) -void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets ) -{ - conf->session_tickets = use_tickets; -} -#endif - -#if defined(MBEDTLS_SSL_SRV_C) -void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf, - mbedtls_ssl_ticket_write_t *f_ticket_write, - mbedtls_ssl_ticket_parse_t *f_ticket_parse, - void *p_ticket ) -{ - conf->f_ticket_write = f_ticket_write; - conf->f_ticket_parse = f_ticket_parse; - conf->p_ticket = p_ticket; -} -#endif -#endif /* MBEDTLS_SSL_SESSION_TICKETS */ - -#if defined(MBEDTLS_SSL_EXPORT_KEYS) -void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, - mbedtls_ssl_export_keys_t *f_export_keys, - void *p_export_keys ) -{ - conf->f_export_keys = f_export_keys; - conf->p_export_keys = p_export_keys; -} -#endif - -/* - * SSL get accessors - */ -size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) -{ - return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); -} - -uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ) -{ - if( ssl->session != NULL ) - return( ssl->session->verify_result ); - - if( ssl->session_negotiate != NULL ) - return( ssl->session_negotiate->verify_result ); - - return( 0xFFFFFFFF ); -} - -const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl ) -{ - if( ssl == NULL || ssl->session == NULL ) - return( NULL ); - - return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite ); -} - -const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ) -{ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - switch( ssl->minor_ver ) - { - case MBEDTLS_SSL_MINOR_VERSION_2: - return( "DTLSv1.0" ); - - case MBEDTLS_SSL_MINOR_VERSION_3: - return( "DTLSv1.2" ); - - default: - return( "unknown (DTLS)" ); - } - } -#endif - - switch( ssl->minor_ver ) - { - case MBEDTLS_SSL_MINOR_VERSION_0: - return( "SSLv3.0" ); - - case MBEDTLS_SSL_MINOR_VERSION_1: - return( "TLSv1.0" ); - - case MBEDTLS_SSL_MINOR_VERSION_2: - return( "TLSv1.1" ); - - case MBEDTLS_SSL_MINOR_VERSION_3: - return( "TLSv1.2" ); - - default: - return( "unknown" ); - } -} - -int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ) -{ - size_t transform_expansion; - const mbedtls_ssl_transform *transform = ssl->transform_out; - -#if defined(MBEDTLS_ZLIB_SUPPORT) - if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL ) - return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); -#endif - - if( transform == NULL ) - return( (int) mbedtls_ssl_hdr_len( ssl ) ); - - switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) ) - { - case MBEDTLS_MODE_GCM: - case MBEDTLS_MODE_CCM: - case MBEDTLS_MODE_STREAM: - transform_expansion = transform->minlen; - break; - - case MBEDTLS_MODE_CBC: - transform_expansion = transform->maclen - + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc ); - break; - - default: - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - - return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) ); -} - -#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) -size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ) -{ - size_t max_len; - - /* - * Assume mfl_code is correct since it was checked when set - */ - max_len = mfl_code_to_length[ssl->conf->mfl_code]; - - /* - * Check if a smaller max length was negotiated - */ - if( ssl->session_out != NULL && - mfl_code_to_length[ssl->session_out->mfl_code] < max_len ) - { - max_len = mfl_code_to_length[ssl->session_out->mfl_code]; - } - - return max_len; -} -#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl ) -{ - if( ssl == NULL || ssl->session == NULL ) - return( NULL ); - - return( ssl->session->peer_cert ); -} -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -#if defined(MBEDTLS_SSL_CLI_C) -int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst ) -{ - if( ssl == NULL || - dst == NULL || - ssl->session == NULL || - ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) - { - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - - return( ssl_session_copy( dst, ssl->session ) ); -} -#endif /* MBEDTLS_SSL_CLI_C */ - -/* - * Perform a single step of the SSL handshake - */ -int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) -{ - int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - ret = mbedtls_ssl_handshake_client_step( ssl ); -#endif -#if defined(MBEDTLS_SSL_SRV_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - ret = mbedtls_ssl_handshake_server_step( ssl ); -#endif - - return( ret ); -} - -/* - * Perform the SSL handshake - */ -int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ) -{ - int ret = 0; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) ); - - while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - { - ret = mbedtls_ssl_handshake_step( ssl ); - - if( ret != 0 ) - break; - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) ); - - return( ret ); -} - -#if defined(MBEDTLS_SSL_RENEGOTIATION) -#if defined(MBEDTLS_SSL_SRV_C) -/* - * Write HelloRequest to request renegotiation on server - */ -static int ssl_write_hello_request( mbedtls_ssl_context *ssl ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) ); - - ssl->out_msglen = 4; - ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; - ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST; - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) ); - - return( 0 ); -} -#endif /* MBEDTLS_SSL_SRV_C */ - -/* - * Actually renegotiate current connection, triggered by either: - * - any side: calling mbedtls_ssl_renegotiate(), - * - client: receiving a HelloRequest during mbedtls_ssl_read(), - * - server: receiving any handshake message on server during mbedtls_ssl_read() after - * the initial handshake is completed. - * If the handshake doesn't complete due to waiting for I/O, it will continue - * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively. - */ -static int ssl_start_renegotiation( mbedtls_ssl_context *ssl ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) ); - - if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) - return( ret ); - - /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and - * the ServerHello will have message_seq = 1" */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) - { - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - ssl->handshake->out_msg_seq = 1; - else - ssl->handshake->in_msg_seq = 1; - } -#endif - - ssl->state = MBEDTLS_SSL_HELLO_REQUEST; - ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS; - - if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); - return( ret ); - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) ); - - return( 0 ); -} - -/* - * Renegotiate current connection on client, - * or request renegotiation on server - */ -int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ) -{ - int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - -#if defined(MBEDTLS_SSL_SRV_C) - /* On server, just send the request */ - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) - { - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; - - /* Did we already try/start sending HelloRequest? */ - if( ssl->out_left != 0 ) - return( mbedtls_ssl_flush_output( ssl ) ); - - return( ssl_write_hello_request( ssl ) ); - } -#endif /* MBEDTLS_SSL_SRV_C */ - -#if defined(MBEDTLS_SSL_CLI_C) - /* - * On client, either start the renegotiation process or, - * if already in progress, continue the handshake - */ - if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) - { - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret ); - return( ret ); - } - } - else - { - if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); - return( ret ); - } - } -#endif /* MBEDTLS_SSL_CLI_C */ - - return( ret ); -} - -/* - * Check record counters and renegotiate if they're above the limit. - */ -static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl ) -{ - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER || - ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING || - ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ) - { - return( 0 ); - } - - if( memcmp( ssl->in_ctr, ssl->conf->renego_period, 8 ) <= 0 && - memcmp( ssl->out_ctr, ssl->conf->renego_period, 8 ) <= 0 ) - { - return( 0 ); - } - - MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) ); - return( mbedtls_ssl_renegotiate( ssl ) ); -} -#endif /* MBEDTLS_SSL_RENEGOTIATION */ - -/* - * Receive application data decrypted from the SSL layer - */ -int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) -{ - int ret, record_read = 0; - size_t n; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) - return( ret ); - - if( ssl->handshake != NULL && - ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) - { - if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) - return( ret ); - } - } -#endif - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); - return( ret ); - } -#endif - - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - { - ret = mbedtls_ssl_handshake( ssl ); - if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ) - { - record_read = 1; - } - else if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); - return( ret ); - } - } - - if( ssl->in_offt == NULL ) - { - /* Start timer if not already running */ - if( ssl->f_get_timer != NULL && - ssl->f_get_timer( ssl->p_timer ) == -1 ) - { - ssl_set_timer( ssl, ssl->conf->read_timeout ); - } - - if( ! record_read ) - { - if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) - { - if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) - return( 0 ); - - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - } - - if( ssl->in_msglen == 0 && - ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA ) - { - /* - * OpenSSL sends empty messages to randomize the IV - */ - if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) - { - if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) - return( 0 ); - - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); - return( ret ); - } - } - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); - -#if defined(MBEDTLS_SSL_CLI_C) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && - ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST || - ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); - - /* With DTLS, drop the packet (probably from last handshake) */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - return( MBEDTLS_ERR_SSL_WANT_READ ); -#endif - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) ); - - /* With DTLS, drop the packet (probably from last handshake) */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - return( MBEDTLS_ERR_SSL_WANT_READ ); -#endif - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } -#endif - - if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || - ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && - ssl->conf->allow_legacy_renegotiation == - MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) - { - MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) ); - -#if defined(MBEDTLS_SSL_PROTO_SSL3) - if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) - { - /* - * SSLv3 does not have a "no_renegotiation" alert - */ - if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) - return( ret ); - } - else -#endif /* MBEDTLS_SSL_PROTO_SSL3 */ -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) - { - if( ( ret = mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_WARNING, - MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) - { - return( ret ); - } - } - else -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || - MBEDTLS_SSL_PROTO_TLS1_2 */ - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); - return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); - } - } - else - { - /* DTLS clients need to know renego is server-initiated */ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && - ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) - { - ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; - } -#endif - ret = ssl_start_renegotiation( ssl ); - if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ) - { - record_read = 1; - } - else if( ret != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret ); - return( ret ); - } - } - - /* If a non-handshake record was read during renego, fallthrough, - * else tell the user they should call mbedtls_ssl_read() again */ - if( ! record_read ) - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) - { - - if( ssl->conf->renego_max_records >= 0 ) - { - if( ++ssl->renego_records_seen > ssl->conf->renego_max_records ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " - "but not honored by client" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - } - } -#endif /* MBEDTLS_SSL_RENEGOTIATION */ - - /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */ - if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) ); - return( MBEDTLS_ERR_SSL_WANT_READ ); - } - - if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); - return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); - } - - ssl->in_offt = ssl->in_msg; - - /* We're going to return something now, cancel timer, - * except if handshake (renegotiation) is in progress */ - if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) - ssl_set_timer( ssl, 0 ); - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - /* If we requested renego but received AppData, resend HelloRequest. - * Do it now, after setting in_offt, to avoid taking this branch - * again if ssl_write_hello_request() returns WANT_WRITE */ -#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) - if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && - ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) - { - if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret ); - return( ret ); - } - } -#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ -#endif - } - - n = ( len < ssl->in_msglen ) - ? len : ssl->in_msglen; - - memcpy( buf, ssl->in_offt, n ); - ssl->in_msglen -= n; - - if( ssl->in_msglen == 0 ) - /* all bytes consumed */ - ssl->in_offt = NULL; - else - /* more data available */ - ssl->in_offt += n; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) ); - - return( (int) n ); -} - -/* - * Send application data to be encrypted by the SSL layer, - * taking care of max fragment length and buffer size - */ -static int ssl_write_real( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ - int ret; -#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) - size_t max_len = mbedtls_ssl_get_max_frag_len( ssl ); - - if( len > max_len ) - { -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) " - "maximum fragment length: %d > %d", - len, max_len ) ); - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - } - else -#endif - len = max_len; - } -#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ - - if( ssl->out_left != 0 ) - { - if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); - return( ret ); - } - } - else - { - ssl->out_msglen = len; - ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA; - memcpy( ssl->out_msg, buf, len ); - - if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); - return( ret ); - } - } - - return( (int) len ); -} - -/* - * Write application data, doing 1/n-1 splitting if necessary. - * - * With non-blocking I/O, ssl_write_real() may return WANT_WRITE, - * then the caller will call us again with the same arguments, so - * remember wether we already did the split or not. - */ -#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) -static int ssl_write_split( mbedtls_ssl_context *ssl, - const unsigned char *buf, size_t len ) -{ - int ret; - - if( ssl->conf->cbc_record_splitting == - MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED || - len <= 1 || - ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 || - mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ) - != MBEDTLS_MODE_CBC ) - { - return( ssl_write_real( ssl, buf, len ) ); - } - - if( ssl->split_done == 0 ) - { - if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 ) - return( ret ); - ssl->split_done = 1; - } - - if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 ) - return( ret ); - ssl->split_done = 0; - - return( ret + 1 ); -} -#endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ - -/* - * Write application data (public-facing wrapper) - */ -int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) -{ - int ret; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) ); - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); - return( ret ); - } -#endif - - if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) - { - if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); - return( ret ); - } - } - -#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) - ret = ssl_write_split( ssl, buf, len ); -#else - ret = ssl_write_real( ssl, buf, len ); -#endif - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) ); - - return( ret ); -} - -/* - * Notify the peer that the connection is being closed - */ -int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ) -{ - int ret; - - if( ssl == NULL || ssl->conf == NULL ) - return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); - - if( ssl->out_left != 0 ) - return( mbedtls_ssl_flush_output( ssl ) ); - - if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) - { - if( ( ret = mbedtls_ssl_send_alert_message( ssl, - MBEDTLS_SSL_ALERT_LEVEL_WARNING, - MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) - { - MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret ); - return( ret ); - } - } - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); - - return( 0 ); -} - -void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) -{ - if( transform == NULL ) - return; - -#if defined(MBEDTLS_ZLIB_SUPPORT) - deflateEnd( &transform->ctx_deflate ); - inflateEnd( &transform->ctx_inflate ); -#endif - - mbedtls_cipher_free( &transform->cipher_ctx_enc ); - mbedtls_cipher_free( &transform->cipher_ctx_dec ); - - mbedtls_md_free( &transform->md_ctx_enc ); - mbedtls_md_free( &transform->md_ctx_dec ); - - mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); -} - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert ) -{ - mbedtls_ssl_key_cert *cur = key_cert, *next; - - while( cur != NULL ) - { - next = cur->next; - mbedtls_free( cur ); - cur = next; - } -} -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ) -{ - if( handshake == NULL ) - return; - -#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ - defined(MBEDTLS_SSL_PROTO_TLS1_1) - mbedtls_md5_free( &handshake->fin_md5 ); - mbedtls_sha1_free( &handshake->fin_sha1 ); -#endif -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) -#if defined(MBEDTLS_SHA256_C) - mbedtls_sha256_free( &handshake->fin_sha256 ); -#endif -#if defined(MBEDTLS_SHA512_C) - mbedtls_sha512_free( &handshake->fin_sha512 ); -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ - -#if defined(MBEDTLS_DHM_C) - mbedtls_dhm_free( &handshake->dhm_ctx ); -#endif -#if defined(MBEDTLS_ECDH_C) - mbedtls_ecdh_free( &handshake->ecdh_ctx ); -#endif -#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) - mbedtls_ecjpake_free( &handshake->ecjpake_ctx ); -#if defined(MBEDTLS_SSL_CLI_C) - mbedtls_free( handshake->ecjpake_cache ); - handshake->ecjpake_cache = NULL; - handshake->ecjpake_cache_len = 0; -#endif -#endif - -#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ - defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) - /* explicit void pointer cast for buggy MS compiler */ - mbedtls_free( (void *) handshake->curves ); -#endif - -#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) - if( handshake->psk != NULL ) - { - mbedtls_zeroize( handshake->psk, handshake->psk_len ); - mbedtls_free( handshake->psk ); - } -#endif - -#if defined(MBEDTLS_X509_CRT_PARSE_C) && \ - defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) - /* - * Free only the linked list wrapper, not the keys themselves - * since the belong to the SNI callback - */ - if( handshake->sni_key_cert != NULL ) - { - mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next; - - while( cur != NULL ) - { - next = cur->next; - mbedtls_free( cur ); - cur = next; - } - } -#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */ - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - mbedtls_free( handshake->verify_cookie ); - mbedtls_free( handshake->hs_msg ); - ssl_flight_free( handshake->flight ); -#endif - - mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); -} - -void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) -{ - if( session == NULL ) - return; - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - if( session->peer_cert != NULL ) - { - mbedtls_x509_crt_free( session->peer_cert ); - mbedtls_free( session->peer_cert ); - } -#endif - -#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) - mbedtls_free( session->ticket ); -#endif - - mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) ); -} - -/* - * Free an SSL context - */ -void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) -{ - if( ssl == NULL ) - return; - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) ); - - if( ssl->out_buf != NULL ) - { - mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN ); - mbedtls_free( ssl->out_buf ); - } - - if( ssl->in_buf != NULL ) - { - mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN ); - mbedtls_free( ssl->in_buf ); - } - -#if defined(MBEDTLS_ZLIB_SUPPORT) - if( ssl->compress_buf != NULL ) - { - mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN ); - mbedtls_free( ssl->compress_buf ); - } -#endif - - if( ssl->transform ) - { - mbedtls_ssl_transform_free( ssl->transform ); - mbedtls_free( ssl->transform ); - } - - if( ssl->handshake ) - { - mbedtls_ssl_handshake_free( ssl->handshake ); - mbedtls_ssl_transform_free( ssl->transform_negotiate ); - mbedtls_ssl_session_free( ssl->session_negotiate ); - - mbedtls_free( ssl->handshake ); - mbedtls_free( ssl->transform_negotiate ); - mbedtls_free( ssl->session_negotiate ); - } - - if( ssl->session ) - { - mbedtls_ssl_session_free( ssl->session ); - mbedtls_free( ssl->session ); - } - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - if( ssl->hostname != NULL ) - { - mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) ); - mbedtls_free( ssl->hostname ); - } -#endif - -#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) - if( mbedtls_ssl_hw_record_finish != NULL ) - { - MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) ); - mbedtls_ssl_hw_record_finish( ssl ); - } -#endif - -#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) - mbedtls_free( ssl->cli_id ); -#endif - - MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) ); - - /* Actually clear after last debug message */ - mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); -} - -/* - * Initialze mbedtls_ssl_config - */ -void mbedtls_ssl_config_init( mbedtls_ssl_config *conf ) -{ - memset( conf, 0, sizeof( mbedtls_ssl_config ) ); -} - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) -static int ssl_preset_default_hashes[] = { -#if defined(MBEDTLS_SHA512_C) - MBEDTLS_MD_SHA512, - MBEDTLS_MD_SHA384, -#endif -#if defined(MBEDTLS_SHA256_C) - MBEDTLS_MD_SHA256, - MBEDTLS_MD_SHA224, -#endif -#if defined(MBEDTLS_SHA1_C) - MBEDTLS_MD_SHA1, -#endif - MBEDTLS_MD_NONE -}; -#endif - -static int ssl_preset_suiteb_ciphersuites[] = { - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - 0 -}; - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) -static int ssl_preset_suiteb_hashes[] = { - MBEDTLS_MD_SHA256, - MBEDTLS_MD_SHA384, - MBEDTLS_MD_NONE -}; -#endif - -#if defined(MBEDTLS_ECP_C) -static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = { - MBEDTLS_ECP_DP_SECP256R1, - MBEDTLS_ECP_DP_SECP384R1, - MBEDTLS_ECP_DP_NONE -}; -#endif - -/* - * Load default in mbedtls_ssl_config - */ -int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf, - int endpoint, int transport, int preset ) -{ -#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) - int ret; -#endif - - /* Use the functions here so that they are covered in tests, - * but otherwise access member directly for efficiency */ - mbedtls_ssl_conf_endpoint( conf, endpoint ); - mbedtls_ssl_conf_transport( conf, transport ); - - /* - * Things that are common to all presets - */ -#if defined(MBEDTLS_SSL_CLI_C) - if( endpoint == MBEDTLS_SSL_IS_CLIENT ) - { - conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED; -#if defined(MBEDTLS_SSL_SESSION_TICKETS) - conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED; -#endif - } -#endif - -#if defined(MBEDTLS_ARC4_C) - conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED; -#endif - -#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) - conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; -#endif - -#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) - conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; -#endif - -#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) - conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED; -#endif - -#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) - conf->f_cookie_write = ssl_cookie_write_dummy; - conf->f_cookie_check = ssl_cookie_check_dummy; -#endif - -#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) - conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED; -#endif - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN; - conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX; -#endif - -#if defined(MBEDTLS_SSL_RENEGOTIATION) - conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT; - memset( conf->renego_period, 0xFF, 7 ); - conf->renego_period[7] = 0x00; -#endif - -#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) - if( endpoint == MBEDTLS_SSL_IS_SERVER ) - { - if( ( ret = mbedtls_ssl_conf_dh_param( conf, - MBEDTLS_DHM_RFC5114_MODP_2048_P, - MBEDTLS_DHM_RFC5114_MODP_2048_G ) ) != 0 ) - { - return( ret ); - } - } -#endif - - /* - * Preset-specific defaults - */ - switch( preset ) - { - /* - * NSA Suite B - */ - case MBEDTLS_SSL_PRESET_SUITEB: - conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; - conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ - conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; - conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; - - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = - ssl_preset_suiteb_ciphersuites; - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - conf->cert_profile = &mbedtls_x509_crt_profile_suiteb; -#endif - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) - conf->sig_hashes = ssl_preset_suiteb_hashes; -#endif - -#if defined(MBEDTLS_ECP_C) - conf->curve_list = ssl_preset_suiteb_curves; -#endif - break; - - /* - * Default - */ - default: - conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; - conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */ - conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; - conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; - -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2; -#endif - - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = - conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = - mbedtls_ssl_list_ciphersuites(); - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - conf->cert_profile = &mbedtls_x509_crt_profile_default; -#endif - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) - conf->sig_hashes = ssl_preset_default_hashes; -#endif - -#if defined(MBEDTLS_ECP_C) - conf->curve_list = mbedtls_ecp_grp_id_list(); -#endif - -#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) - conf->dhm_min_bitlen = 1024; -#endif - } - - return( 0 ); -} - -/* - * Free mbedtls_ssl_config - */ -void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) -{ -#if defined(MBEDTLS_DHM_C) - mbedtls_mpi_free( &conf->dhm_P ); - mbedtls_mpi_free( &conf->dhm_G ); -#endif - -#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) - if( conf->psk != NULL ) - { - mbedtls_zeroize( conf->psk, conf->psk_len ); - mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len ); - mbedtls_free( conf->psk ); - mbedtls_free( conf->psk_identity ); - conf->psk_len = 0; - conf->psk_identity_len = 0; - } -#endif - -#if defined(MBEDTLS_X509_CRT_PARSE_C) - ssl_key_cert_free( conf->key_cert ); -#endif - - mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) ); -} - -#if defined(MBEDTLS_PK_C) && \ - ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) ) -/* - * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX - */ -unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ) -{ -#if defined(MBEDTLS_RSA_C) - if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) ) - return( MBEDTLS_SSL_SIG_RSA ); -#endif -#if defined(MBEDTLS_ECDSA_C) - if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) ) - return( MBEDTLS_SSL_SIG_ECDSA ); -#endif - return( MBEDTLS_SSL_SIG_ANON ); -} - -mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig ) -{ - switch( sig ) - { -#if defined(MBEDTLS_RSA_C) - case MBEDTLS_SSL_SIG_RSA: - return( MBEDTLS_PK_RSA ); -#endif -#if defined(MBEDTLS_ECDSA_C) - case MBEDTLS_SSL_SIG_ECDSA: - return( MBEDTLS_PK_ECDSA ); -#endif - default: - return( MBEDTLS_PK_NONE ); - } -} -#endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */ - -/* - * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX - */ -mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash ) -{ - switch( hash ) - { -#if defined(MBEDTLS_MD5_C) - case MBEDTLS_SSL_HASH_MD5: - return( MBEDTLS_MD_MD5 ); -#endif -#if defined(MBEDTLS_SHA1_C) - case MBEDTLS_SSL_HASH_SHA1: - return( MBEDTLS_MD_SHA1 ); -#endif -#if defined(MBEDTLS_SHA256_C) - case MBEDTLS_SSL_HASH_SHA224: - return( MBEDTLS_MD_SHA224 ); - case MBEDTLS_SSL_HASH_SHA256: - return( MBEDTLS_MD_SHA256 ); -#endif -#if defined(MBEDTLS_SHA512_C) - case MBEDTLS_SSL_HASH_SHA384: - return( MBEDTLS_MD_SHA384 ); - case MBEDTLS_SSL_HASH_SHA512: - return( MBEDTLS_MD_SHA512 ); -#endif - default: - return( MBEDTLS_MD_NONE ); - } -} - -/* - * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX - */ -unsigned char mbedtls_ssl_hash_from_md_alg( int md ) -{ - switch( md ) - { -#if defined(MBEDTLS_MD5_C) - case MBEDTLS_MD_MD5: - return( MBEDTLS_SSL_HASH_MD5 ); -#endif -#if defined(MBEDTLS_SHA1_C) - case MBEDTLS_MD_SHA1: - return( MBEDTLS_SSL_HASH_SHA1 ); -#endif -#if defined(MBEDTLS_SHA256_C) - case MBEDTLS_MD_SHA224: - return( MBEDTLS_SSL_HASH_SHA224 ); - case MBEDTLS_MD_SHA256: - return( MBEDTLS_SSL_HASH_SHA256 ); -#endif -#if defined(MBEDTLS_SHA512_C) - case MBEDTLS_MD_SHA384: - return( MBEDTLS_SSL_HASH_SHA384 ); - case MBEDTLS_MD_SHA512: - return( MBEDTLS_SSL_HASH_SHA512 ); -#endif - default: - return( MBEDTLS_SSL_HASH_NONE ); - } -} - -#if defined(MBEDTLS_ECP_C) -/* - * Check if a curve proposed by the peer is in our list. - * Return 0 if we're willing to use it, -1 otherwise. - */ -int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id ) -{ - const mbedtls_ecp_group_id *gid; - - if( ssl->conf->curve_list == NULL ) - return( -1 ); - - for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) - if( *gid == grp_id ) - return( 0 ); - - return( -1 ); -} -#endif /* MBEDTLS_ECP_C */ - -#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) -/* - * Check if a hash proposed by the peer is in our list. - * Return 0 if we're willing to use it, -1 otherwise. - */ -int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, - mbedtls_md_type_t md ) -{ - const int *cur; - - if( ssl->conf->sig_hashes == NULL ) - return( -1 ); - - for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) - if( *cur == (int) md ) - return( 0 ); - - return( -1 ); -} -#endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ - -#if defined(MBEDTLS_X509_CRT_PARSE_C) -int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, - const mbedtls_ssl_ciphersuite_t *ciphersuite, - int cert_endpoint, - uint32_t *flags ) -{ - int ret = 0; -#if defined(MBEDTLS_X509_CHECK_KEY_USAGE) - int usage = 0; -#endif -#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) - const char *ext_oid; - size_t ext_len; -#endif - -#if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \ - !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) - ((void) cert); - ((void) cert_endpoint); - ((void) flags); -#endif - -#if defined(MBEDTLS_X509_CHECK_KEY_USAGE) - if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) - { - /* Server part of the key exchange */ - switch( ciphersuite->key_exchange ) - { - case MBEDTLS_KEY_EXCHANGE_RSA: - case MBEDTLS_KEY_EXCHANGE_RSA_PSK: - usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT; - break; - - case MBEDTLS_KEY_EXCHANGE_DHE_RSA: - case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: - case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: - usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; - break; - - case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: - case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: - usage = MBEDTLS_X509_KU_KEY_AGREEMENT; - break; - - /* Don't use default: we want warnings when adding new values */ - case MBEDTLS_KEY_EXCHANGE_NONE: - case MBEDTLS_KEY_EXCHANGE_PSK: - case MBEDTLS_KEY_EXCHANGE_DHE_PSK: - case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: - case MBEDTLS_KEY_EXCHANGE_ECJPAKE: - usage = 0; - } - } - else - { - /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */ - usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; - } - - if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 ) - { - *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE; - ret = -1; - } -#else - ((void) ciphersuite); -#endif /* MBEDTLS_X509_CHECK_KEY_USAGE */ - -#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) - if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) - { - ext_oid = MBEDTLS_OID_SERVER_AUTH; - ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH ); - } - else - { - ext_oid = MBEDTLS_OID_CLIENT_AUTH; - ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH ); - } - - if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 ) - { - *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; - ret = -1; - } -#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ - - return( ret ); -} -#endif /* MBEDTLS_X509_CRT_PARSE_C */ - -/* - * Convert version numbers to/from wire format - * and, for DTLS, to/from TLS equivalent. - * - * For TLS this is the identity. - * For DTLS, use one complement (v -> 255 - v, and then map as follows: - * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1) - * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2) - */ -void mbedtls_ssl_write_version( int major, int minor, int transport, - unsigned char ver[2] ) -{ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - if( minor == MBEDTLS_SSL_MINOR_VERSION_2 ) - --minor; /* DTLS 1.0 stored as TLS 1.1 internally */ - - ver[0] = (unsigned char)( 255 - ( major - 2 ) ); - ver[1] = (unsigned char)( 255 - ( minor - 1 ) ); - } - else -#else - ((void) transport); -#endif - { - ver[0] = (unsigned char) major; - ver[1] = (unsigned char) minor; - } -} - -void mbedtls_ssl_read_version( int *major, int *minor, int transport, - const unsigned char ver[2] ) -{ -#if defined(MBEDTLS_SSL_PROTO_DTLS) - if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) - { - *major = 255 - ver[0] + 2; - *minor = 255 - ver[1] + 1; - - if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 ) - ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */ - } - else -#else - ((void) transport); -#endif - { - *major = ver[0]; - *minor = ver[1]; - } -} - -int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md ) -{ -#if defined(MBEDTLS_SSL_PROTO_TLS1_2) - if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) - return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; - - switch( md ) - { -#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) -#if defined(MBEDTLS_MD5_C) - case MBEDTLS_SSL_HASH_MD5: - ssl->handshake->calc_verify = ssl_calc_verify_tls; - break; -#endif -#if defined(MBEDTLS_SHA1_C) - case MBEDTLS_SSL_HASH_SHA1: - ssl->handshake->calc_verify = ssl_calc_verify_tls; - break; -#endif -#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ -#if defined(MBEDTLS_SHA512_C) - case MBEDTLS_SSL_HASH_SHA384: - ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384; - break; -#endif -#if defined(MBEDTLS_SHA256_C) - case MBEDTLS_SSL_HASH_SHA256: - ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256; - break; -#endif - default: - return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; - } - - return 0; -#else /* !MBEDTLS_SSL_PROTO_TLS1_2 */ - (void) ssl; - (void) md; - - return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; -#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ -} - -#endif /* MBEDTLS_SSL_TLS_C */ diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_468k_cpp.ld b/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_468k_cpp.ld deleted file mode 100644 index be3332d..0000000 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_468k_cpp.ld +++ /dev/null @@ -1,222 +0,0 @@ - - -ENTRY(Reset_Handler) - -INCLUDE "export-rom_symbol_v01.txt" - -GROUP ( - libgcc.a - libc.a - libg.a - libm.a - libnosys.a -) - -MEMORY -{ - ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */ - ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */ - BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */ - BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 224k */ - ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */ - MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */ - RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */ - - XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ - XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ - XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0x75000-0x20 /* XIP1: 468k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x08080000+0x20, LENGTH = 0x75000-0x20 /* XIP2: 468k, 32 Bytes resvd for header */ -} - - - -SECTIONS -{ - .rom.text : { } > ROM - .rom.rodata : { } > ROM - .ARM.exidx : - { - __exidx_start = .; - *(.ARM.exidx*) - *(.gnu.linkonce.armexidx.*) - __exidx_end = .; - } > ROM - .hal.rom.bss : { } > ROMBSS_RAM - - /* image1 entry, this section should in RAM and fixed address for ROM */ - .ram_image1.entry : - { - __ram_image1_text_start__ = .; - __ram_start_table_start__ = .; - KEEP(*(SORT(.image1.entry.data*))) - __ram_start_table_end__ = .; - - __image1_validate_code__ = .; - KEEP(*(.image1.validate.rodata*)) - KEEP(*(.image1.export.symb*)) - } > BOOTLOADER_RAM - - /* Add . to assign the start address of the section */ - /* to prevent the change of the start address by ld doing section alignment */ - .ram_image1.text . : - { - /* image1 text */ - *(.boot.ram.text*) - *(.boot.rodata*) - } > BOOTLOADER_RAM - - .ram_image1.data . : - { - __ram_image1_data_start__ = .; - KEEP(*(.boot.ram.data*)) - __ram_image1_data_end__ = .; - - __ram_image1_text_end__ = .; - } > BOOTLOADER_RAM - - .ram_image1.bss . : - { - __image1_bss_start__ = .; - KEEP(*(.boot.ram.bss*)) - KEEP(*(.boot.ram.end.bss*)) - __image1_bss_end__ = .; - } > BOOTLOADER_RAM - - .ram_image2.entry : - { - __ram_image2_text_start__ = .; - __image2_entry_func__ = .; - KEEP(*(SORT(.image2.entry.data*))) - - __image2_validate_code__ = .; - KEEP(*(.image2.validate.rodata*)) - - } > BD_RAM - - .ram_image2.text : - { - KEEP(*(.image2.ram.text*)) - } > BD_RAM - - .ram_image2.data : - { - __data_start__ = .; - *(.data*) - __data_end__ = .; - __ram_image2_text_end__ = .; - . = ALIGN(16); - } > BD_RAM - - .ram_image2.bss : - { - __bss_start__ = .; - *(.bss*) - *(COMMON) - } > BD_RAM - - .ram_image2.skb.bss : - { - *(.bdsram.data*) - __bss_end__ = .; - } > BD_RAM - - .ram_heap.data : - { - *(.bfsram.data*) - } > BD_RAM - - . = ALIGN(8); - PROVIDE(heap_start = .); - PROVIDE(heap_end = 0x1003CFFF); - PROVIDE(heap_len = heap_end - heap_start); - - .rom.bss : - { - *(.heap.stdlib*) - } > ROM_BSS_RAM - - .ram_rdp.text : - { - __rom_top_4k_start_ = .; - __rdp_text_start__ = .; - KEEP(*(.rdp.ram.text*)) - KEEP(*(.rdp.ram.data*)) - __rdp_text_end__ = .; - . = ALIGN(16); - - } > RDP_RAM - - .xip_image1.text : - { - __flash_boot_text_start__ = .; - - *(.flashboot.text*) - - __flash_boot_text_end__ = .; - - . = ALIGN(16); - } > XIPBOOT - - .xip_image2.text : - { - __flash_text_start__ = .; - - *(.img2_custom_signature*) - *(.text) - *(.text*) - *(.rodata) - *(.rodata*) - *(.debug_trace*) - - /* https://www.embedded.com/building-bare-metal-arm-systems-with-gnu-part-3/ */ - KEEP(*crtbegin.o(.ctors)) - KEEP(*(EXCLUDE_FILE (*ctrend.o) .ctors)) - KEEP(*(SORT(.ctors.*))) - KEEP(*crtend.o(.ctors)) - KEEP(*crtbegin.o(.dtors)) - KEEP(*(EXCLUDE_FILE (*crtend.o) .dtors)) - KEEP(*(SORT(.dtors.*))) - KEEP(*crtend.o(.dtors)) - *(.rodata .rodata.* .gnu.linkonce.r.*) - - /* Add This for C++ support */ - /* ambd_arduino/Arduino_package/hardware/variants/rtl8720dn_bw16/linker_scripts/gcc/rlx8721d_img2_is_arduino.ld */ - . = ALIGN(4); - __preinit_array_start = .; - KEEP(*(.preinit_array)) - __preinit_array_end = .; - . = ALIGN(4); - __init_array_start = .; - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - __init_array_end = .; - . = ALIGN(4); - __fini_array_start = .; - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - __fini_array_end = .; - /*-----------------*/ - - . = ALIGN (4); - __cmd_table_start__ = .; - KEEP(*(.cmd.table.data*)) - __cmd_table_end__ = .; - - /* https://community.silabs.com/s/article/understand-the-gnu-linker-script-of-cortex-m4?language=en_US */ - KEEP(*(.init)) - KEEP(*(.fini)) - *(.init) - *(.fini) - - __flash_text_end__ = .; - - . = ALIGN (16); - } > XIP1 -} - -SECTIONS -{ - /* Bootloader symbol list */ - boot_export_symbol = 0x10002020; -} diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_cpp.ld b/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_cpp.ld deleted file mode 100644 index 2cdfd46..0000000 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip1_2M_cpp.ld +++ /dev/null @@ -1,222 +0,0 @@ - - -ENTRY(Reset_Handler) - -INCLUDE "export-rom_symbol_v01.txt" - -GROUP ( - libgcc.a - libc.a - libg.a - libm.a - libnosys.a -) - -MEMORY -{ - ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */ - ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */ - BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */ - BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 224k */ - ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */ - MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */ - RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */ - - XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ - XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ - XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xC5000-0x20 /* XIP1: 788k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x080D0000+0x20, LENGTH = 0xC5000-0x20 /* XIP2: 788k, 32 Bytes resvd for header */ -} - - - -SECTIONS -{ - .rom.text : { } > ROM - .rom.rodata : { } > ROM - .ARM.exidx : - { - __exidx_start = .; - *(.ARM.exidx*) - *(.gnu.linkonce.armexidx.*) - __exidx_end = .; - } > ROM - .hal.rom.bss : { } > ROMBSS_RAM - - /* image1 entry, this section should in RAM and fixed address for ROM */ - .ram_image1.entry : - { - __ram_image1_text_start__ = .; - __ram_start_table_start__ = .; - KEEP(*(SORT(.image1.entry.data*))) - __ram_start_table_end__ = .; - - __image1_validate_code__ = .; - KEEP(*(.image1.validate.rodata*)) - KEEP(*(.image1.export.symb*)) - } > BOOTLOADER_RAM - - /* Add . to assign the start address of the section */ - /* to prevent the change of the start address by ld doing section alignment */ - .ram_image1.text . : - { - /* image1 text */ - *(.boot.ram.text*) - *(.boot.rodata*) - } > BOOTLOADER_RAM - - .ram_image1.data . : - { - __ram_image1_data_start__ = .; - KEEP(*(.boot.ram.data*)) - __ram_image1_data_end__ = .; - - __ram_image1_text_end__ = .; - } > BOOTLOADER_RAM - - .ram_image1.bss . : - { - __image1_bss_start__ = .; - KEEP(*(.boot.ram.bss*)) - KEEP(*(.boot.ram.end.bss*)) - __image1_bss_end__ = .; - } > BOOTLOADER_RAM - - .ram_image2.entry : - { - __ram_image2_text_start__ = .; - __image2_entry_func__ = .; - KEEP(*(SORT(.image2.entry.data*))) - - __image2_validate_code__ = .; - KEEP(*(.image2.validate.rodata*)) - - } > BD_RAM - - .ram_image2.text : - { - KEEP(*(.image2.ram.text*)) - } > BD_RAM - - .ram_image2.data : - { - __data_start__ = .; - *(.data*) - __data_end__ = .; - __ram_image2_text_end__ = .; - . = ALIGN(16); - } > BD_RAM - - .ram_image2.bss : - { - __bss_start__ = .; - *(.bss*) - *(COMMON) - } > BD_RAM - - .ram_image2.skb.bss : - { - *(.bdsram.data*) - __bss_end__ = .; - } > BD_RAM - - .ram_heap.data : - { - *(.bfsram.data*) - } > BD_RAM - - . = ALIGN(8); - PROVIDE(heap_start = .); - PROVIDE(heap_end = 0x1003CFFF); - PROVIDE(heap_len = heap_end - heap_start); - - .rom.bss : - { - *(.heap.stdlib*) - } > ROM_BSS_RAM - - .ram_rdp.text : - { - __rom_top_4k_start_ = .; - __rdp_text_start__ = .; - KEEP(*(.rdp.ram.text*)) - KEEP(*(.rdp.ram.data*)) - __rdp_text_end__ = .; - . = ALIGN(16); - - } > RDP_RAM - - .xip_image1.text : - { - __flash_boot_text_start__ = .; - - *(.flashboot.text*) - - __flash_boot_text_end__ = .; - - . = ALIGN(16); - } > XIPBOOT - - .xip_image2.text : - { - __flash_text_start__ = .; - - *(.img2_custom_signature*) - *(.text) - *(.text*) - *(.rodata) - *(.rodata*) - *(.debug_trace*) - - /* https://www.embedded.com/building-bare-metal-arm-systems-with-gnu-part-3/ */ - KEEP(*crtbegin.o(.ctors)) - KEEP(*(EXCLUDE_FILE (*ctrend.o) .ctors)) - KEEP(*(SORT(.ctors.*))) - KEEP(*crtend.o(.ctors)) - KEEP(*crtbegin.o(.dtors)) - KEEP(*(EXCLUDE_FILE (*crtend.o) .dtors)) - KEEP(*(SORT(.dtors.*))) - KEEP(*crtend.o(.dtors)) - *(.rodata .rodata.* .gnu.linkonce.r.*) - - /* Add This for C++ support */ - /* ambd_arduino/Arduino_package/hardware/variants/rtl8720dn_bw16/linker_scripts/gcc/rlx8721d_img2_is_arduino.ld */ - . = ALIGN(4); - __preinit_array_start = .; - KEEP(*(.preinit_array)) - __preinit_array_end = .; - . = ALIGN(4); - __init_array_start = .; - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - __init_array_end = .; - . = ALIGN(4); - __fini_array_start = .; - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - __fini_array_end = .; - /*-----------------*/ - - . = ALIGN (4); - __cmd_table_start__ = .; - KEEP(*(.cmd.table.data*)) - __cmd_table_end__ = .; - - /* https://community.silabs.com/s/article/understand-the-gnu-linker-script-of-cortex-m4?language=en_US */ - KEEP(*(.init)) - KEEP(*(.fini)) - *(.init) - *(.fini) - - __flash_text_end__ = .; - - . = ALIGN (16); - } > XIP1 -} - -SECTIONS -{ - /* Bootloader symbol list */ - boot_export_symbol = 0x10002020; -} diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_468k_cpp.ld b/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_468k_cpp.ld deleted file mode 100644 index 9a14106..0000000 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_2M_468k_cpp.ld +++ /dev/null @@ -1,222 +0,0 @@ - - -ENTRY(Reset_Handler) - -INCLUDE "export-rom_symbol_v01.txt" - -GROUP ( - libgcc.a - libc.a - libg.a - libm.a - libnosys.a -) - -MEMORY -{ - ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */ - ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */ - BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */ - BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 224k */ - ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */ - MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */ - RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */ - - XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ - XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ - XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0x75000-0x20 /* XIP1: 468k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x08080000+0x20, LENGTH = 0x75000-0x20 /* XIP2: 468k, 32 Bytes resvd for header */ -} - - - -SECTIONS -{ - .rom.text : { } > ROM - .rom.rodata : { } > ROM - .ARM.exidx : - { - __exidx_start = .; - *(.ARM.exidx*) - *(.gnu.linkonce.armexidx.*) - __exidx_end = .; - } > ROM - .hal.rom.bss : { } > ROMBSS_RAM - - /* image1 entry, this section should in RAM and fixed address for ROM */ - .ram_image1.entry : - { - __ram_image1_text_start__ = .; - __ram_start_table_start__ = .; - KEEP(*(SORT(.image1.entry.data*))) - __ram_start_table_end__ = .; - - __image1_validate_code__ = .; - KEEP(*(.image1.validate.rodata*)) - KEEP(*(.image1.export.symb*)) - } > BOOTLOADER_RAM - - /* Add . to assign the start address of the section */ - /* to prevent the change of the start address by ld doing section alignment */ - .ram_image1.text . : - { - /* image1 text */ - *(.boot.ram.text*) - *(.boot.rodata*) - } > BOOTLOADER_RAM - - .ram_image1.data . : - { - __ram_image1_data_start__ = .; - KEEP(*(.boot.ram.data*)) - __ram_image1_data_end__ = .; - - __ram_image1_text_end__ = .; - } > BOOTLOADER_RAM - - .ram_image1.bss . : - { - __image1_bss_start__ = .; - KEEP(*(.boot.ram.bss*)) - KEEP(*(.boot.ram.end.bss*)) - __image1_bss_end__ = .; - } > BOOTLOADER_RAM - - .ram_image2.entry : - { - __ram_image2_text_start__ = .; - __image2_entry_func__ = .; - KEEP(*(SORT(.image2.entry.data*))) - - __image2_validate_code__ = .; - KEEP(*(.image2.validate.rodata*)) - - } > BD_RAM - - .ram_image2.text : - { - KEEP(*(.image2.ram.text*)) - } > BD_RAM - - .ram_image2.data : - { - __data_start__ = .; - *(.data*) - __data_end__ = .; - __ram_image2_text_end__ = .; - . = ALIGN(16); - } > BD_RAM - - .ram_image2.bss : - { - __bss_start__ = .; - *(.bss*) - *(COMMON) - } > BD_RAM - - .ram_image2.skb.bss : - { - *(.bdsram.data*) - __bss_end__ = .; - } > BD_RAM - - .ram_heap.data : - { - *(.bfsram.data*) - } > BD_RAM - - . = ALIGN(8); - PROVIDE(heap_start = .); - PROVIDE(heap_end = 0x1003CFFF); - PROVIDE(heap_len = heap_end - heap_start); - - .rom.bss : - { - *(.heap.stdlib*) - } > ROM_BSS_RAM - - .ram_rdp.text : - { - __rom_top_4k_start_ = .; - __rdp_text_start__ = .; - KEEP(*(.rdp.ram.text*)) - KEEP(*(.rdp.ram.data*)) - __rdp_text_end__ = .; - . = ALIGN(16); - - } > RDP_RAM - - .xip_image1.text : - { - __flash_boot_text_start__ = .; - - *(.flashboot.text*) - - __flash_boot_text_end__ = .; - - . = ALIGN(16); - } > XIPBOOT - - .xip_image2.text : - { - __flash_text_start__ = .; - - *(.img2_custom_signature*) - *(.text) - *(.text*) - *(.rodata) - *(.rodata*) - *(.debug_trace*) - - /* https://www.embedded.com/building-bare-metal-arm-systems-with-gnu-part-3/ */ - KEEP(*crtbegin.o(.ctors)) - KEEP(*(EXCLUDE_FILE (*ctrend.o) .ctors)) - KEEP(*(SORT(.ctors.*))) - KEEP(*crtend.o(.ctors)) - KEEP(*crtbegin.o(.dtors)) - KEEP(*(EXCLUDE_FILE (*crtend.o) .dtors)) - KEEP(*(SORT(.dtors.*))) - KEEP(*crtend.o(.dtors)) - *(.rodata .rodata.* .gnu.linkonce.r.*) - - /* Add This for C++ support */ - /* ambd_arduino/Arduino_package/hardware/variants/rtl8720dn_bw16/linker_scripts/gcc/rlx8721d_img2_is_arduino.ld */ - . = ALIGN(4); - __preinit_array_start = .; - KEEP(*(.preinit_array)) - __preinit_array_end = .; - . = ALIGN(4); - __init_array_start = .; - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - __init_array_end = .; - . = ALIGN(4); - __fini_array_start = .; - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - __fini_array_end = .; - /*-----------------*/ - - . = ALIGN (4); - __cmd_table_start__ = .; - KEEP(*(.cmd.table.data*)) - __cmd_table_end__ = .; - - /* https://community.silabs.com/s/article/understand-the-gnu-linker-script-of-cortex-m4?language=en_US */ - KEEP(*(.init)) - KEEP(*(.fini)) - *(.init) - *(.fini) - - __flash_text_end__ = .; - - . = ALIGN (16); - } > XIP2 -} - -SECTIONS -{ - /* Bootloader symbol list */ - boot_export_symbol = 0x10002020; -} diff --git a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_4M_980k_cpp.ld b/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_4M_980k_cpp.ld deleted file mode 100644 index e8b78a4..0000000 --- a/platform/realtek-ambz/ld/rlx8711B-symbol-v02-img2_xip2_4M_980k_cpp.ld +++ /dev/null @@ -1,222 +0,0 @@ - - -ENTRY(Reset_Handler) - -INCLUDE "export-rom_symbol_v01.txt" - -GROUP ( - libgcc.a - libc.a - libg.a - libm.a - libnosys.a -) - -MEMORY -{ - ROM (rx) : ORIGIN = 0x00000000, LENGTH = 0x80000 /* ROM: 512k */ - ROMBSS_RAM (rw) : ORIGIN = 0x10000000, LENGTH = 0x2000 /* ROM BSS RAM: 8K */ - BOOTLOADER_RAM (rwx) : ORIGIN = 0x10002000, LENGTH = 0x3000 /* BOOT Loader RAM: 12K */ - BD_RAM (rwx) : ORIGIN = 0x10005000, LENGTH = 0x38000 /* MAIN RAM: 224k */ - ROM_BSS_RAM (rwx) : ORIGIN = 0x1003D000, LENGTH = 0x1000 /* ROM BSS RAM: 4K */ - MSP_RAM (wx) : ORIGIN = 0x1003E000, LENGTH = 0x1000 /* MSP RAM: 4k */ - RDP_RAM (wx) : ORIGIN = 0x1003F000, LENGTH = 0xFF0 /* RDP RAM: 4k-0x10 */ - - XIPBOOT (rx) : ORIGIN = 0x08000000+0x20, LENGTH = 0x04000-0x20 /* XIPBOOT: 16k, 32 Bytes resvd for header*/ - XIPSYS (r) : ORIGIN = 0x08009000, LENGTH = 0x1000 /* XIPSYS: 4K system data in flash */ - XIPCAL (r) : ORIGIN = 0x0800A000, LENGTH = 0x1000 /* XIPCAL: 4K calibration data in flash */ - XIP1 (rx) : ORIGIN = 0x0800B000+0x20, LENGTH = 0xF5000-0x20 /* XIP1: 980k, 32 Bytes resvd for header */ - XIP2 (rx) : ORIGIN = 0x08100000+0x20, LENGTH = 0xF5000-0x20 /* XIP2: 980k, 32 Bytes resvd for header */ -} - - - -SECTIONS -{ - .rom.text : { } > ROM - .rom.rodata : { } > ROM - .ARM.exidx : - { - __exidx_start = .; - *(.ARM.exidx*) - *(.gnu.linkonce.armexidx.*) - __exidx_end = .; - } > ROM - .hal.rom.bss : { } > ROMBSS_RAM - - /* image1 entry, this section should in RAM and fixed address for ROM */ - .ram_image1.entry : - { - __ram_image1_text_start__ = .; - __ram_start_table_start__ = .; - KEEP(*(SORT(.image1.entry.data*))) - __ram_start_table_end__ = .; - - __image1_validate_code__ = .; - KEEP(*(.image1.validate.rodata*)) - KEEP(*(.image1.export.symb*)) - } > BOOTLOADER_RAM - - /* Add . to assign the start address of the section */ - /* to prevent the change of the start address by ld doing section alignment */ - .ram_image1.text . : - { - /* image1 text */ - *(.boot.ram.text*) - *(.boot.rodata*) - } > BOOTLOADER_RAM - - .ram_image1.data . : - { - __ram_image1_data_start__ = .; - KEEP(*(.boot.ram.data*)) - __ram_image1_data_end__ = .; - - __ram_image1_text_end__ = .; - } > BOOTLOADER_RAM - - .ram_image1.bss . : - { - __image1_bss_start__ = .; - KEEP(*(.boot.ram.bss*)) - KEEP(*(.boot.ram.end.bss*)) - __image1_bss_end__ = .; - } > BOOTLOADER_RAM - - .ram_image2.entry : - { - __ram_image2_text_start__ = .; - __image2_entry_func__ = .; - KEEP(*(SORT(.image2.entry.data*))) - - __image2_validate_code__ = .; - KEEP(*(.image2.validate.rodata*)) - - } > BD_RAM - - .ram_image2.text : - { - KEEP(*(.image2.ram.text*)) - } > BD_RAM - - .ram_image2.data : - { - __data_start__ = .; - *(.data*) - __data_end__ = .; - __ram_image2_text_end__ = .; - . = ALIGN(16); - } > BD_RAM - - .ram_image2.bss : - { - __bss_start__ = .; - *(.bss*) - *(COMMON) - } > BD_RAM - - .ram_image2.skb.bss : - { - *(.bdsram.data*) - __bss_end__ = .; - } > BD_RAM - - .ram_heap.data : - { - *(.bfsram.data*) - } > BD_RAM - - . = ALIGN(8); - PROVIDE(heap_start = .); - PROVIDE(heap_end = 0x1003CFFF); - PROVIDE(heap_len = heap_end - heap_start); - - .rom.bss : - { - *(.heap.stdlib*) - } > ROM_BSS_RAM - - .ram_rdp.text : - { - __rom_top_4k_start_ = .; - __rdp_text_start__ = .; - KEEP(*(.rdp.ram.text*)) - KEEP(*(.rdp.ram.data*)) - __rdp_text_end__ = .; - . = ALIGN(16); - - } > RDP_RAM - - .xip_image1.text : - { - __flash_boot_text_start__ = .; - - *(.flashboot.text*) - - __flash_boot_text_end__ = .; - - . = ALIGN(16); - } > XIPBOOT - - .xip_image2.text : - { - __flash_text_start__ = .; - - *(.img2_custom_signature*) - *(.text) - *(.text*) - *(.rodata) - *(.rodata*) - *(.debug_trace*) - - /* https://www.embedded.com/building-bare-metal-arm-systems-with-gnu-part-3/ */ - KEEP(*crtbegin.o(.ctors)) - KEEP(*(EXCLUDE_FILE (*ctrend.o) .ctors)) - KEEP(*(SORT(.ctors.*))) - KEEP(*crtend.o(.ctors)) - KEEP(*crtbegin.o(.dtors)) - KEEP(*(EXCLUDE_FILE (*crtend.o) .dtors)) - KEEP(*(SORT(.dtors.*))) - KEEP(*crtend.o(.dtors)) - *(.rodata .rodata.* .gnu.linkonce.r.*) - - /* Add This for C++ support */ - /* ambd_arduino/Arduino_package/hardware/variants/rtl8720dn_bw16/linker_scripts/gcc/rlx8721d_img2_is_arduino.ld */ - . = ALIGN(4); - __preinit_array_start = .; - KEEP(*(.preinit_array)) - __preinit_array_end = .; - . = ALIGN(4); - __init_array_start = .; - KEEP(*(SORT(.init_array.*))) - KEEP(*(.init_array)) - __init_array_end = .; - . = ALIGN(4); - __fini_array_start = .; - KEEP(*(SORT(.fini_array.*))) - KEEP(*(.fini_array)) - __fini_array_end = .; - /*-----------------*/ - - . = ALIGN (4); - __cmd_table_start__ = .; - KEEP(*(.cmd.table.data*)) - __cmd_table_end__ = .; - - /* https://community.silabs.com/s/article/understand-the-gnu-linker-script-of-cortex-m4?language=en_US */ - KEEP(*(.init)) - KEEP(*(.fini)) - *(.init) - *(.fini) - - __flash_text_end__ = .; - - . = ALIGN (16); - } > XIP2 -} - -SECTIONS -{ - /* Bootloader symbol list */ - boot_export_symbol = 0x10002020; -} diff --git a/platform/realtek-ambz2/config/FreeRTOSConfig.h b/platform/realtek-ambz2/config/FreeRTOSConfig.h deleted file mode 100644 index f1ca201..0000000 --- a/platform/realtek-ambz2/config/FreeRTOSConfig.h +++ /dev/null @@ -1,299 +0,0 @@ -/* - * FreeRTOS Kernel V10.2.0 - * 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! - */ - -/****************************************************************************** - See http://www.freertos.org/a00110.html for an explanation of the - definitions contained in this file. -******************************************************************************/ - -#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. - * http://www.freertos.org/a00110.html - *----------------------------------------------------------*/ - -#if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__) -#include -extern uint32_t SystemCoreClock; -#endif - -/* Cortex M33 port configuration. */ -#define configENABLE_MPU 0 - -#ifdef __ARMVFP__ - #define configENABLE_FPU 1 -#else - #define configENABLE_FPU 0 -#endif - -#if defined(CONFIG_BUILD_SECURE) || defined(CONFIG_BUILD_NONSECURE) -#define configENABLE_TRUSTZONE 1 -#else -#define configENABLE_TRUSTZONE 0 -#endif - -/* Constants related to the behaviour or the scheduler. */ -#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 -#define configUSE_PREEMPTION 1 -#define configUSE_TIME_SLICING 1 -#define configTICK_RATE_HZ ( ( uint32_t ) 1000 ) -#define configMAX_PRIORITIES ( 11 ) -#define configIDLE_SHOULD_YIELD 1 -#define configUSE_16_BIT_TICKS 0 /* Only for 8 and 16-bit hardware. */ - -/* Constants that describe the hardware and memory usage. */ -#define configCPU_CLOCK_HZ ( SystemCoreClock ) -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 70 ) //number of double word -#define configMINIMAL_SECURE_STACK_SIZE ( ( unsigned short ) configMINIMAL_STACK_SIZE*4 ) //number of byte -#define configMAX_TASK_NAME_LEN ( 10 ) -#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 160 * 1024 ) ) -#define configAPPLICATION_ALLOCATED_HEAP 0 - -/* Constants that build features in or out. */ -#define configUSE_MUTEXES 1 -#define configUSE_APPLICATION_TASK_TAG 0 -#define configUSE_NEWLIB_REENTRANT 0 -#define configUSE_CO_ROUTINES 0 -#define configUSE_COUNTING_SEMAPHORES 1 -#define configUSE_RECURSIVE_MUTEXES 1 -#define configUSE_QUEUE_SETS 1 -#define configUSE_TASK_NOTIFICATIONS 1 -#define configUSE_TRACE_FACILITY 0 - -/* Constants that define which hook (callback) functions should be used. */ -#define configUSE_IDLE_HOOK 0 -#define configUSE_TICK_HOOK 0 -#define configUSE_MALLOC_FAILED_HOOK 1 -#define secureconfigUSE_MALLOC_FAILED_HOOK 1 - -/* Constants provided for debugging and optimisation assistance. */ -#define configCHECK_FOR_STACK_OVERFLOW 2 - -/* Software timer definitions. */ -#define configUSE_TIMERS 1 -#define configTIMER_TASK_PRIORITY ( configMAX_PRIORITIES - 1 ) -#define configTIMER_QUEUE_LENGTH ( 10 + 32) -#define configTIMER_TASK_STACK_DEPTH ( 512 ) - -/* Set the following definitions to 1 to include the API function, or zero - * to exclude the API function. NOTE: Setting an INCLUDE_ parameter to 0 is - * only necessary if the linker does not automatically remove functions that are - * not referenced anyway. */ -#define INCLUDE_vTaskPrioritySet 1 -#define INCLUDE_uxTaskPriorityGet 1 -#define INCLUDE_vTaskDelete 1 -#define INCLUDE_vTaskSuspend 1 -#define INCLUDE_vTaskDelayUntil 1 -#define INCLUDE_vTaskDelay 1 -#define INCLUDE_pcTaskGetTaskName 1 -#define INCLUDE_uxTaskGetStackHighWaterMark 0 -#define INCLUDE_xTaskGetIdleTaskHandle 0 -#define INCLUDE_eTaskGetState 1 -#define INCLUDE_xTaskResumeFromISR 0 -#define INCLUDE_xTaskGetCurrentTaskHandle 1 -#define INCLUDE_xTaskGetSchedulerState 1 -#define INCLUDE_xSemaphoreGetMutexHolder 1 -#define INCLUDE_xTimerPendFunctionCall 1 - -/* This demo makes use of one or more example stats formatting functions. These - * format the raw data provided by the uxTaskGetSystemState() function in to - * human readable ASCII form. See the notes in the implementation of vTaskList() - * within FreeRTOS/Source/tasks.c for limitations. */ -#define configUSE_STATS_FORMATTING_FUNCTIONS 1 - -/* Dimensions a buffer that can be used by the FreeRTOS+CLI command interpreter. - * See the FreeRTOS+CLI documentation for more information: - * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_CLI/ */ -#define configCOMMAND_INT_MAX_OUTPUT_SIZE 2048 - -/* Interrupt priority configuration follows...................... */ - -/* Use the system definition, if there is one. */ - -#ifdef __NVIC_PRIO_BITS - /* __NVIC_PRIO_BITS will be specified when CMSIS is being used. */ -#if __NVIC_PRIO_BITS != 3 - #error "__NVIC_PRIO_BITS is NOT correct for RTL8710C" -#endif - #define configPRIO_BITS __NVIC_PRIO_BITS -#else - #define configPRIO_BITS 3 /* 8 priority levels */ - //#error "__NVIC_PRIO_BITS must be defined!" -#endif - -/* The lowest interrupt priority that can be used in a call to a "set priority" - * function. */ -#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 7 - -/* The highest interrupt priority that can be used by any interrupt service - * routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT - * CALL INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A - * HIGHER PRIORITY THAN THIS! (higher priorities are lower numeric values). */ -#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 2 - -/* Interrupt priorities used by the kernel port layer itself. These are generic - * to all Cortex-M ports, and do not rely on any particular library functions. */ -#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << ( 8 - configPRIO_BITS ) ) - -/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! - * See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ -#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << ( 8 - configPRIO_BITS ) ) - - -/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS -standard names - or at least those used in the unmodified vector table. */ -#define vPortSVCHandler SVC_Handler -#define xPortPendSVHandler PendSV_Handler -#define xPortSysTickHandler SysTick_Handler - -/* The #ifdef guards against the file being included from IAR assembly files. */ -#if !defined(__IASMARM__) - -/* Constants related to the generation of run time stats. */ -#define configGENERATE_RUN_TIME_STATS 0 -#if configGENERATE_RUN_TIME_STATS -#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() -#define portGET_RUN_TIME_COUNTER_VALUE() xTickCount -#undef configUSE_TRACE_FACILITY -#define configUSE_TRACE_FACILITY 1 -#define portCONFIGURE_STATS_PEROID_VALUE 1000 //unit Ticks -#endif - -#include "diag.h" -#if defined(CONFIG_BUILD_SECURE) && (CONFIG_BUILD_SECURE == 1) -#define configASSERT(x) do { \ - if( (x) == 0 ) { \ - char *pcAssertTask = "ISR"; \ - if(__get_IPSR() == 0) \ - { \ - pcAssertTask = "TSK"; \ - } \ - dbg_printf("\n\r[%s]Assert(" #x ") failed on line %d in file %s\r\n", pcAssertTask, __LINE__, __FILE__); \ - __disable_irq(); for(;;);} \ - } while(0) -#else -#define configASSERT(x) do { \ - if( (x) == 0 ) { \ - char *pcAssertTask = "ISR"; \ - if( (__get_IPSR() == 0) && (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) ) \ - { \ - pcAssertTask = pcTaskGetName( NULL ); \ - } \ - dbg_printf("\n\r[%s]Assert(" #x ") failed on line %d in file %s\r\n", pcAssertTask, __LINE__, __FILE__); \ - taskDISABLE_INTERRUPTS(); for(;;);} \ - } while(0) -#endif -#define configPRINTF( x ) dbg_printf( x ) - -#endif /* __IASMARM__ */ - -/* use the low power tickless mode */ -#define configUSE_TICKLESS_IDLE 0 -#if defined(configUSE_TICKLESS_IDLE) && configUSE_TICKLESS_IDLE -#if !defined(__IASMARM__) || (__IASMARM__ != 1) -#if !defined(CONFIG_BUILD_SECURE) || (CONFIG_BUILD_SECURE == 0) -/* At least n further complete tick periods will pass before the kernel is due to transition an application task out of the Blocked state */ -#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 -/* use realtek customized low power tickless mode */ -#define configUSE_CUSTOMIZED_TICKLESS_IDLE 0 -#if defined(configUSE_CUSTOMIZED_TICKLESS_IDLE) && configUSE_CUSTOMIZED_TICKLESS_IDLE -extern void freertos_pre_sleep_processing(unsigned int *expected_idle_time); -extern void freertos_post_sleep_processing(unsigned int *expected_idle_time); -extern int freertos_ready_to_sleep(void); -extern void freertos_suppress_ticks_and_sleep(unsigned int xExpectedIdleTime); - -/* configEXPECTED_IDLE_TIME_BEFORE_SLEEP is used for native tickless support -configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP is used for realtek customized low power tickless mode -if xExpectedIdleTime < configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP, system will go for native tickless mode -if xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP, system will got for realtek customized tickless mode -In wlan usage, this value is suggested to use value less than 80 milliseconds */ -#define configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP 2 -#if configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP < configEXPECTED_IDLE_TIME_BEFORE_SLEEP - #error configEXPECTED_IDLE_TIME_BEFORE_CUSTOMIZED_SLEEP must not be less than configEXPECTED_IDLE_TIME_BEFORE_SLEEP -#endif - -/* Enable tickless power saving. */ -#define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) do { \ - if (freertos_ready_to_sleep() == FALSE) {\ - x = 0;\ - }\ - } while(0) - -#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) do { \ - freertos_suppress_ticks_and_sleep(xExpectedIdleTime); \ - } while(0) - -/* It's magic trick that let us can use our own sleep function */ -#define configPRE_SLEEP_PROCESSING( x ) do { \ - freertos_pre_sleep_processing((unsigned int *)&x); \ - } while(0) - -#define configPOST_SLEEP_PROCESSING( x ) do { \ - freertos_post_sleep_processing((unsigned int *)&x); \ - } while(0) - -/* It's magic trick that let us can enable/disable tickless dynamically */ -#define traceLOW_POWER_IDLE_BEGIN() do { - -#define traceLOW_POWER_IDLE_END() } while (0) - -/* It's FreeRTOS related feature but it's not included in FreeRTOS design. */ -#define configUSE_WAKELOCK_PMU 1 - -#undef configMINIMAL_STACK_SIZE -#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 192 ) -#endif //#if defined(configUSE_CUSTOMIZED_TICKLESS_IDLE) && configUSE_CUSTOMIZED_TICKLESS_IDLE -#endif // #if !defined(CONFIG_BUILD_SECURE) || (CONFIG_BUILD_SECURE == 0) -#endif // #if !defined(__IASMARM__) || (__IASMARM__ != 1) -#endif // #if defined(configUSE_TICKLESS_IDLE) && configUSE_TICKLESS_IDLE - -/* Add by Realtek to re-arrange the FreeRTOS priority*/ -#define PRIORITIE_OFFSET ( 4 ) - -#if defined(__ICCARM__) -/* Keep below compiler pragma, below 10.2.0 remove them from portmacro.h -which will generate compiler warnings. -*/ -/* Suppress warnings that are generated by the IAR tools, but cannot be fixed in -the source code because to do so would cause other compilers to generate -warnings. */ -#pragma diag_suppress=Pe191 -#pragma diag_suppress=Pa082 -#endif - -#if defined(ENABLE_AMAZON_COMMON) -#include "FreeRTOSConfig_Amazon.h" -#endif -#endif /* FREERTOS_CONFIG_H */ diff --git a/platform/realtek-ambz2/config/autoconf.h b/platform/realtek-ambz2/config/autoconf.h deleted file mode 100644 index ad291e9..0000000 --- a/platform/realtek-ambz2/config/autoconf.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-20. */ - -#pragma once - -#include_next "autoconf.h" diff --git a/platform/realtek-ambz2/config/lwipopts.h b/platform/realtek-ambz2/config/lwipopts.h deleted file mode 100644 index 3ee9dab..0000000 --- a/platform/realtek-ambz2/config/lwipopts.h +++ /dev/null @@ -1,5 +0,0 @@ -/* Copyright (c) Kuba SzczodrzyƄski 2022-07-20. */ - -#pragma once - -#include_next "lwipopts.h" diff --git a/platform/realtek-ambz2/config/platform_opts.h b/platform/realtek-ambz2/config/platform_opts.h deleted file mode 100644 index 66e08cc..0000000 --- a/platform/realtek-ambz2/config/platform_opts.h +++ /dev/null @@ -1,406 +0,0 @@ -/** - ****************************************************************************** - *This file contains general configurations for ameba platform - ****************************************************************************** - */ - -#ifndef __PLATFORM_OPTS_H__ -#define __PLATFORM_OPTS_H__ - -/*For MP mode setting*/ -#define SUPPORT_MP_MODE 1 - -/** - * For AT cmd Log service configurations - */ -#define SUPPORT_LOG_SERVICE 1 -#if SUPPORT_LOG_SERVICE -#define LOG_SERVICE_BUFLEN 100 // can't larger than UART_LOG_CMD_BUFLEN(127) -#define CONFIG_LOG_HISTORY 0 -#if CONFIG_LOG_HISTORY -#define LOG_HISTORY_LEN 5 -#endif -#define SUPPORT_INTERACTIVE_MODE 0 // on/off wifi_interactive_mode -#define CONFIG_LOG_SERVICE_LOCK 0 -#define CONFIG_ATCMD_MP 0 // support MP AT command -#define USE_MODE 1 // for test -#endif - -/** - * For interactive mode configurations, depends on log service - */ -#if defined(SUPPORT_INTERACTIVE_MODE) && SUPPORT_INTERACTIVE_MODE -#define CONFIG_INTERACTIVE_MODE 1 -#define CONFIG_INTERACTIVE_EXT 0 -#else -#define CONFIG_INTERACTIVE_MODE 0 -#define CONFIG_INTERACTIVE_EXT 0 -#endif - -/** - * For FreeRTOS tickless configurations - */ -#define FREERTOS_PMU_TICKLESS_PLL_RESERVED 0 // In sleep mode, 0: close PLL clock, 1: reserve PLL clock -#define FREERTOS_PMU_TICKLESS_SUSPEND_SDRAM 1 // In sleep mode, 1: suspend SDRAM, 0: no act - -/******************************************************************************/ - -/** - * For common flash usage - */ -#define FLASH_BAKEUP_SECTOR (0x3000) -#define FAST_RECONNECT_DATA (0x200000 - 0x1000) -#define BT_FTL_PHY_ADDR0 (0x200000 - 0x2000) -#define BT_FTL_PHY_ADDR1 (0x200000 - 0x3000) -#define BT_FTL_BKUP_ADDR (0x200000 - 0x4000) -#define UART_SETTING_SECTOR (0x200000 - 0x5000) -#define DCT_BEGIN_ADDR \ - (0x200000 - 0x29000) /*!< DCT begin address of flash, ex: 0x200000 = 2M, the default size of DCT is 24K; ; if \ - backup enabled, the size is 48k; if wear leveling enabled, the size is 144k*/ -#define FLASH_APP_BASE \ - (0x200000 - 0xA9000 \ - ) /*!< FATFS begin address, default size used is 512KB (can be adjusted based on user requirement)*/ -#define BT_WHITELIST_BASE_1 (0x200000 - 0xA000) -#define BT_WHITELIST_PAGE_SIZE (0x1000) -#define BT_WHITELIST_BASE_2 (BT_WHITELIST_BASE_1 + BT_WHITELIST_PAGE_SIZE) -/** - * For Wlan configurations - */ -#define CONFIG_WLAN 1 -#if CONFIG_WLAN -#define CONFIG_LWIP_LAYER 1 -#define CONFIG_INIT_NET 1 // init lwip layer when start up -#define CONFIG_WIFI_IND_USE_THREAD 0 // wifi indicate worker thread -#define CONFIG_ENABLE_AP_POLLING_CLIENT_ALIVE 0 // on or off AP POLLING CLIENT - -// on/off relative commands in log service -#define CONFIG_SSL_CLIENT 0 -#define CONFIG_OTA_UPDATE 1 -#define CONFIG_BSD_TCP 0 // NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size -#define CONFIG_AIRKISS 0 // on or off tencent airkiss -#define CONFIG_UART_SOCKET 0 -#define CONFIG_JD_SMART 0 // on or off for jdsmart -#define CONFIG_JOYLINK 0 // on or off for jdsmart2.0 -#define CONFIG_QQ_LINK 0 // on or off for qqlink -#define CONFIG_AIRKISS_CLOUD 0 // on or off for weixin hardware cloud -#define CONFIG_UART_YMODEM 0 // support uart ymodem upgrade or not -#define CONFIG_TRANSPORT 0 // on or off the at command for transport socket -#define CONFIG_ALINK 0 // on or off for alibaba alink -#define CONFIG_MIIO 0 // on or off for alibaba alink -#define CONFIG_RIC 0 // on or off for RICloud -#define CONFIG_LINKKIT_AWSS 0 // on or off for ali feiyan cloud - -/* For WPS and P2P */ -#define CONFIG_ENABLE_WPS 0 -#define CONFIG_ENABLE_P2P 0 -#if CONFIG_ENABLE_WPS -#define CONFIG_ENABLE_WPS_DISCOVERY 1 -#endif -#if CONFIG_ENABLE_P2P -#define CONFIG_ENABLE_WPS_AP 1 -#undef CONFIG_WIFI_IND_USE_THREAD -#define CONFIG_WIFI_IND_USE_THREAD 1 -#endif -#if (CONFIG_ENABLE_P2P && ((CONFIG_ENABLE_WPS_AP == 0) || (CONFIG_ENABLE_WPS == 0))) -#error "If CONFIG_ENABLE_P2P, need to define CONFIG_ENABLE_WPS_AP 1" -#endif - -/* For Simple Link */ -#define CONFIG_INCLUDE_SIMPLE_CONFIG 1 -#define CONFIG_INCLUDE_DPP_CONFIG 0 -/*For fast reconnection*/ -#ifdef PLATFORM_OHOS -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#else -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 1 -#endif -#if CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_FAST_DHCP 1 -#else -#define CONFIG_FAST_DHCP 0 -#endif - -/*For wowlan service settings*/ -#define CONFIG_WOWLAN_SERVICE 0 - -#define CONFIG_GAGENT 0 -/*Disable CONFIG_EXAMPLE_WLAN_FAST_CONNECT when CONFIG_GAGENT is enabled,because - reconnect to previous AP is not suitable when re-configuration. -*/ -#if CONFIG_GAGENT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - -#endif // end of #if CONFIG_WLAN -/*******************************************************************************/ - -/* For SSL/TLS */ -#define CONFIG_USE_POLARSSL 0 // polarssl is no longer suppported for AmebaZ2 -#define CONFIG_USE_MBEDTLS 1 -#if ((CONFIG_USE_POLARSSL == 0) && (CONFIG_USE_MBEDTLS == 0)) || \ - ((CONFIG_USE_POLARSSL == 1) && (CONFIG_USE_MBEDTLS == 1)) -#undef CONFIG_USE_POLARSSL -#define CONFIG_USE_POLARSSL 1 -#undef CONFIG_USE_MBEDTLS -#define CONFIG_USE_MBEDTLS 0 -#endif -#define CONFIG_SSL_CLIENT_PRIVATE_IN_TZ 1 - -/* For LWIP configuration */ -#define CONFIG_LWIP_DHCP_COARSE_TIMER 60 - -/*Enable CONFIG_LWIP_DHCP_FINE_TIMEOUT if lease time is less than or equal to CONFIG_LWIP_DHCP_COARSE_TIMER - * replace dhcp_coarse_tmr with dhcp_fine_tmr to manage and check for lease timeout - */ -#define CONFIG_LWIP_DHCP_FINE_TIMEOUT 0 - -/** - * For Ethernet configurations - */ -#define CONFIG_ETHERNET 0 -#if CONFIG_ETHERNET - -#define CONFIG_LWIP_LAYER 1 -#define CONFIG_INIT_NET 1 // init lwip layer when start up - -// on/off relative commands in log service -#define CONFIG_SSL_CLIENT 0 -#define CONFIG_BSD_TCP 0 // NOTE : Enable CONFIG_BSD_TCP will increase about 11KB code size - -#endif - -/* For Azure Examples */ -#define CONFIG_USE_AZURE_EMBEDDED_C 1 -#if CONFIG_USE_AZURE_EMBEDDED_C -/* For Azure embedded iot examples*/ -#define CONFIG_EXAMPLE_AZURE 0 -#if CONFIG_EXAMPLE_AZURE -#undef WAIT_FOR_ACK -#define WAIT_FOR_ACK -#endif -#else -/* For Azure iot hub telemetry example*/ -#define CONFIG_EXAMPLE_AZURE_IOTHUB_TELEMETRY 0 -/* For Azure iot hub x509 example*/ -#define CONFIG_EXAMPLE_AZURE_IOTHUB_X509 0 -#endif - -/* for CoAP example*/ -#define CONFIG_EXAMPLE_COAP 0 - -/* for lib CoAP example*/ -#define CONFIG_EXAMPLE_COAP_SERVER 0 -#define CONFIG_EXAMPLE_COAP_CLIENT 0 - -/* For WIFI GET BEACON FRAME example */ -#define CONFIG_EXAMPLE_GET_BEACON_FRAME 0 - -/* For WIFI MAC MONITOR example */ -#define CONFIG_EXAMPLE_WIFI_MAC_MONITOR 0 - -/* For HTTP CLIENT example */ -#define CONFIG_EXAMPLE_HTTP_CLIENT 0 - -/* For MQTT example */ -#define CONFIG_EXAMPLE_MQTT 0 - -/* For multicast example */ -#define CONFIG_EXAMPLE_MCAST 0 - -/* For XML example */ -#define CONFIG_EXAMPLE_XML 0 - -/* For JSON example */ -#define CONFIG_EXAMPLE_CJSON 0 - -/* For socket select example */ -#define CONFIG_EXAMPLE_SOCKET_SELECT 0 - -/* For socket nonblocking connect example */ -#define CONFIG_EXAMPLE_NONBLOCK_CONNECT 0 - -/* For socket TCP bidirectional transmission example */ -#define CONFIG_EXAMPLE_SOCKET_TCP_TRX 0 - -/* For ssl download example */ -#define CONFIG_EXAMPLE_SSL_DOWNLOAD 0 - -/* For http download example */ -#define CONFIG_EXAMPLE_HTTP_DOWNLOAD 0 - -/* For httpc example */ -#define CONFIG_EXAMPLE_HTTPC 0 - -/* For Amazon ffs example */ -#define CONFIG_EXAMPLE_FFS 0 -#if CONFIG_EXAMPLE_FFS -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#undef CONFIG_FAST_DHCP -#define CONFIG_FAST_DHCP 0 -#endif - -/* For httpd example */ -#define CONFIG_EXAMPLE_HTTPD 0 - -/* For tcp keepalive example */ -#define CONFIG_EXAMPLE_TCP_KEEPALIVE 0 - -/* For sntp show time example */ -#define CONFIG_EXAMPLE_SNTP_SHOWTIME 0 - -/* For websocket client example */ -#define CONFIG_EXAMPLE_WEBSOCKET_CLIENT 0 - -/* For DCT example*/ -#define CONFIG_EXAMPLE_DCT 0 - -/****************** For EAP method example *******************/ -#define CONFIG_EXAMPLE_EAP 0 - -// on/off specified eap method -#define CONFIG_ENABLE_PEAP 0 -#define CONFIG_ENABLE_TLS 0 -#define CONFIG_ENABLE_TTLS 0 - -// optional feature: whether to verify the cert of radius server -#define ENABLE_EAP_SSL_VERIFY_SERVER 0 - -#if CONFIG_ENABLE_PEAP || CONFIG_ENABLE_TLS || CONFIG_ENABLE_TTLS -#define CONFIG_ENABLE_EAP -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#undef CONFIG_FAST_DHCP -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#define CONFIG_FAST_DHCP 0 -#endif - -#if CONFIG_ENABLE_TLS -#define ENABLE_EAP_SSL_VERIFY_CLIENT 1 -#else -#define ENABLE_EAP_SSL_VERIFY_CLIENT 0 -#endif -/******************End of EAP configurations*******************/ - -/* For FATFS example*/ -#define CONFIG_EXAMPLE_FATFS 0 -#if CONFIG_EXAMPLE_FATFS -#define CONFIG_FATFS_EN 1 -#if CONFIG_FATFS_EN -// fatfs version -#define FATFS_R_10C -// fatfs disk interface -#define FATFS_DISK_USB 0 -#define FATFS_DISK_SD 0 -#define FATFS_DISK_FLASH 1 -#endif -#endif - -/* For iNIC host example*/ -#ifdef CONFIG_INIC_GSPI_HOST // this flag is defined in IAR project -#define CONFIG_EXAMPLE_INIC_GSPI_HOST 1 -#if CONFIG_EXAMPLE_INIC_GSPI_HOST - -#define CONFIG_INIC_HOST 1 - -#undef CONFIG_WLAN -#define CONFIG_WLAN 0 -#undef CONFIG_INCLUDE_SIMPLE_CONFIG -#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#undef CONFIG_LWIP_LAYER -#define CONFIG_LWIP_LAYER 1 -#undef CONFIG_BSD_TCP -#define CONFIG_BSD_TCP 1 - -#endif -#endif - -/* For wifi scenarios example (Wi-Fi, WPS enrollee, P2P GO) */ -// also need to enable WPS and P2P -#define CONFIG_EXAMPLE_WLAN_SCENARIO 0 - -/* For broadcast example */ -#define CONFIG_EXAMPLE_BCAST 0 - -/* For high-load memory use case memory usage */ -#define CONFIG_EXAMPLE_HIGH_LOAD_MEMORY_USE 0 - -/* For rarp example */ -#define CONFIG_EXAMPLE_RARP 0 - -/* For ssl server example */ -#define CONFIG_EXAMPLE_SSL_SERVER 0 - -/*For secure boot example */ -#define CONFIG_EXAMPLE_SECURE_BOOT 0 - -/*For secure storage example */ -#define CONFIG_EXAMPLE_SECURE_STORAGE 0 - -/* For ota update http example */ -#define CONFIG_EXAMPLE_OTA_HTTP 0 - -/*For wifi roaming example*/ -#define CONFIG_EXAMPLE_WIFI_ROAMING 0 - -/* for tickless roaming */ -#define CONFIG_EXAMPLE_TICKLESS_WIFI_ROAMING 0 - -/*For ipv6 example*/ -#define CONFIG_EXAMPLE_IPV6 0 - -#if CONFIG_ENABLE_WPS -#define WPS_CONNECT_RETRY_COUNT 4 -#define WPS_CONNECT_RETRY_INTERVAL 5000 // in ms -#endif - -#define AUTO_RECONNECT_COUNT 8 -#define AUTO_RECONNECT_INTERVAL 5 // in sec - -/*For trust zone example */ -#define CONFIG_EXAMPLE_TRUST_ZONE 0 - -/* For Amazon FreeRTOS SDK example */ -#define CONFIG_EXAMPLE_AMAZON_FREERTOS 0 - -#define CONFIG_EXAMPLE_AMAZON_AFQP_TESTS 0 - -#if (defined(CONFIG_EXAMPLE_AMAZON_FREERTOS) && CONFIG_EXAMPLE_AMAZON_FREERTOS) || \ - (defined(CONFIG_EXAMPLE_AMAZON_AFQP_TESTS) && CONFIG_EXAMPLE_AMAZON_AFQP_TESTS) -#undef CONFIG_INCLUDE_SIMPLE_CONFIG -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#undef CONFIG_FAST_DHCP -#define CONFIG_INCLUDE_SIMPLE_CONFIG 0 -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#define CONFIG_FAST_DHCP 0 -#if defined(CONFIG_BUILD_SECURE) -#define ENABLE_AMAZON_COMMON -#endif -#if defined(CONFIG_BUILD_NONSECURE) && (CONFIG_SSL_CLIENT_PRIVATE_IN_TZ == 0) -#undef SUPPORT_LOG_SERVICE -#define SUPPORT_LOG_SERVICE 0 -#endif -#endif - -/* For UART Module AT command example */ -#define CONFIG_EXAMPLE_UART_ATCMD 0 -#if (defined(CONFIG_EXAMPLE_UART_ATCMD) && CONFIG_EXAMPLE_UART_ATCMD) -#define UART_SETTING_BACKUP_SECTOR (FLASH_BAKEUP_SECTOR) -#undef CONFIG_OTA_UPDATE -#define CONFIG_OTA_UPDATE 1 -#undef CONFIG_TRANSPORT -#define CONFIG_TRANSPORT 1 -#undef LOG_SERVICE_BUFLEN -#define LOG_SERVICE_BUFLEN 1600 -#undef CONFIG_LOG_SERVICE_LOCK -#define CONFIG_LOG_SERVICE_LOCK 1 -#undef CONFIG_EXAMPLE_WLAN_FAST_CONNECT -#define CONFIG_EXAMPLE_WLAN_FAST_CONNECT 0 -#endif - -#if (SUPPORT_MP_MODE && CONFIG_MIIO) -#define CONFIG_MIIO_MP 0 // miio mp test and rw private data -#endif - -#endif diff --git a/platform/realtek-ambz2/config/platform_opts_bt.h b/platform/realtek-ambz2/config/platform_opts_bt.h deleted file mode 100644 index 06d2278..0000000 --- a/platform/realtek-ambz2/config/platform_opts_bt.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef __PLATFORM_OPTS_BT_H__ -#define __PLATFORM_OPTS_BT_H__ - -#define CONFIG_BT 0 - -#if CONFIG_BT -#define CONFIG_FTL_ENABLED -#define CONFIG_BT_CONFIG 0 -#define CONFIG_BT_AIRSYNC_CONFIG 0 -#define CONFIG_BT_PERIPHERAL 0 -#define CONFIG_BT_CENTRAL 0 -#define CONFIG_BT_SCATTERNET 0 -#define CONFIG_BT_BEACON 0 -#define CONFIG_BT_FUZZ_TEST 0 -#define CONFIG_BT_OTA_CENTRAL_CLIENT 0 -#define CONFIG_BT_DATATRANS 0 -#define CONFIG_BT_MESH_PROVISIONER 0 -#define CONFIG_BT_MESH_DEVICE 0 -#define CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE 0 -#define CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE 0 -#define CONFIG_BT_MESH_CENTRAL 0 -#define CONFIG_BT_MESH_PERIPHERAL 0 -#define CONFIG_BT_MESH_SCATTERNET 0 -#define CONFIG_BT_MESH_PROVISIONER_RTK_DEMO 0 -#define CONFIG_BT_MESH_DEVICE_RTK_DEMO 0 -#define CONFIG_BT_MESH_TEST 0 -#define CONFIG_BT_ONLY_WITHOUT_WLAN 0 -#endif // CONFIG_BT - -#if defined CONFIG_BT_SCATTERNET && CONFIG_BT_SCATTERNET -#undef CONFIG_BT_PERIPHERAL -#undef CONFIG_BT_CENTRAL -#define CONFIG_BT_PERIPHERAL 1 -#define CONFIG_BT_CENTRAL 1 -#endif - -#if defined CONFIG_BT_CENTRAL && CONFIG_BT_CENTRAL -#define CONFIG_BT_USER_COMMAND 0 -#define CONFIG_BT_WHITE_LIST_TO_FLASH 0 -#endif - -#if defined CONFIG_BT_OTA_CENTRAL_CLIENT && CONFIG_BT_OTA_CENTRAL_CLIENT -#define CONFIG_BT_OTA_CENTRAL_CLIENT_SPLIT 0 -#endif - -#if ((defined CONFIG_BT_MESH_PROVISIONER && CONFIG_BT_MESH_PROVISIONER) || (defined CONFIG_BT_MESH_DEVICE && CONFIG_BT_MESH_DEVICE) || (defined CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE && CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE) || (defined CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE && CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE)) -#define CONFIG_BT_MESH_USER_API 1 -#define CONFIG_BT_MESH_IDLE_CHECK 0 -#endif - -#if defined CONFIG_BT_MESH_PROVISIONER_RTK_DEMO && CONFIG_BT_MESH_PROVISIONER_RTK_DEMO -#undef CONFIG_BT_CONFIG -#define CONFIG_BT_CONFIG 1 -#endif - -#if ((defined CONFIG_BT_MESH_PROVISIONER && CONFIG_BT_MESH_PROVISIONER) && (defined CONFIG_BT_MESH_DEVICE && CONFIG_BT_MESH_DEVICE)) -#error "CONFIG_BT_MESH_PROVISIONER & CONFIG_BT_MESH_DEVICE can not open at the same time" -#endif - -#if ((defined CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE && CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE) && (defined CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE && CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE)) -#error \ - "CONFIG_BT_MESH_PROVISIONER_MULTIPLE_PROFILE & CONFIG_BT_MESH_DEVICE_MULTIPLE_PROFILE can not open at the same time" -#endif - -#if (((defined CONFIG_BT_MESH_CENTRAL && CONFIG_BT_MESH_CENTRAL) && (defined CONFIG_BT_MESH_PERIPHERAL && CONFIG_BT_MESH_PERIPHERAL)) || ((defined CONFIG_BT_MESH_CENTRAL && CONFIG_BT_MESH_CENTRAL) && (defined CONFIG_BT_MESH_SCATTERNET && CONFIG_BT_MESH_SCATTERNET)) || ((defined CONFIG_BT_MESH_PERIPHERAL && CONFIG_BT_MESH_PERIPHERAL) && (defined CONFIG_BT_MESH_SCATTERNET && CONFIG_BT_MESH_SCATTERNET)) || ((defined CONFIG_BT_MESH_CENTRAL && CONFIG_BT_MESH_CENTRAL) && (defined CONFIG_BT_MESH_PERIPHERAL && CONFIG_BT_MESH_PERIPHERAL) && (defined CONFIG_BT_MESH_SCATTERNET && CONFIG_BT_MESH_SCATTERNET))) -#error "Only one of CONFIG_BT_MESH_CENTRAL, CONFIG_BT_MESH_PERIPHERAL and CONFIG_BT_MESH_SCATTERNET can be enabled" -#endif - -#endif // __PLATFORM_OPTS_BT_H__