diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9532a662f..0f735b1f5 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,6 +4,7 @@ stages: - host_test - unit_test - integration_test + - check - deploy variables: @@ -68,6 +69,12 @@ before_script: # fetch the submodules (& if necessary re-fetch repo) from gitlab - time ./tools/ci/get-full-sources.sh +# used for check scripts which we want to run unconditionally +.do_nothing_before_no_filter: + before_script: &do_nothing_before_no_filter + - *git_clean_stale_submodules + +# used for everything else where we want to do no prep, except for bot filter .do_nothing_before: before_script: &do_nothing_before - *git_clean_stale_submodules @@ -534,30 +541,22 @@ check_doc_links: - make linkcheck check_line_endings: - stage: deploy + stage: check image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG tags: - build - except: - - master - - /^release\/v/ - - /^v\d+\.\d+(\.\d+)?($|-)/ dependencies: [] - before_script: *do_nothing_before + before_script: *do_nothing_before_no_filter script: - tools/ci/check-line-endings.sh ${IDF_PATH} check_commit_msg: - stage: deploy + stage: check image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG tags: - build - except: - - master - - /^release\/v/ - - /^v\d+\.\d+(\.\d+)?($|-)/ dependencies: [] - before_script: *do_nothing_before + before_script: *do_nothing_before_no_filter script: - git status - git log -n10 --oneline @@ -565,16 +564,12 @@ check_commit_msg: - 'git log --pretty=%s master.. -- | grep "^WIP: " && exit 1 || exit 0' check_permissions: - stage: deploy + stage: check image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG tags: - build - except: - - master - - /^release\/v/ - - /^v\d+\.\d+(\.\d+)?($|-)/ dependencies: [] - before_script: *do_nothing_before + before_script: *do_nothing_before_no_filter script: - tools/ci/check-executable.sh @@ -593,18 +588,14 @@ check_examples_cmake_make: - tools/ci/check_examples_cmake_make.sh check_submodule_sync: - stage: deploy + stage: check image: $CI_DOCKER_REGISTRY/esp32-ci-env$BOT_DOCKER_IMAGE_TAG tags: - build - except: - - master - - /^release\/v/ - - /^v\d+\.\d+(\.\d+)?($|-)/ dependencies: [] variables: GIT_STRATEGY: clone - before_script: *do_nothing_before + before_script: *do_nothing_before_no_filter script: # check if all submodules are correctly synced to public repostory - git submodule update --init --recursive diff --git a/components/app_update/Makefile.projbuild b/components/app_update/Makefile.projbuild index a21e047b8..f4cf1d055 100644 --- a/components/app_update/Makefile.projbuild +++ b/components/app_update/Makefile.projbuild @@ -49,7 +49,7 @@ $(BLANK_OTA_DATA_FILE): partition_table_get_info blank_ota_data: $(BLANK_OTA_DATA_FILE) -erase_ota: partition_table_get_info check_python_dependencies +erase_ota: partition_table_get_info | check_python_dependencies @echo $(if $(OTA_DATA_OFFSET), "Erase ota_data [addr=$(OTA_DATA_OFFSET) size=$(OTA_DATA_SIZE)] ...", $(error "ERROR: Partition table does not have ota_data partition.")) $(ESPTOOLPY_SERIAL) erase_region $(OTA_DATA_OFFSET) $(OTA_DATA_SIZE) diff --git a/components/app_update/esp_ota_ops.c b/components/app_update/esp_ota_ops.c index 7a7c9ae64..5e4dcb424 100644 --- a/components/app_update/esp_ota_ops.c +++ b/components/app_update/esp_ota_ops.c @@ -377,7 +377,7 @@ esp_err_t esp_ota_set_boot_partition(const esp_partition_t *partition) return ESP_ERR_OTA_VALIDATE_FAILED; } -#ifdef CONFIG_SECURE_BOOT_ENABLED +#ifdef CONFIG_SECURE_SIGNED_ON_UPDATE esp_err_t ret = esp_secure_boot_verify_signature(partition->address, data.image_len); if (ret != ESP_OK) { return ESP_ERR_OTA_VALIDATE_FAILED; diff --git a/components/bootloader/Kconfig.projbuild b/components/bootloader/Kconfig.projbuild index 75dae508a..f0188f19a 100644 --- a/components/bootloader/Kconfig.projbuild +++ b/components/bootloader/Kconfig.projbuild @@ -127,14 +127,96 @@ config BOOTLOADER_HOLD_TIME_GPIO The GPIO must be held low continuously for this period of time after reset before a factory reset or test partition boot (as applicable) is performed. +config BOOTLOADER_WDT_ENABLE + bool "Use RTC watchdog in start code" + default y + help + Tracks the execution time of startup code. + If the execution time is exceeded, the RTC_WDT will restart system. + It is also useful to prevent a lock up in start code caused by an unstable power source. + NOTE: Tracks the execution time starts from the bootloader code - re-set timeout, while selecting the source for slow_clk - and ends calling app_main. + Re-set timeout is needed due to WDT uses a SLOW_CLK clock source. After changing a frequency slow_clk a time of WDT needs to re-set for new frequency. + slow_clk depends on ESP32_RTC_CLOCK_SOURCE (INTERNAL_RC or EXTERNAL_CRYSTAL). + +config BOOTLOADER_WDT_DISABLE_IN_USER_CODE + bool "Allows RTC watchdog disable in user code" + depends on BOOTLOADER_WDT_ENABLE + default n + help + If it is set, the client must itself reset or disable rtc_wdt in their code (app_main()). + Otherwise rtc_wdt will be disabled before calling app_main function. + Use function rtc_wdt_feed() for resetting counter of rtc_wdt. + Use function rtc_wdt_disable() for disabling rtc_wdt. + +config BOOTLOADER_WDT_TIME_MS + int "Timeout for RTC watchdog (ms)" + depends on BOOTLOADER_WDT_ENABLE + default 9000 + range 0 120000 + help + Verify that this parameter is correct and more then the execution time. + Pay attention to options such as reset to factory, trigger test partition and encryption on boot + - these options can increase the execution time. + Note: RTC_WDT will reset while encryption operations will be performed. + endmenu # Bootloader menu "Security features" +# These three are the actual options to check in code, +# selected by the displayed options +config SECURE_SIGNED_ON_BOOT + bool + default y + depends on SECURE_BOOT_ENABLED || SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT + +config SECURE_SIGNED_ON_UPDATE + bool + default y + depends on SECURE_BOOT_ENABLED || SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT + +config SECURE_SIGNED_APPS + bool + default y + depends on SECURE_SIGNED_ON_BOOT || SECURE_SIGNED_ON_UPDATE + + +config SECURE_SIGNED_APPS_NO_SECURE_BOOT + bool "Require signed app images" + default n + depends on !SECURE_BOOT_ENABLED + help + Require apps to be signed to verify their integrity. + + This option uses the same app signature scheme as hardware secure boot, but unlike hardware secure boot it does not prevent the bootloader from being physically updated. This means that the device can be secured against remote network access, but not physical access. Compared to using hardware Secure Boot this option is much simpler to implement. + +config SECURE_SIGNED_ON_BOOT_NO_SECURE_BOOT + bool "Bootloader verifies app signatures" + default n + depends on SECURE_SIGNED_APPS_NO_SECURE_BOOT + help + If this option is set, the bootloader will be compiled with code to verify that an app is signed before booting it. + + If hardware secure boot is enabled, this option is always enabled and cannot be disabled. + If hardware secure boot is not enabled, this option doesn't add significant security by itself so most users will want to leave it disabled. + +config SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT + bool "Verify app signature on update" + default y + depends on SECURE_SIGNED_APPS_NO_SECURE_BOOT + help + If this option is set, any OTA updated apps will have the signature verified before being considered valid. + + When enabled, the signature is automatically checked whenever the esp_ota_ops.h APIs are used for OTA updates, + or esp_image_format.h APIs are used to verify apps. + + If hardware secure boot is enabled, this option is always enabled and cannot be disabled. + If hardware secure boot is not enabled, this option still adds significant security against network-based attackers by preventing spoofing of OTA updates. + config SECURE_BOOT_ENABLED - bool "Enable secure boot in bootloader (READ DOCS FIRST)" - default N + bool "Enable hardware secure boot in bootloader (READ DOCS FIRST)" + default n help Build a bootloader which enables secure boot on first boot. @@ -169,12 +251,12 @@ endchoice config SECURE_BOOT_BUILD_SIGNED_BINARIES bool "Sign binaries during build" - depends on SECURE_BOOT_ENABLED + depends on SECURE_SIGNED_APPS default y help - Once secure boot is enabled, bootloader will only boot if partition table and app image are signed. + Once secure boot or signed app requirement is enabled, app images are required to be signed. - If enabled, these binary files are signed as part of the build process. The file named in "Secure boot private signing key" will be used to sign the image. + If enabled (default), these binary files are signed as part of the build process. The file named in "Secure boot private signing key" will be used to sign the image. If disabled, unsigned app/partition data will be built. They must be signed manually using espsecure.py (for example, on a remote signing server.) @@ -183,7 +265,7 @@ config SECURE_BOOT_SIGNING_KEY depends on SECURE_BOOT_BUILD_SIGNED_BINARIES default secure_boot_signing_key.pem help - Path to the key file used to sign partition tables and app images for secure boot. Once secure boot is enabled, bootloader will only boot if partition table and app image are signed. + Path to the key file used to sign app images. Key file is an ECDSA private key (NIST256p curve) in PEM format. @@ -196,11 +278,11 @@ config SECURE_BOOT_SIGNING_KEY config SECURE_BOOT_VERIFICATION_KEY string "Secure boot public signature verification key" - depends on SECURE_BOOT_ENABLED && !SECURE_BOOT_BUILD_SIGNED_BINARIES + depends on SECURE_SIGNED_APPS && !SECURE_BOOT_BUILD_SIGNED_BINARIES default signature_verification_key.bin help - Path to a public key file used to verify signed images. This key is compiled into the bootloader, - and may also be used to verify signatures on OTA images after download. + Path to a public key file used to verify signed images. This key is compiled into the bootloader and/or app, + to verify app images. Key file is in raw binary format, and can be extracted from a PEM formatted private key using the espsecure.py diff --git a/components/bootloader/Makefile.projbuild b/components/bootloader/Makefile.projbuild index d8fa2a5ca..ba8855c27 100644 --- a/components/bootloader/Makefile.projbuild +++ b/components/bootloader/Makefile.projbuild @@ -56,7 +56,7 @@ bootloader: $(BOOTLOADER_BIN) | check_python_dependencies ESPTOOL_ALL_FLASH_ARGS += $(BOOTLOADER_OFFSET) $(BOOTLOADER_BIN) -bootloader-flash: $(BOOTLOADER_BIN) $(call prereq_if_explicit,erase_flash) check_python_dependencies +bootloader-flash: $(BOOTLOADER_BIN) $(call prereq_if_explicit,erase_flash) | check_python_dependencies $(ESPTOOLPY_WRITE_FLASH) 0x1000 $^ else ifdef CONFIG_SECURE_BOOTLOADER_ONE_TIME_FLASH diff --git a/components/bootloader/subproject/main/esp32.bootloader.ld b/components/bootloader/subproject/main/esp32.bootloader.ld index d44295115..1a182acb5 100644 --- a/components/bootloader/subproject/main/esp32.bootloader.ld +++ b/components/bootloader/subproject/main/esp32.bootloader.ld @@ -36,11 +36,12 @@ SECTIONS { . = ALIGN (16); _stext = .; - _text_start = ABSOLUTE(.); + _loader_text_start = ABSOLUTE(.); *(.stub .gnu.warning .gnu.linkonce.literal.* .gnu.linkonce.t.*.literal .gnu.linkonce.t.*) *(.iram1 .iram1.*) /* catch stray IRAM_ATTR */ *liblog.a:(.literal .text .literal.* .text.*) *libgcc.a:(.literal .text .literal.* .text.*) + *libbootloader_support.a:bootloader_common.*(.literal .text .literal.* .text.*) *libbootloader_support.a:bootloader_flash.*(.literal .text .literal.* .text.*) *libbootloader_support.a:bootloader_random.*(.literal .text .literal.* .text.*) *libbootloader_support.a:bootloader_utility.*(.literal .text .literal.* .text.*) @@ -56,7 +57,7 @@ SECTIONS *(.fini.literal) *(.fini) *(.gnu.version) - _text_end = ABSOLUTE(.); + _loader_text_end = ABSOLUTE(.); _etext = .; } > iram_loader_seg diff --git a/components/bootloader_support/component.mk b/components/bootloader_support/component.mk index 8907c31ae..0b464bdb1 100644 --- a/components/bootloader_support/component.mk +++ b/components/bootloader_support/component.mk @@ -12,7 +12,7 @@ COMPONENT_SRCDIRS := src # # Secure boot signing key support # -ifdef CONFIG_SECURE_BOOT_ENABLED +ifdef CONFIG_SECURE_SIGNED_APPS # this path is created relative to the component build directory SECURE_BOOT_VERIFICATION_KEY := $(abspath signature_verification_key.bin) diff --git a/components/bootloader_support/include_bootloader/bootloader_random.h b/components/bootloader_support/include/bootloader_random.h similarity index 100% rename from components/bootloader_support/include_bootloader/bootloader_random.h rename to components/bootloader_support/include/bootloader_random.h diff --git a/components/bootloader_support/include/esp_flash_encrypt.h b/components/bootloader_support/include/esp_flash_encrypt.h index 45fce4465..59eca33b2 100644 --- a/components/bootloader_support/include/esp_flash_encrypt.h +++ b/components/bootloader_support/include/esp_flash_encrypt.h @@ -85,6 +85,8 @@ static inline /** @cond */ IRAM_ATTR /** @endcond */ bool esp_flash_encryption_e * @note Take care not to power off the device while this function * is running, or the partition currently being encrypted will be lost. * + * @note RTC_WDT will reset while encryption operations will be performed (if RTC_WDT is configured). + * * @return ESP_OK if all operations succeeded, ESP_ERR_INVALID_STATE * if a fatal error occured during encryption of all partitions. */ @@ -93,6 +95,7 @@ esp_err_t esp_flash_encrypt_check_and_update(void); /** @brief Encrypt-in-place a block of flash sectors * + * @note This function resets RTC_WDT between operations with sectors. * @param src_addr Source offset in flash. Should be multiple of 4096 bytes. * @param data_length Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. * diff --git a/components/bootloader_support/include/esp_secure_boot.h b/components/bootloader_support/include/esp_secure_boot.h index 6aa4b6285..370bdd363 100644 --- a/components/bootloader_support/include/esp_secure_boot.h +++ b/components/bootloader_support/include/esp_secure_boot.h @@ -17,6 +17,14 @@ #include #include "soc/efuse_reg.h" +#include "sdkconfig.h" + +#ifdef CONFIG_SECURE_BOOT_ENABLED +#if !defined(CONFIG_SECURE_SIGNED_ON_BOOT) || !defined(CONFIG_SECURE_SIGNED_ON_UPDATE) || !defined(CONFIG_SECURE_SIGNED_APPS) +#error "internal sdkconfig error, secure boot should always enable all signature options" +#endif +#endif + #ifdef __cplusplus extern "C" { #endif diff --git a/components/bootloader_support/include_bootloader/bootloader_flash.h b/components/bootloader_support/include_bootloader/bootloader_flash.h index 763136e03..85a482781 100644 --- a/components/bootloader_support/include_bootloader/bootloader_flash.h +++ b/components/bootloader_support/include_bootloader/bootloader_flash.h @@ -21,6 +21,7 @@ #include "esp_spi_flash.h" #define FLASH_SECTOR_SIZE 0x1000 +#define FLASH_BLOCK_SIZE 0x10000 /* Provide a Flash API for bootloader_support code, that can be used from bootloader or app code. @@ -100,4 +101,14 @@ esp_err_t bootloader_flash_write(size_t dest_addr, void *src, size_t size, bool */ esp_err_t bootloader_flash_erase_sector(size_t sector); +/** + * @brief Erase the Flash range. + * + * @param start_addr start address of flash offset + * @param size sector aligned size to be erased + * + * @return esp_err_t + */ +esp_err_t bootloader_flash_erase_range(uint32_t start_addr, uint32_t size); + #endif diff --git a/components/bootloader_support/src/bootloader_common.c b/components/bootloader_support/src/bootloader_common.c index a17492601..479407845 100644 --- a/components/bootloader_support/src/bootloader_common.c +++ b/components/bootloader_support/src/bootloader_common.c @@ -106,8 +106,8 @@ bool bootloader_common_erase_part_type_data(const char *list_erase, bool ota_dat partitions = bootloader_mmap(ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN); if (!partitions) { - ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN); - return false; + ESP_LOGE(TAG, "bootloader_mmap(0x%x, 0x%x) failed", ESP_PARTITION_TABLE_OFFSET, ESP_PARTITION_TABLE_MAX_LEN); + return false; } ESP_LOGD(TAG, "mapped partition table 0x%x at 0x%x", ESP_PARTITION_TABLE_OFFSET, (intptr_t)partitions); @@ -128,7 +128,7 @@ bool bootloader_common_erase_part_type_data(const char *list_erase, bool ota_dat // partition->label is not null-terminated string. strncpy(label, (char *)&partition->label, sizeof(label) - 1); if (fl_ota_data_erase == true || (bootloader_common_label_search(list_erase, label) == true)) { - err = esp_rom_spiflash_erase_area(partition->pos.offset, partition->pos.size); + err = bootloader_flash_erase_range(partition->pos.offset, partition->pos.size); if (err != ESP_OK) { ret = false; marker = "err"; diff --git a/components/bootloader_support/src/bootloader_flash.c b/components/bootloader_support/src/bootloader_flash.c index a7a6f6e61..735c21327 100644 --- a/components/bootloader_support/src/bootloader_flash.c +++ b/components/bootloader_support/src/bootloader_flash.c @@ -73,6 +73,11 @@ esp_err_t bootloader_flash_erase_sector(size_t sector) return spi_flash_erase_sector(sector); } +esp_err_t bootloader_flash_erase_range(uint32_t start_addr, uint32_t size) +{ + return spi_flash_erase_range(start_addr, size); +} + #else /* Bootloader version, uses ROM functions only */ #include @@ -247,4 +252,28 @@ esp_err_t bootloader_flash_erase_sector(size_t sector) return spi_to_esp_err(esp_rom_spiflash_erase_sector(sector)); } +esp_err_t bootloader_flash_erase_range(uint32_t start_addr, uint32_t size) +{ + if (start_addr % FLASH_SECTOR_SIZE != 0) { + return ESP_ERR_INVALID_ARG; + } + if (size % FLASH_SECTOR_SIZE != 0) { + return ESP_ERR_INVALID_SIZE; + } + size_t start = start_addr / FLASH_SECTOR_SIZE; + size_t end = start + size / FLASH_SECTOR_SIZE; + const size_t sectors_per_block = FLASH_BLOCK_SIZE / FLASH_SECTOR_SIZE; + + esp_rom_spiflash_result_t rc = ESP_ROM_SPIFLASH_RESULT_OK; + for (size_t sector = start; sector != end && rc == ESP_ROM_SPIFLASH_RESULT_OK; ) { + if (sector % sectors_per_block == 0 && end - sector >= sectors_per_block) { + rc = esp_rom_spiflash_erase_block(sector / sectors_per_block); + sector += sectors_per_block; + } else { + rc = esp_rom_spiflash_erase_sector(sector); + ++sector; + } + } + return spi_to_esp_err(rc); +} #endif diff --git a/components/bootloader_support/src/bootloader_init.c b/components/bootloader_support/src/bootloader_init.c index fe0d756fb..68e2101ef 100644 --- a/components/bootloader_support/src/bootloader_init.c +++ b/components/bootloader_support/src/bootloader_init.c @@ -143,8 +143,21 @@ static esp_err_t bootloader_main() ESP_LOGI(TAG, "compile time " __TIME__ ); ets_set_appcpu_boot_addr(0); +#ifdef CONFIG_BOOTLOADER_WDT_ENABLE + ESP_LOGD(TAG, "Enabling RTCWDT(%d ms)", CONFIG_BOOTLOADER_WDT_TIME_MS); + rtc_wdt_protect_off(); + rtc_wdt_disable(); + rtc_wdt_set_length_of_reset_signal(RTC_WDT_SYS_RESET_SIG, RTC_WDT_LENGTH_3_2us); + rtc_wdt_set_length_of_reset_signal(RTC_WDT_CPU_RESET_SIG, RTC_WDT_LENGTH_3_2us); + rtc_wdt_set_stage(RTC_WDT_STAGE0, RTC_WDT_STAGE_ACTION_RESET_RTC); + rtc_wdt_set_time(RTC_WDT_STAGE0, CONFIG_BOOTLOADER_WDT_TIME_MS); + rtc_wdt_enable(); + rtc_wdt_protect_on(); +#else /* disable watch dog here */ rtc_wdt_disable(); +#endif + REG_SET_FIELD(TIMG_WDTWPROTECT_REG(0), TIMG_WDT_WKEY, TIMG_WDT_WKEY_VALUE); REG_CLR_BIT( TIMG_WDTCONFIG0_REG(0), TIMG_WDT_FLASHBOOT_MOD_EN ); #ifndef CONFIG_SPI_FLASH_ROM_DRIVER_PATCH diff --git a/components/bootloader_support/src/bootloader_random.c b/components/bootloader_support/src/bootloader_random.c index 36628e6c4..eb34d6add 100644 --- a/components/bootloader_support/src/bootloader_random.c +++ b/components/bootloader_support/src/bootloader_random.c @@ -23,19 +23,23 @@ #ifndef BOOTLOADER_BUILD #include "esp_system.h" -#endif +void bootloader_fill_random(void *buffer, size_t length) +{ + return esp_fill_random(buffer, length); +} + +#else void bootloader_fill_random(void *buffer, size_t length) { uint8_t *buffer_bytes = (uint8_t *)buffer; uint32_t random; -#ifdef BOOTLOADER_BUILD uint32_t start, now; -#endif + + assert(buffer != NULL); for (int i = 0; i < length; i++) { if (i == 0 || i % 4 == 0) { /* redundant check is for a compiler warning */ -#ifdef BOOTLOADER_BUILD /* in bootloader with ADC feeding HWRNG, we accumulate 1 bit of entropy per 40 APB cycles (==80 CPU cycles.) @@ -49,14 +53,12 @@ void bootloader_fill_random(void *buffer, size_t length) random ^= REG_READ(WDEV_RND_REG); RSR(CCOUNT, now); } while(now - start < 80*32*2); /* extra factor of 2 is precautionary */ -#else - random = esp_random(); -#endif } buffer_bytes[i] = random >> ((i % 4) * 8); } } +#endif // BOOTLOADER_BUILD void bootloader_random_enable(void) { diff --git a/components/bootloader_support/src/esp_image_format.c b/components/bootloader_support/src/esp_image_format.c index fea89e6a3..3cce32865 100644 --- a/components/bootloader_support/src/esp_image_format.c +++ b/components/bootloader_support/src/esp_image_format.c @@ -24,6 +24,20 @@ #include #include +/* Checking signatures as part of verifying images is necessary: + - Always if secure boot is enabled + - Differently in bootloader and/or app, depending on kconfig +*/ +#ifdef BOOTLOADER_BUILD +#ifdef CONFIG_SECURE_SIGNED_ON_BOOT +#define SECURE_BOOT_CHECK_SIGNATURE +#endif +#else /* !BOOTLOADER_BUILD */ +#ifdef CONFIG_SECURE_SIGNED_ON_UPDATE +#define SECURE_BOOT_CHECK_SIGNATURE +#endif +#endif + static const char *TAG = "esp_image"; #define HASH_LEN 32 /* SHA-256 digest length */ @@ -107,7 +121,7 @@ static esp_err_t image_load(esp_image_load_mode_t mode, const esp_partition_pos_ } // Calculate SHA-256 of image if secure boot is on, or if image has a hash appended -#ifdef CONFIG_SECURE_BOOT_ENABLED +#ifdef SECURE_BOOT_CHECK_SIGNATURE if (1) { #else if (data->image.hash_appended) { @@ -174,7 +188,7 @@ static esp_err_t image_load(esp_image_load_mode_t mode, const esp_partition_pos_ rewritten the header - rely on esptool.py having verified the bootloader at flashing time, instead. */ if (!is_bootloader) { -#ifdef CONFIG_SECURE_BOOT_ENABLED +#ifdef SECURE_BOOT_CHECK_SIGNATURE // secure boot images have a signature appended err = verify_secure_boot_signature(sha_handle, data); #else @@ -182,7 +196,7 @@ static esp_err_t image_load(esp_image_load_mode_t mode, const esp_partition_pos_ if (sha_handle != NULL && !esp_cpu_in_ocd_debug_mode()) { err = verify_simple_hash(sha_handle, data); } -#endif // CONFIG_SECURE_BOOT_ENABLED +#endif // SECURE_BOOT_CHECK_SIGNATURE } else { // is_bootloader // bootloader may still have a sha256 digest handle open if (sha_handle != NULL) { @@ -519,6 +533,8 @@ static esp_err_t verify_secure_boot_signature(bootloader_sha256_handle_t sha_han { uint8_t image_hash[HASH_LEN] = { 0 }; + ESP_LOGI(TAG, "Verifying image signature..."); + // For secure boot, we calculate the signature hash over the whole file, which includes any "simple" hash // appended to the image for corruption detection if (data->image.hash_appended) { diff --git a/components/bootloader_support/src/flash_encrypt.c b/components/bootloader_support/src/flash_encrypt.c index 7b17dd451..e04945dae 100644 --- a/components/bootloader_support/src/flash_encrypt.c +++ b/components/bootloader_support/src/flash_encrypt.c @@ -24,6 +24,7 @@ #include "esp_efuse.h" #include "esp_log.h" #include "rom/secure_boot.h" +#include "soc/rtc_wdt.h" #include "rom/cache.h" #include "rom/spi_flash.h" /* TODO: Remove this */ @@ -317,6 +318,7 @@ esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length) } for (size_t i = 0; i < data_length; i += FLASH_SECTOR_SIZE) { + rtc_wdt_feed(); uint32_t sec_start = i + src_addr; err = bootloader_flash_read(sec_start, buf, FLASH_SECTOR_SIZE, false); if (err != ESP_OK) { diff --git a/components/bt/bluedroid/api/include/api/esp_a2dp_api.h b/components/bt/bluedroid/api/include/api/esp_a2dp_api.h index 8117d4c54..3b002a405 100644 --- a/components/bt/bluedroid/api/include/api/esp_a2dp_api.h +++ b/components/bt/bluedroid/api/include/api/esp_a2dp_api.h @@ -116,7 +116,7 @@ typedef union { struct a2d_audio_cfg_param { esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ esp_a2d_mcc_t mcc; /*!< A2DP media codec capability information */ - } audio_cfg; /*!< media codec configuration infomation */ + } audio_cfg; /*!< media codec configuration information */ /** * @brief ESP_A2D_MEDIA_CTRL_ACK_EVT @@ -147,12 +147,12 @@ typedef void (* esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len); /** * @brief A2DP source data read callback function * - * @param[in] buf : buffer to be filled with PCM data stream from higer layer + * @param[in] buf : buffer to be filled with PCM data stream from higher layer * * @param[in] len : size(in bytes) of data block to be copied to buf. -1 is an indication to user * that data buffer shall be flushed * - * @return size of bytes read successfully, if the argumetn len is -1, this value is ignored. + * @return size of bytes read successfully, if the argument len is -1, this value is ignored. * */ typedef int32_t (* esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len); diff --git a/components/bt/bluedroid/api/include/api/esp_avrc_api.h b/components/bt/bluedroid/api/include/api/esp_avrc_api.h index 228beb8ae..e1f68392c 100644 --- a/components/bt/bluedroid/api/include/api/esp_avrc_api.h +++ b/components/bt/bluedroid/api/include/api/esp_avrc_api.h @@ -111,7 +111,7 @@ typedef enum { /// AVRC shuffle modes typedef enum { ESP_AVRC_PS_SHUFFLE_OFF = 0x1, /* #include @@ -44,3 +47,5 @@ extern esp_err_t esp_ble_gatt_set_local_mtu (uint16_t mtu); #ifdef __cplusplus } #endif + +#endif /* __ESP_GATT_COMMON_API_H__ */ diff --git a/components/bt/bluedroid/api/include/api/esp_gatt_defs.h b/components/bt/bluedroid/api/include/api/esp_gatt_defs.h index 7053f266f..de4bc8976 100644 --- a/components/bt/bluedroid/api/include/api/esp_gatt_defs.h +++ b/components/bt/bluedroid/api/include/api/esp_gatt_defs.h @@ -224,7 +224,7 @@ typedef enum { ESP_GATT_CONN_L2C_FAILURE = 1, /*!< General L2cap failure */ /* relate to BTA_GATT_CONN_L2C_FAILURE in bta/bta_gatt_api.h */ ESP_GATT_CONN_TIMEOUT = 0x08, /*!< Connection timeout */ /* relate to BTA_GATT_CONN_TIMEOUT in bta/bta_gatt_api.h */ ESP_GATT_CONN_TERMINATE_PEER_USER = 0x13, /*!< Connection terminate by peer user */ /* relate to BTA_GATT_CONN_TERMINATE_PEER_USER in bta/bta_gatt_api.h */ - ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connectionterminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta/bta_gatt_api.h */ + ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connection terminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta/bta_gatt_api.h */ ESP_GATT_CONN_FAIL_ESTABLISH = 0x3e, /*!< Connection fail to establish */ /* relate to BTA_GATT_CONN_FAIL_ESTABLISH in bta/bta_gatt_api.h */ ESP_GATT_CONN_LMP_TIMEOUT = 0x22, /*!< Connection fail for LMP response tout */ /* relate to BTA_GATT_CONN_LMP_TIMEOUT in bta/bta_gatt_api.h */ ESP_GATT_CONN_CONN_CANCEL = 0x0100, /*!< L2CAP connection cancelled */ /* relate to BTA_GATT_CONN_CONN_CANCEL in bta/bta_gatt_api.h */ @@ -453,7 +453,7 @@ typedef struct { uint16_t incl_srvc_s_handle; /*!< The start handle of the service which has been included */ uint16_t incl_srvc_e_handle; /*!< The end handle of the service which has been included */ esp_bt_uuid_t uuid; /*!< The include service uuid */ -} esp_gattc_incl_svc_elem_t; /*!< The gattc inclue service element */ +} esp_gattc_incl_svc_elem_t; /*!< The gattc include service element */ #ifdef __cplusplus diff --git a/components/bt/bluedroid/api/include/api/esp_gattc_api.h b/components/bt/bluedroid/api/include/api/esp_gattc_api.h index 44c013d5e..b0fabb7a1 100644 --- a/components/bt/bluedroid/api/include/api/esp_gattc_api.h +++ b/components/bt/bluedroid/api/include/api/esp_gattc_api.h @@ -312,7 +312,7 @@ esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, e /** - * @brief Close a virtual connection to a GATT server. gattc maybe have multiple virtual GATT server connections when multiple app_id registed, + * @brief Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections when multiple app_id registered, * this API only close one virtual GATT server connection. if there exist other virtual GATT server connections, * it does not disconnect the physical connection. * if you want to disconnect the physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device). @@ -371,7 +371,7 @@ esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID which identify the server. * @param[in] svc_uuid: the pointer to the service uuid. - * @param[out] result: The pointer to the service whith has been found in the gattc cache. + * @param[out] result: The pointer to the service which has been found in the gattc cache. * @param[inout] count: input the number of service want to find, * it will output the number of service has been found in the gattc cache with the given service uuid. * @param[in] offset: Offset of the service position to get. @@ -392,7 +392,7 @@ esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t con * @param[in] conn_id: connection ID which identify the server. * @param[in] start_handle: the attribute start handle. * @param[in] end_handle: the attribute end handle - * @param[out] result: The pointer to the charateristic in the service. + * @param[out] result: The pointer to the characteristic in the service. * @param[inout] count: input the number of characteristic want to find, * it will output the number of characteristic has been found in the gattc cache with the given service. * @param[in] offset: Offset of the characteristic position to get. @@ -695,7 +695,7 @@ esp_err_t esp_ble_gattc_write_char_descr (esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : charateristic handle to prepare write. + * @param[in] handle : characteristic handle to prepare write. * @param[in] offset : offset of the write value. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. @@ -720,7 +720,7 @@ esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : characteristic descriptor hanlde to prepare write. + * @param[in] handle : characteristic descriptor handle to prepare write. * @param[in] offset : offset of the write value. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. diff --git a/components/bt/bluedroid/api/include/api/esp_hf_client_api.h b/components/bt/bluedroid/api/include/api/esp_hf_client_api.h index 65598e087..67ec894e0 100644 --- a/components/bt/bluedroid/api/include/api/esp_hf_client_api.h +++ b/components/bt/bluedroid/api/include/api/esp_hf_client_api.h @@ -40,7 +40,7 @@ typedef enum { ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED = 0, /*!< audio connection released */ ESP_HF_CLIENT_AUDIO_STATE_CONNECTING, /*!< audio connection has been initiated */ ESP_HF_CLIENT_AUDIO_STATE_CONNECTED, /*!< audio connection is established */ - ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is estalibshed */ + ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is established */ } esp_hf_client_audio_state_t; /// in-band ring tone state @@ -66,9 +66,9 @@ typedef enum { #define ESP_HF_CLIENT_CHLD_FEAT_REL_ACC 0x02 /* 1 Release active calls and accept other waiting or held call */ #define ESP_HF_CLIENT_CHLD_FEAT_REL_X 0x04 /* 1x Release specified active call only */ #define ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC 0x08 /* 2 Active calls on hold and accept other waiting or held call */ -#define ESP_HF_CLIENT_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold */ +#define ESP_HF_CLIENT_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold) */ #define ESP_HF_CLIENT_CHLD_FEAT_MERGE 0x20 /* 3 Add held call to multiparty */ -#define ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnct from multiparty */ +#define ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnect from multiparty) */ /// HF CLIENT callback events typedef enum { @@ -140,7 +140,7 @@ typedef union { * @brief ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT */ struct hf_client_signal_strength_ind_param { - int value; /*!< singal strength value, ranges from 0 to 5 */ + int value; /*!< signal strength value, ranges from 0 to 5 */ } signal_strength; /*!< HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT */ /** @@ -175,7 +175,7 @@ typedef union { * @brief ESP_HF_CLIENT_CIND_CALL_HELD_EVT */ struct hf_client_call_held_ind_param { - esp_hf_call_held_status_t status; /*!< bluetooth proprietary call hold status indocator */ + esp_hf_call_held_status_t status; /*!< bluetooth proprietary call hold status indicator */ } call_held; /*!< HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT */ /** @@ -619,7 +619,7 @@ void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t c * @brief Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM * samples. This can only be used in the case that Voice Over HCI is enabled. * - * @param[in] src: pointer to the buffer where the original smapling PCM are stored + * @param[in] src: pointer to the buffer where the original sampling PCM are stored * @param[in] in_bytes: length of the input PCM sample buffer in byte * @param[in] dst: pointer to the buffer which is to be used to store the converted PCM samples * diff --git a/components/bt/bluedroid/api/include/api/esp_hf_defs.h b/components/bt/bluedroid/api/include/api/esp_hf_defs.h index b71277932..1ff9f14f6 100644 --- a/components/bt/bluedroid/api/include/api/esp_hf_defs.h +++ b/components/bt/bluedroid/api/include/api/esp_hf_defs.h @@ -120,7 +120,7 @@ typedef enum { /// response indication codes for AT commands typedef enum { - ESP_HF_AT_RESPONSE_CODE_OK = 0, /*!< acknoweledges execution of a command line */ + ESP_HF_AT_RESPONSE_CODE_OK = 0, /*!< acknowledges execution of a command line */ ESP_HF_AT_RESPONSE_CODE_ERR, /*!< command not accepted */ ESP_HF_AT_RESPONSE_CODE_NO_CARRIER, /*!< connection terminated */ ESP_HF_AT_RESPONSE_CODE_BUSY, /*!< busy signal detected */ diff --git a/components/bt/bluedroid/api/include/api/esp_spp_api.h b/components/bt/bluedroid/api/include/api/esp_spp_api.h index e819158cd..d7f357748 100644 --- a/components/bt/bluedroid/api/include/api/esp_spp_api.h +++ b/components/bt/bluedroid/api/include/api/esp_spp_api.h @@ -62,9 +62,9 @@ typedef enum { ESP_SPP_CLOSE_EVT = 27, /*!< When SPP connection closed, the event comes */ ESP_SPP_START_EVT = 28, /*!< When SPP server started, the event comes */ ESP_SPP_CL_INIT_EVT = 29, /*!< When SPP client initiated a connection, the event comes */ - ESP_SPP_DATA_IND_EVT = 30, /*!< When SPP connection received data, the event comes, olny for ESP_SPP_MODE_CB */ - ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes, olny for ESP_SPP_MODE_CB */ - ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, the event comes, olny for ESP_SPP_MODE_CB */ + ESP_SPP_DATA_IND_EVT = 30, /*!< When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB */ ESP_SPP_SRV_OPEN_EVT = 34, /*!< When SPP Server connection open, the event comes */ } esp_spp_cb_event_t; @@ -95,7 +95,7 @@ typedef union { struct spp_open_evt_param { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ - int fd; /*!< The file descriptor olny for ESP_SPP_MODE_VFS*/ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ esp_bd_addr_t rem_bda; /*!< The peer address */ } open; /*!< SPP callback param of ESP_SPP_OPEN_EVT */ @@ -106,7 +106,7 @@ typedef union { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ uint32_t new_listen_handle; /*!< The new listen handle */ - int fd; /*!< The file descriptor olny for ESP_SPP_MODE_VFS*/ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ esp_bd_addr_t rem_bda; /*!< The peer address */ } srv_open; /*!< SPP callback param of ESP_SPP_SRV_OPEN_EVT */ /** @@ -155,7 +155,7 @@ typedef union { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ uint16_t len; /*!< The length of data */ - uint8_t *data; /*!< The data recived */ + uint8_t *data; /*!< The data received */ } data_ind; /*!< SPP callback param of ESP_SPP_DATA_IND_EVT */ /** @@ -224,14 +224,14 @@ esp_err_t esp_spp_deinit(); esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr); /** - * @brief This function makes an SPP conection to a remote BD Address. + * @brief This function makes an SPP connection to a remote BD Address. * When the connection is initiated or failed to initiate, * the callback is called with ESP_SPP_CL_INIT_EVT. * When the connection is established or failed, * the callback is called with ESP_SPP_OPEN_EVT. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @param[in] role: Master or slave. * @param[in] remote_scn: Remote device bluetooth device SCN. * @param[in] peer_bd_addr: Remote device bluetooth device address. * @@ -262,7 +262,7 @@ esp_err_t esp_spp_disconnect(uint32_t handle); * with ESP_SPP_SRV_OPEN_EVT. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @param[in] role: Master or slave. * @param[in] local_scn: The specific channel you want to get. * If channel is 0, means get any channel. * @param[in] name: Server's name. @@ -276,7 +276,7 @@ esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, /** - * @brief This function is used to write data, olny for ESP_SPP_MODE_CB. + * @brief This function is used to write data, only for ESP_SPP_MODE_CB. * * @param[in] handle: The connection handle. * @param[in] len: The length of the data written. @@ -302,4 +302,4 @@ esp_err_t esp_spp_vfs_register(void); } #endif -#endif ///__ESP_SPP_API_H__ \ No newline at end of file +#endif ///__ESP_SPP_API_H__ diff --git a/components/bt/bluedroid/stack/btm/btm_ble_addr.c b/components/bt/bluedroid/stack/btm/btm_ble_addr.c index d62717fae..785ed733f 100644 --- a/components/bt/bluedroid/stack/btm/btm_ble_addr.c +++ b/components/bt/bluedroid/stack/btm/btm_ble_addr.c @@ -65,6 +65,23 @@ static void btm_gen_resolve_paddr_cmpl(tSMP_ENC *p) p_cb->set_local_privacy_cback = NULL; } + if (btm_cb.ble_ctr_cb.inq_var.adv_mode == BTM_BLE_ADV_ENABLE){ + BTM_TRACE_DEBUG("Advertise with new resolvable private address, now."); + /** + * Restart advertising, using new resolvable private address + */ + btm_ble_stop_adv(); + btm_ble_start_adv(); + } + if (btm_cb.ble_ctr_cb.inq_var.state == BTM_BLE_SCANNING){ + BTM_TRACE_DEBUG("Scan with new resolvable private address, now."); + /** + * Restart scaning, using new resolvable private address + */ + btm_ble_stop_scan(); + btm_ble_start_scan(); + } + /* start a periodical timer to refresh random addr */ btu_stop_timer_oneshot(&p_cb->raddr_timer_ent); #if (BTM_BLE_CONFORMANCE_TESTING == TRUE) diff --git a/components/bt/bluedroid/stack/rfcomm/rfc_ts_frames.c b/components/bt/bluedroid/stack/rfcomm/rfc_ts_frames.c index 3a9a60b74..26a2caa02 100644 --- a/components/bt/bluedroid/stack/rfcomm/rfc_ts_frames.c +++ b/components/bt/bluedroid/stack/rfcomm/rfc_ts_frames.c @@ -23,6 +23,7 @@ ******************************************************************************/ #include +#include #include "common/bt_target.h" #include "stack/rfcdefs.h" #include "stack/port_api.h" @@ -513,6 +514,13 @@ void rfc_send_test (tRFC_MCB *p_mcb, BOOLEAN is_command, BT_HDR *p_buf) UINT16 xx; UINT8 *p_src, *p_dest; + BT_HDR *p_buf_new; + if ((p_buf_new = (BT_HDR *)osi_malloc(RFCOMM_CMD_BUF_SIZE)) == NULL) { + return; + } + memcpy(p_buf_new, p_buf, sizeof(BT_HDR) + p_buf->offset + p_buf->len); + osi_free(p_buf); + p_buf = p_buf_new; /* Shift buffer to give space for header */ if (p_buf->offset < (L2CAP_MIN_OFFSET + RFCOMM_MIN_OFFSET + 2)) { p_src = (UINT8 *) (p_buf + 1) + p_buf->offset + p_buf->len - 1; diff --git a/components/bt/bluedroid/stack/sdp/sdp_discovery.c b/components/bt/bluedroid/stack/sdp/sdp_discovery.c index 8f76f2022..d63b164de 100644 --- a/components/bt/bluedroid/stack/sdp/sdp_discovery.c +++ b/components/bt/bluedroid/stack/sdp/sdp_discovery.c @@ -354,15 +354,17 @@ static void sdp_copy_raw_data (tCONN_CB *p_ccb, BOOLEAN offset) type = *p++; p = sdpu_get_len_from_type (p, type, &list_len); } - if (list_len && list_len < cpy_len ) { + if (list_len < cpy_len ) { cpy_len = list_len; } #if (SDP_DEBUG_RAW == TRUE) - SDP_TRACE_WARNING("list_len :%d cpy_len:%d raw_size:%d raw_used:%d\n", + SDP_TRACE_DEBUG("list_len :%d cpy_len:%d raw_size:%d raw_used:%d\n", list_len, cpy_len, p_ccb->p_db->raw_size, p_ccb->p_db->raw_used); #endif - memcpy (&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); - p_ccb->p_db->raw_used += cpy_len; + if (cpy_len != 0){ + memcpy (&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); + p_ccb->p_db->raw_used += cpy_len; + } } } #endif diff --git a/components/bt/bt.c b/components/bt/bt.c index a5d5e1424..b23750662 100644 --- a/components/bt/bt.c +++ b/components/bt/bt.c @@ -820,17 +820,30 @@ static void btdm_controller_mem_init(void) { /* initialise .data section */ memcpy(&_data_start_btdm, (void *)_data_start_btdm_rom, &_data_end_btdm - &_data_start_btdm); - ESP_LOGD(BTDM_LOG_TAG, ".data initialise [0x%08x] <== [0x%08x]\n", (uint32_t)&_data_start_btdm, _data_start_btdm_rom); + ESP_LOGD(BTDM_LOG_TAG, ".data initialise [0x%08x] <== [0x%08x]", (uint32_t)&_data_start_btdm, _data_start_btdm_rom); //initial em, .bss section for (int i = 1; i < sizeof(btdm_dram_available_region)/sizeof(btdm_dram_available_region_t); i++) { if (btdm_dram_available_region[i].mode != ESP_BT_MODE_IDLE) { memset((void *)btdm_dram_available_region[i].start, 0x0, btdm_dram_available_region[i].end - btdm_dram_available_region[i].start); - ESP_LOGD(BTDM_LOG_TAG, ".bss initialise [0x%08x] - [0x%08x]\n", btdm_dram_available_region[i].start, btdm_dram_available_region[i].end); + ESP_LOGD(BTDM_LOG_TAG, ".bss initialise [0x%08x] - [0x%08x]", btdm_dram_available_region[i].start, btdm_dram_available_region[i].end); } } } +static esp_err_t try_heap_caps_add_region(intptr_t start, intptr_t end) +{ + int ret = heap_caps_add_region(start, end); + /* heap_caps_add_region() returns ESP_ERR_INVALID_SIZE if the memory region is + * is too small to fit a heap. This cannot be termed as a fatal error and hence + * we replace it by ESP_OK + */ + if (ret == ESP_ERR_INVALID_SIZE) { + return ESP_OK; + } + return ret; +} + esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode) { bool update = true; @@ -870,14 +883,14 @@ esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode) && mem_end == btdm_dram_available_region[i+1].start) { continue; } else { - ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); update = true; } } else { mem_end = btdm_dram_available_region[i].end; - ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release DRAM [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); update = true; } } @@ -886,14 +899,14 @@ esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode) mem_start = (intptr_t)&_btdm_bss_start; mem_end = (intptr_t)&_btdm_bss_end; if (mem_start != mem_end) { - ESP_LOGD(BTDM_LOG_TAG, "Release BTDM BSS [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release BTDM BSS [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); } mem_start = (intptr_t)&_btdm_data_start; mem_end = (intptr_t)&_btdm_data_end; if (mem_start != mem_end) { - ESP_LOGD(BTDM_LOG_TAG, "Release BTDM Data [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release BTDM Data [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); } } return ESP_OK; @@ -913,14 +926,14 @@ esp_err_t esp_bt_mem_release(esp_bt_mode_t mode) mem_start = (intptr_t)&_bt_bss_start; mem_end = (intptr_t)&_bt_bss_end; if (mem_start != mem_end) { - ESP_LOGD(BTDM_LOG_TAG, "Release BT BSS [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release BT BSS [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); } mem_start = (intptr_t)&_bt_data_start; mem_end = (intptr_t)&_bt_data_end; if (mem_start != mem_end) { - ESP_LOGD(BTDM_LOG_TAG, "Release BT Data [0x%08x] - [0x%08x]\n", mem_start, mem_end); - ESP_ERROR_CHECK(heap_caps_add_region(mem_start, mem_end)); + ESP_LOGD(BTDM_LOG_TAG, "Release BT Data [0x%08x] - [0x%08x]", mem_start, mem_end); + ESP_ERROR_CHECK(try_heap_caps_add_region(mem_start, mem_end)); } } return ESP_OK; @@ -976,7 +989,7 @@ esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg) } #endif - ESP_LOGI(BTDM_LOG_TAG, "BT controller compile version [%s]\n", btdm_controller_get_compile_version()); + ESP_LOGI(BTDM_LOG_TAG, "BT controller compile version [%s]", btdm_controller_get_compile_version()); #if CONFIG_SPIRAM_USE_MALLOC btdm_queue_table_mux = xSemaphoreCreateMutex(); diff --git a/components/bt/include/esp_bt.h b/components/bt/include/esp_bt.h index 0376b5d38..c18e0e543 100644 --- a/components/bt/include/esp_bt.h +++ b/components/bt/include/esp_bt.h @@ -141,7 +141,7 @@ typedef struct { * It will be overwrite with a constant value which in menuconfig or from a macro. * So, do not modify the value when esp_bt_controller_init() */ - uint8_t bt_max_sync_conn; /*!< BR/EDR maxium ACL connection numbers. Effective in menuconfig */ + uint8_t bt_max_sync_conn; /*!< BR/EDR maximum ACL connection numbers. Effective in menuconfig */ uint32_t magic; /*!< Magic number */ } esp_bt_controller_config_t; @@ -233,7 +233,7 @@ esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type); * BR/EDR power control will use the power in range of minimum value and maximum value. * The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on. * Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. - * So you can call the function can before do discover, beofre profile init and so on. + * So you can call the function before doing discovery, profile init and so on. * For example, if you want BR/EDR use the new TX power to do inquire, you should call * this function before inquire. Another word, If call this function when BR/EDR is in inquire(ING), * please do inquire again after call this function. @@ -324,7 +324,7 @@ bool esp_vhci_host_check_send_available(void); void esp_vhci_host_send_packet(uint8_t *data, uint16_t len); /** @brief esp_vhci_host_register_callback - * register the vhci referece callback, the call back + * register the vhci reference callback * struct defined by vhci_host_callback structure. * @param callback esp_vhci_host_callback type variable * @return ESP_OK - success, ESP_FAIL - failed @@ -440,7 +440,7 @@ bool esp_bt_controller_is_sleeping(void); * Note that after this request, bluetooth controller may again enter sleep as long as the modem sleep is enabled * * Profiling shows that it takes several milliseconds to wakeup from modem sleep after this request. - * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequncy of the former as the bluetooth low power clock source. + * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequency of the former as the bluetooth low power clock source. */ void esp_bt_controller_wakeup_request(void); diff --git a/components/bt/lib b/components/bt/lib index 17e29e6ed..c272133d6 160000 --- a/components/bt/lib +++ b/components/bt/lib @@ -1 +1 @@ -Subproject commit 17e29e6ed4e2c952a24e4097e9f41bb89bac6128 +Subproject commit c272133d6d9c046e05e2514b12e17cc561980865 diff --git a/components/driver/can.c b/components/driver/can.c index 139d8a49a..0c20288f9 100644 --- a/components/driver/can.c +++ b/components/driver/can.c @@ -20,6 +20,7 @@ #include "esp_types.h" #include "esp_log.h" #include "esp_intr_alloc.h" +#include "esp_pm.h" #include "soc/dport_reg.h" #include "soc/can_struct.h" #include "driver/gpio.h" @@ -128,6 +129,10 @@ typedef struct { SemaphoreHandle_t alert_semphr; uint32_t alerts_enabled; uint32_t alerts_triggered; +#ifdef CONFIG_PM_ENABLE + //Power Management + esp_pm_lock_handle_t pm_lock; +#endif } can_obj_t; static can_obj_t *p_can_obj = NULL; @@ -591,6 +596,7 @@ static void can_configure_gpio(gpio_num_t tx, gpio_num_t rx, gpio_num_t clkout, gpio_set_pull_mode(rx, GPIO_FLOATING); gpio_matrix_in(rx, CAN_RX_IDX, false); gpio_pad_select_gpio(rx); + gpio_set_direction(rx, GPIO_MODE_INPUT); //Configure output clock pin (Optional) if (clkout >= 0 && clkout < GPIO_NUM_MAX) { @@ -611,41 +617,61 @@ static void can_configure_gpio(gpio_num_t tx, gpio_num_t rx, gpio_num_t clkout, esp_err_t can_driver_install(const can_general_config_t *g_config, const can_timing_config_t *t_config, const can_filter_config_t *f_config) { - //Check arguments and state - CAN_CHECK(p_can_obj == NULL, ESP_ERR_INVALID_STATE); //Check is driver is already installed + //Check arguments CAN_CHECK(g_config != NULL, ESP_ERR_INVALID_ARG); CAN_CHECK(t_config != NULL, ESP_ERR_INVALID_ARG); CAN_CHECK(f_config != NULL, ESP_ERR_INVALID_ARG); CAN_CHECK(g_config->rx_queue_len > 0, ESP_ERR_INVALID_ARG); CAN_CHECK(g_config->tx_io >= 0 && g_config->tx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG); CAN_CHECK(g_config->rx_io >= 0 && g_config->rx_io < GPIO_NUM_MAX, ESP_ERR_INVALID_ARG); - esp_err_t ret; - //Initialize CAN object - p_can_obj = calloc(1, sizeof(can_obj_t)); - CAN_CHECK(p_can_obj != NULL, ESP_ERR_NO_MEM); - p_can_obj->tx_queue = (g_config->tx_queue_len > 0) ? xQueueCreate(g_config->tx_queue_len, sizeof(can_frame_t)) : NULL; - p_can_obj->rx_queue = xQueueCreate(g_config->rx_queue_len, sizeof(can_frame_t)); - p_can_obj->alert_semphr = xSemaphoreCreateBinary(); - if ((g_config->tx_queue_len > 0 && p_can_obj->tx_queue == NULL) || - p_can_obj->rx_queue == NULL || p_can_obj->alert_semphr == NULL) { + esp_err_t ret; + can_obj_t *p_can_obj_dummy; + + //Create a CAN object + p_can_obj_dummy = calloc(1, sizeof(can_obj_t)); + CAN_CHECK(p_can_obj_dummy != NULL, ESP_ERR_NO_MEM); + + //Initialize queues, semaphores, and power management locks + p_can_obj_dummy->tx_queue = (g_config->tx_queue_len > 0) ? xQueueCreate(g_config->tx_queue_len, sizeof(can_frame_t)) : NULL; + p_can_obj_dummy->rx_queue = xQueueCreate(g_config->rx_queue_len, sizeof(can_frame_t)); + p_can_obj_dummy->alert_semphr = xSemaphoreCreateBinary(); + if ((g_config->tx_queue_len > 0 && p_can_obj_dummy->tx_queue == NULL) || + p_can_obj_dummy->rx_queue == NULL || p_can_obj_dummy->alert_semphr == NULL) { ret = ESP_ERR_NO_MEM; goto err; } - p_can_obj->control_flags = CTRL_FLAG_STOPPED; - p_can_obj->control_flags |= (g_config->mode == CAN_MODE_NO_ACK) ? CTRL_FLAG_SELF_TEST : 0; - p_can_obj->control_flags |= (g_config->mode == CAN_MODE_LISTEN_ONLY) ? CTRL_FLAG_LISTEN_ONLY : 0; - p_can_obj->tx_msg_count = 0; - p_can_obj->rx_msg_count = 0; - p_can_obj->tx_failed_count = 0; - p_can_obj->rx_missed_count = 0; - p_can_obj->arb_lost_count = 0; - p_can_obj->bus_error_count = 0; - p_can_obj->alerts_enabled = g_config->alerts_enabled; - p_can_obj->alerts_triggered = 0; +#ifdef CONFIG_PM_ENABLE + esp_err_t pm_err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "can", &(p_can_obj_dummy->pm_lock)); + if (pm_err != ESP_OK ) { + ret = pm_err; + goto err; + } +#endif + //Initialize flags and variables + p_can_obj_dummy->control_flags = CTRL_FLAG_STOPPED; + p_can_obj_dummy->control_flags |= (g_config->mode == CAN_MODE_NO_ACK) ? CTRL_FLAG_SELF_TEST : 0; + p_can_obj_dummy->control_flags |= (g_config->mode == CAN_MODE_LISTEN_ONLY) ? CTRL_FLAG_LISTEN_ONLY : 0; + p_can_obj_dummy->tx_msg_count = 0; + p_can_obj_dummy->rx_msg_count = 0; + p_can_obj_dummy->tx_failed_count = 0; + p_can_obj_dummy->rx_missed_count = 0; + p_can_obj_dummy->arb_lost_count = 0; + p_can_obj_dummy->bus_error_count = 0; + p_can_obj_dummy->alerts_enabled = g_config->alerts_enabled; + p_can_obj_dummy->alerts_triggered = 0; + + //Initialize CAN peripheral registers, and allocate interrupt CAN_ENTER_CRITICAL(); - //Initialize CAN peripheral + if (p_can_obj == NULL) { + p_can_obj = p_can_obj_dummy; + } else { + //Check if driver is already installed + CAN_EXIT_CRITICAL(); + ret = ESP_ERR_INVALID_STATE; + goto err; + } periph_module_enable(PERIPH_CAN_MODULE); //Enable APB CLK to CAN peripheral configASSERT(can_enter_reset_mode() == ESP_OK); //Must enter reset mode to write to config registers can_config_pelican(); //Use PeliCAN addresses @@ -661,56 +687,72 @@ esp_err_t can_driver_install(const can_general_config_t *g_config, const can_tim can_configure_gpio(g_config->tx_io, g_config->rx_io, g_config->clkout_io, g_config->bus_off_io); (void) can_get_interrupt_reason(); //Read interrupt reg to clear it before allocating ISR ESP_ERROR_CHECK(esp_intr_alloc(ETS_CAN_INTR_SOURCE, 0, can_intr_handler_main, NULL, &p_can_obj->isr_handle)); - CAN_EXIT_CRITICAL(); //Todo: Allow interrupt to be registered to specified CPU + CAN_EXIT_CRITICAL(); - //CAN module is still in reset mode, users need to call can_start() afterwards - return ESP_OK; +#ifdef CONFIG_PM_ENABLE + ESP_ERROR_CHECK(esp_pm_lock_acquire(p_can_obj->pm_lock)); //Acquire pm_lock to keep APB clock at 80MHz +#endif + return ESP_OK; //CAN module is still in reset mode, users need to call can_start() afterwards err: - //Cleanup and return error - if (p_can_obj != NULL) { - if (p_can_obj->tx_queue != NULL) { - vQueueDelete(p_can_obj->tx_queue); - p_can_obj->tx_queue = NULL; + //Cleanup CAN object and return error + if (p_can_obj_dummy != NULL) { + if (p_can_obj_dummy->tx_queue != NULL) { + vQueueDelete(p_can_obj_dummy->tx_queue); + p_can_obj_dummy->tx_queue = NULL; } - if (p_can_obj->rx_queue != NULL) { - vQueueDelete(p_can_obj->rx_queue); - p_can_obj->rx_queue = NULL; + if (p_can_obj_dummy->rx_queue != NULL) { + vQueueDelete(p_can_obj_dummy->rx_queue); + p_can_obj_dummy->rx_queue = NULL; } - if (p_can_obj->alert_semphr != NULL) { - vSemaphoreDelete(p_can_obj->alert_semphr); - p_can_obj->alert_semphr = NULL; + if (p_can_obj_dummy->alert_semphr != NULL) { + vSemaphoreDelete(p_can_obj_dummy->alert_semphr); + p_can_obj_dummy->alert_semphr = NULL; } - free(p_can_obj); +#ifdef CONFIG_PM_ENABLE + if (p_can_obj_dummy->pm_lock != NULL) { + ESP_ERROR_CHECK(esp_pm_lock_delete(p_can_obj_dummy->pm_lock)); + } +#endif + free(p_can_obj_dummy); } return ret; } esp_err_t can_driver_uninstall() { - //Check state + can_obj_t *p_can_obj_dummy; + CAN_ENTER_CRITICAL(); + //Check state CAN_CHECK_FROM_CRIT(p_can_obj != NULL, ESP_ERR_INVALID_STATE); CAN_CHECK_FROM_CRIT(p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF), ESP_ERR_INVALID_STATE); - - //Clear registers configASSERT(can_enter_reset_mode() == ESP_OK); //Enter reset mode to stop any CAN bus activity + //Clear registers by reading (void) can_get_interrupt_reason(); (void) can_get_arbitration_lost_capture(); (void) can_get_error_code_capture(); ESP_ERROR_CHECK(esp_intr_free(p_can_obj->isr_handle)); //Free interrupt periph_module_disable(PERIPH_CAN_MODULE); //Disable CAN peripheral - //Delete queues, semaphores - if (p_can_obj->tx_queue != NULL) { - vQueueDelete(p_can_obj->tx_queue); - } - vQueueDelete(p_can_obj->rx_queue); - vSemaphoreDelete(p_can_obj->alert_semphr); - free(p_can_obj); //Free can driver object + p_can_obj_dummy = p_can_obj; //Use dummy to shorten critical section + p_can_obj = NULL; CAN_EXIT_CRITICAL(); + //Delete queues, semaphores, and power management locks + if (p_can_obj_dummy->tx_queue != NULL) { + vQueueDelete(p_can_obj_dummy->tx_queue); + } + vQueueDelete(p_can_obj_dummy->rx_queue); + vSemaphoreDelete(p_can_obj_dummy->alert_semphr); +#ifdef CONFIG_PM_ENABLE + //Release and delete power management lock + ESP_ERROR_CHECK(esp_pm_lock_release(p_can_obj_dummy->pm_lock)); + ESP_ERROR_CHECK(esp_pm_lock_delete(p_can_obj_dummy->pm_lock)); +#endif + free(p_can_obj_dummy); //Free can driver object + return ESP_OK; } @@ -801,7 +843,7 @@ esp_err_t can_transmit(const can_message_t *message, TickType_t ticks_to_wait) } else if (xQueueSend(p_can_obj->tx_queue, &tx_frame, ticks_to_wait) == pdTRUE) { //Copied to TX Queue CAN_ENTER_CRITICAL(); - if (p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_STOPPED)) { + if (p_can_obj->control_flags & (CTRL_FLAG_STOPPED | CTRL_FLAG_BUS_OFF)) { //TX queue was reset (due to stop/bus_off), remove copied frame from queue to prevent transmission configASSERT(xQueueReceive(p_can_obj->tx_queue, &tx_frame, 0) == pdTRUE); ret = ESP_ERR_INVALID_STATE; diff --git a/components/driver/include/driver/can.h b/components/driver/include/driver/can.h index 5ec272ca4..af7b66e0b 100644 --- a/components/driver/include/driver/can.h +++ b/components/driver/include/driver/can.h @@ -42,6 +42,8 @@ extern "C" { * @brief Initializer macros for timing configuration structure * * The following initializer macros offer commonly found bit rates. + * + * @note These timing values are based on the assumption APB clock is at 80MHz */ #define CAN_TIMING_CONFIG_25KBITS() {.brp = 128, .tseg_1 = 16, .tseg_2 = 8, .sjw = 3, .triple_sampling = false} #define CAN_TIMING_CONFIG_50KBITS() {.brp = 80, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} diff --git a/components/esp32/Kconfig b/components/esp32/Kconfig index 2f7d4c868..aa7415f57 100644 --- a/components/esp32/Kconfig +++ b/components/esp32/Kconfig @@ -646,6 +646,14 @@ config BROWNOUT_DET_LVL default 7 if BROWNOUT_DET_LVL_SEL_7 +#Reduce PHY TX power when brownout reset +config REDUCE_PHY_TX_POWER + bool "Reduce PHY TX power when brownout reset" + depends on BROWNOUT_DET + default y + help + When brownout reset occurs, reduce PHY TX power to keep the code running + # Note about the use of "FRC1" name: currently FRC1 timer is not used for # high resolution timekeeping anymore. Instead the esp_timer API, implemented # using FRC2 timer, is used. diff --git a/components/esp32/clk.c b/components/esp32/clk.c index 17afaa1b3..54abc18b7 100644 --- a/components/esp32/clk.c +++ b/components/esp32/clk.c @@ -26,6 +26,7 @@ #include "rom/rtc.h" #include "soc/soc.h" #include "soc/rtc.h" +#include "soc/rtc_wdt.h" #include "soc/rtc_cntl_reg.h" #include "soc/i2s_reg.h" #include "driver/periph_ctrl.h" @@ -87,6 +88,18 @@ void esp_clk_init(void) rtc_clk_fast_freq_set(RTC_FAST_FREQ_8M); +#ifdef CONFIG_BOOTLOADER_WDT_ENABLE + // WDT uses a SLOW_CLK clock source. After a function select_rtc_slow_clk a frequency of this source can changed. + // If the frequency changes from 150kHz to 32kHz, then the timeout set for the WDT will increase 4.6 times. + // Therefore, for the time of frequency change, set a new lower timeout value (1.6 sec). + // This prevents excessive delay before resetting in case the supply voltage is drawdown. + // (If frequency is changed from 150kHz to 32kHz then WDT timeout will increased to 1.6sec * 150/32 = 7.5 sec). + rtc_wdt_protect_off(); + rtc_wdt_feed(); + rtc_wdt_set_time(RTC_WDT_STAGE0, 1600); + rtc_wdt_protect_on(); +#endif + #if defined(CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL) select_rtc_slow_clk(SLOW_CLK_32K_XTAL); #elif defined(CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_OSC) @@ -97,6 +110,14 @@ void esp_clk_init(void) select_rtc_slow_clk(RTC_SLOW_FREQ_RTC); #endif +#ifdef CONFIG_BOOTLOADER_WDT_ENABLE + // After changing a frequency WDT timeout needs to be set for new frequency. + rtc_wdt_protect_off(); + rtc_wdt_feed(); + rtc_wdt_set_time(RTC_WDT_STAGE0, CONFIG_BOOTLOADER_WDT_TIME_MS); + rtc_wdt_protect_on(); +#endif + rtc_cpu_freq_config_t old_config, new_config; rtc_clk_cpu_freq_get_config(&old_config); const uint32_t old_freq_mhz = old_config.freq_mhz; diff --git a/components/esp32/cpu_start.c b/components/esp32/cpu_start.c index bf044bd7b..cfff63a2c 100644 --- a/components/esp32/cpu_start.c +++ b/components/esp32/cpu_start.c @@ -137,7 +137,9 @@ void IRAM_ATTR call_start_cpu0() || rst_reas[1] == RTCWDT_SYS_RESET || rst_reas[1] == TG0WDT_SYS_RESET #endif ) { +#ifndef CONFIG_BOOTLOADER_WDT_ENABLE rtc_wdt_disable(); +#endif } //Clear BSS. Please do not attempt to do any complex stuff (like early logging) before this. @@ -427,9 +429,6 @@ static void do_global_ctors(void) static void main_task(void* args) { - // Now that the application is about to start, disable boot watchdogs - REG_CLR_BIT(TIMG_WDTCONFIG0_REG(0), TIMG_WDT_FLASHBOOT_MOD_EN_S); - rtc_wdt_disable(); #if !CONFIG_FREERTOS_UNICORE // Wait for FreeRTOS initialization to finish on APP CPU, before replacing its startup stack while (port_xSchedulerRunning[1] == 0) { @@ -470,6 +469,10 @@ static void main_task(void* args) } #endif + // Now that the application is about to start, disable boot watchdog +#ifndef CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE + rtc_wdt_disable(); +#endif app_main(); vTaskDelete(NULL); } diff --git a/components/esp32/hw_random.c b/components/esp32/hw_random.c index 78ad542fc..1bd0e6300 100644 --- a/components/esp32/hw_random.c +++ b/components/esp32/hw_random.c @@ -16,6 +16,7 @@ #include #include #include +#include #include "esp_attr.h" #include "esp_clk.h" #include "soc/wdev_reg.h" @@ -54,3 +55,16 @@ uint32_t IRAM_ATTR esp_random(void) last_ccount = ccount; return result ^ REG_READ(WDEV_RND_REG); } + +void esp_fill_random(void *buf, size_t len) +{ + assert(buf != NULL); + uint8_t *buf_bytes = (uint8_t *)buf; + while (len > 0) { + uint32_t word = esp_random(); + uint32_t to_copy = MIN(sizeof(word), len); + memcpy(buf_bytes, &word, to_copy); + buf_bytes += to_copy; + len -= to_copy; + } +} diff --git a/components/esp32/include/esp_err.h b/components/esp32/include/esp_err.h index d8820e5ae..9dcb25af6 100644 --- a/components/esp32/include/esp_err.h +++ b/components/esp32/include/esp_err.h @@ -27,20 +27,20 @@ typedef int32_t esp_err_t; #define ESP_OK 0 /*!< esp_err_t value indicating success (no error) */ #define ESP_FAIL -1 /*!< Generic esp_err_t code indicating failure */ -#define ESP_ERR_NO_MEM 0x101 /*!< Out of memory */ -#define ESP_ERR_INVALID_ARG 0x102 /*!< Invalid argument */ -#define ESP_ERR_INVALID_STATE 0x103 /*!< Invalid state */ -#define ESP_ERR_INVALID_SIZE 0x104 /*!< Invalid size */ -#define ESP_ERR_NOT_FOUND 0x105 /*!< Requested resource not found */ -#define ESP_ERR_NOT_SUPPORTED 0x106 /*!< Operation or feature not supported */ -#define ESP_ERR_TIMEOUT 0x107 /*!< Operation timed out */ +#define ESP_ERR_NO_MEM 0x101 /*!< Out of memory */ +#define ESP_ERR_INVALID_ARG 0x102 /*!< Invalid argument */ +#define ESP_ERR_INVALID_STATE 0x103 /*!< Invalid state */ +#define ESP_ERR_INVALID_SIZE 0x104 /*!< Invalid size */ +#define ESP_ERR_NOT_FOUND 0x105 /*!< Requested resource not found */ +#define ESP_ERR_NOT_SUPPORTED 0x106 /*!< Operation or feature not supported */ +#define ESP_ERR_TIMEOUT 0x107 /*!< Operation timed out */ #define ESP_ERR_INVALID_RESPONSE 0x108 /*!< Received response was invalid */ -#define ESP_ERR_INVALID_CRC 0x109 /*!< CRC or checksum was invalid */ +#define ESP_ERR_INVALID_CRC 0x109 /*!< CRC or checksum was invalid */ #define ESP_ERR_INVALID_VERSION 0x10A /*!< Version was invalid */ -#define ESP_ERR_INVALID_MAC 0x10B /*!< MAC address was invalid */ +#define ESP_ERR_INVALID_MAC 0x10B /*!< MAC address was invalid */ -#define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ -#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ +#define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ +#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ /** * @brief Returns string for esp_err_t error codes diff --git a/components/esp32/include/esp_mesh.h b/components/esp32/include/esp_mesh.h index 0adb59124..6322dc602 100644 --- a/components/esp32/include/esp_mesh.h +++ b/components/esp32/include/esp_mesh.h @@ -26,7 +26,7 @@ * | | ...) | (LwIP) | | | | * | |-----------------------------------| |---------------| | * | | | | - * | | WiFi Driver | | + * | | Wi-Fi Driver | | * | |--------------------------------------------------| | * | | | * | | Platform HAL | @@ -36,7 +36,7 @@ * * |---------------| * | | default handler - * | WiFi stack | events |---------------------| + * | Wi-Fi stack | events |---------------------| * | | -------------> | | * |---------------| | | * | event task | @@ -58,27 +58,27 @@ * Mesh Stack * * Mesh event defines almost all system events applications tasks need. - * Mesh event contains WiFi connection states on station interface, children connection states on softAP interface and etc.. + * Mesh event contains Wi-Fi connection states on station interface, children connection states on softAP interface and etc.. * Applications need to register a mesh event callback handler by API esp_mesh_set_config() firstly. * This handler is to receive events posted from mesh stack and LwIP stack. * Applications could add relative handler for each event. * Examples: - * (1)Applications could use WiFi station connect states to decide when to send data to its parent, to root or to external IP network; - * (2)Applications could use WiFi softAP states to decide when to send data to its children. + * (1) Applications could use Wi-Fi station connect states to decide when to send data to its parent, to the root or to external IP network; + * (2) Applications could use Wi-Fi softAP states to decide when to send data to its children. * * In present implementation, applications are able to access mesh stack directly without having to go through LwIP stack. * Applications use esp_mesh_send() and esp_mesh_recv() to send and receive messages over the mesh network. * In mesh stack design, normal devices don't require LwIP stack. But since IDF hasn't supported system without initializing LwIP stack yet, * applications still need to do LwIP initialization and two more things are required to be done - * (1)stop DHCP server on softAP interface by default - * (2)stop DHCP client on station interface by default. + * (1) stop DHCP server on softAP interface by default + * (2) stop DHCP client on station interface by default. * Examples: * tcpip_adapter_init(); * tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); * tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); * - * Over the mesh network, only root is able to access external IP network. - * In application mesh event handler, once a device becomes a root, start DHCP client immediately if DHCP is chosen. + * Over the mesh network, only the root is able to access external IP network. + * In application mesh event handler, once a device becomes a root, start DHCP client immediately whether DHCP is chosen. */ #ifndef __ESP_MESH_H__ @@ -100,9 +100,9 @@ extern "C" { #define MESH_MTU (1500) /**< max transmit unit(in bytes) */ #define MESH_MPS (1472) /**< max payload size(in bytes) */ /** - * @brief mesh error code definition + * @brief Mesh error code definition */ -#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< WiFi isn't started */ +#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< Wi-Fi isn't started */ #define ESP_ERR_MESH_NOT_INIT (ESP_ERR_MESH_BASE + 2) /**< mesh isn't initialized */ #define ESP_ERR_MESH_NOT_CONFIG (ESP_ERR_MESH_BASE + 3) /**< mesh isn't configured */ #define ESP_ERR_MESH_NOT_START (ESP_ERR_MESH_BASE + 4) /**< mesh isn't started */ @@ -120,41 +120,41 @@ extern "C" { #define ESP_ERR_MESH_OPTION_NULL (ESP_ERR_MESH_BASE + 16) /**< no option found */ #define ESP_ERR_MESH_OPTION_UNKNOWN (ESP_ERR_MESH_BASE + 17) /**< unknown option */ #define ESP_ERR_MESH_XON_NO_WINDOW (ESP_ERR_MESH_BASE + 18) /**< no window for software flow control on upstream */ -#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level WiFi interface error */ +#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level Wi-Fi interface error */ #define ESP_ERR_MESH_DISCARD_DUPLICATE (ESP_ERR_MESH_BASE + 20) /**< discard the packet due to the duplicate sequence number */ #define ESP_ERR_MESH_DISCARD (ESP_ERR_MESH_BASE + 21) /**< discard the packet */ #define ESP_ERR_MESH_VOTING (ESP_ERR_MESH_BASE + 22) /**< vote in progress */ /** - * @brief flags used with esp_mesh_send() and esp_mesh_recv() + * @brief Flags bitmap for esp_mesh_send() and esp_mesh_recv() */ -#define MESH_DATA_ENC (0x01) /**< data encrypted(Unimplemented) */ +#define MESH_DATA_ENC (0x01) /**< data encrypted (Unimplemented) */ #define MESH_DATA_P2P (0x02) /**< point-to-point delivery over the mesh network */ #define MESH_DATA_FROMDS (0x04) /**< receive from external IP network */ #define MESH_DATA_TODS (0x08) /**< identify this packet is target to external IP network */ #define MESH_DATA_NONBLOCK (0x10) /**< esp_mesh_send() non-block */ -#define MESH_DATA_DROP (0x20) /**< in the situation of root having been changed, identify this packet can be dropped by new root */ +#define MESH_DATA_DROP (0x20) /**< in the situation of the root having been changed, identify this packet can be dropped by new root */ #define MESH_DATA_GROUP (0x40) /**< identify this packet is target to a group address */ /** - * @brief option definitions for esp_mesh_send() and esp_mesh_recv() + * @brief Option definitions for esp_mesh_send() and esp_mesh_recv() */ #define MESH_OPT_SEND_GROUP (7) /**< data transmission by group; used with esp_mesh_send() and shall have payload */ #define MESH_OPT_RECV_DS_ADDR (8) /**< return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() */ /** - * @brief flag of mesh networking IE + * @brief Flag of mesh networking IE */ #define MESH_ASSOC_FLAG_VOTE_IN_PROGRESS (0x02) /**< vote in progress */ #define MESH_ASSOC_FLAG_NETWORK_FREE (0x08) /**< no root in current network */ #define MESH_ASSOC_FLAG_ROOTS_FOUND (0x20) /**< root conflict is found */ -#define MESH_ASSOC_FLAG_ROOT_FIXED (0x40) /**< root is fixed */ +#define MESH_ASSOC_FLAG_ROOT_FIXED (0x40) /**< fixed root */ /******************************************************* * Enumerations *******************************************************/ /** - * @brief enumerated list of mesh event id + * @brief Enumerated list of mesh event id */ typedef enum { MESH_EVENT_STARTED, /**< mesh is started */ @@ -168,28 +168,28 @@ typedef enum { MESH_EVENT_PARENT_DISCONNECTED, /**< parent is disconnected on station interface */ MESH_EVENT_NO_PARENT_FOUND, /**< no parent found */ MESH_EVENT_LAYER_CHANGE, /**< layer changes over the mesh network */ - MESH_EVENT_TODS_STATE, /**< state represents if root is able to access external IP network */ - MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by root */ + MESH_EVENT_TODS_STATE, /**< state represents whether the root is able to access external IP network */ + MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by the root */ MESH_EVENT_VOTE_STOPPED, /**< the process of voting a new root is stopped */ MESH_EVENT_ROOT_ADDRESS, /**< the root address is obtained. It is posted by mesh stack automatically. */ MESH_EVENT_ROOT_SWITCH_REQ, /**< root switch request sent from a new voted root candidate */ MESH_EVENT_ROOT_SWITCH_ACK, /**< root switch acknowledgment responds the above request sent from current root */ - MESH_EVENT_ROOT_GOT_IP, /**< root obtains the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_LOST_IP, /**< root loses the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_ASKED_YIELD, /**< root is asked yield by a more powerful existing root. If self organized is disabled + MESH_EVENT_ROOT_GOT_IP, /**< the root obtains the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_LOST_IP, /**< the root loses the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_ASKED_YIELD, /**< the root is asked yield by a more powerful existing root. If self organized is disabled and this device is specified to be a root by users, users should set a new parent for this device. if self organized is enabled, this device will find a new parent by itself, users could ignore this event. */ MESH_EVENT_ROOT_FIXED, /**< when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. - Fixed Root setting of each device is variable as that setting changes of root. */ + Fixed Root Setting of each device is variable as that setting changes of the root. */ MESH_EVENT_SCAN_DONE, /**< if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event. */ MESH_EVENT_MAX, } mesh_event_id_t; /** - * @brief device type + * @brief Device type */ typedef enum { MESH_IDLE, /**< hasn't joined the mesh network yet */ @@ -199,7 +199,7 @@ typedef enum { } mesh_type_t; /** - * @brief protocol of transmitted application data + * @brief Protocol of transmitted application data */ typedef enum { MESH_PROTO_BIN, /**< binary */ @@ -209,24 +209,24 @@ typedef enum { } mesh_proto_t; /** - * @brief for reliable transmission, mesh stack provides three type of services + * @brief For reliable transmission, mesh stack provides three type of services */ typedef enum { - MESH_TOS_P2P, /**< provide P2P(point-to-point) retransmission on mesh stack by default */ - MESH_TOS_E2E, /**< provide E2E(end-to-end) retransmission on mesh stack (Unimplemented) */ + MESH_TOS_P2P, /**< provide P2P (point-to-point) retransmission on mesh stack by default */ + MESH_TOS_E2E, /**< provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) */ MESH_TOS_DEF, /**< no retransmission on mesh stack */ } mesh_tos_t; /** - * @brief vote reason + * @brief Vote reason */ typedef enum { - MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by root */ + MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by the root */ MESH_VOTE_REASON_CHILD_INITIATED, /**< vote is initiated by children */ } mesh_vote_reason_t; /** - * @brief mesh disconnect reason code + * @brief Mesh disconnect reason code */ typedef enum { MESH_REASON_CYCLIC = 100, /**< cyclic is detected */ @@ -250,7 +250,7 @@ typedef struct { } __attribute__((packed)) mip_t; /** - * @brief mesh address + * @brief Mesh address */ typedef union { uint8_t addr[6]; /**< mac address */ @@ -258,47 +258,47 @@ typedef union { } mesh_addr_t; /** - * @brief channel switch information + * @brief Channel switch information */ typedef struct { uint8_t channel; /**< new channel */ } mesh_event_channel_switch_t; /** - * @brief parent connected information + * @brief Parent connected information */ typedef struct { - system_event_sta_connected_t connected; /**< parent information, same as WiFi event SYSTEM_EVENT_STA_CONNECTED does */ + system_event_sta_connected_t connected; /**< parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does */ uint8_t self_layer; /**< layer */ } mesh_event_connected_t; /** - * @brief no parent found information + * @brief No parent found information */ typedef struct { int scan_times; /**< scan times being through */ } mesh_event_no_parent_found_t; /** - * @brief layer change information + * @brief Layer change information */ typedef struct { uint8_t new_layer; /**< new layer */ } mesh_event_layer_change_t; /** - * @brief the reachability of root to a DS(distribute system) + * @brief The reachability of the root to a DS (distribute system) */ typedef enum { - MESH_TODS_UNREACHABLE, /**< root isn't able to access external IP network */ - MESH_TODS_REACHABLE, /**< root is able to access external IP network */ + MESH_TODS_UNREACHABLE, /**< the root isn't able to access external IP network */ + MESH_TODS_REACHABLE, /**< the root is able to access external IP network */ } mesh_event_toDS_state_t; /** * @brief vote started information */ typedef struct { - int reason; /**< vote reason, vote could be initiated by children or by root itself */ + int reason; /**< vote reason, vote could be initiated by children or by the root itself */ int attempts; /**< max vote attempts before stopped */ mesh_addr_t rc_addr; /**< root address specified by users via API esp_mesh_waive_root() */ } mesh_event_vote_started_t; @@ -309,27 +309,27 @@ typedef struct { typedef system_event_sta_got_ip_t mesh_event_root_got_ip_t; /** - * @brief root address + * @brief Root address */ typedef mesh_addr_t mesh_event_root_address_t; /** - * @brief parent disconnected information + * @brief Parent disconnected information */ typedef system_event_sta_disconnected_t mesh_event_disconnected_t; /** - * @brief child connected information + * @brief Child connected information */ typedef system_event_ap_staconnected_t mesh_event_child_connected_t; /** - * @brief child disconnected information + * @brief Child disconnected information */ typedef system_event_ap_stadisconnected_t mesh_event_child_disconnected_t; /** - * @brief root switch request information + * @brief Root switch request information */ typedef struct { int reason; /**< root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() */ @@ -337,7 +337,7 @@ typedef struct { } mesh_event_root_switch_req_t; /** - * @brief other powerful root address + * @brief Other powerful root address */ typedef struct { int8_t rssi; /**< rssi with router */ @@ -346,7 +346,7 @@ typedef struct { } mesh_event_root_conflict_t; /** - * @brief routing table change + * @brief Routing table change */ typedef struct { uint16_t rt_size_new; /**< the new value */ @@ -354,21 +354,21 @@ typedef struct { } mesh_event_routing_table_change_t; /** - * @brief root fixed + * @brief Root fixed */ typedef struct { bool is_fixed; /**< status */ } mesh_event_root_fixed_t; /** - * @brief scan done event information + * @brief Scan done event information */ typedef struct { - uint8_t number; /**< the number of scanned APs */ + uint8_t number; /**< the number of APs scanned */ } mesh_event_scan_done_t; /** - * @brief mesh event information + * @brief Mesh event information */ typedef union { mesh_event_channel_switch_t channel_switch; /**< channel switch */ @@ -380,7 +380,7 @@ typedef union { mesh_event_no_parent_found_t no_parent; /**< no parent found */ mesh_event_layer_change_t layer_change; /**< layer change */ mesh_event_toDS_state_t toDS_state; /**< toDS state, devices shall check this state firstly before trying to send packets to - external IP network. This state indicates right now if root is capable of sending + external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices had better to wait until this state changes to be MESH_TODS_REACHABLE. */ mesh_event_vote_started_t vote_started; /**< vote started */ @@ -388,12 +388,12 @@ typedef union { mesh_event_root_address_t root_addr; /**< root address */ mesh_event_root_switch_req_t switch_req; /**< root switch request */ mesh_event_root_conflict_t root_conflict; /**< other powerful root */ - mesh_event_root_fixed_t root_fixed; /**< root fixed */ + mesh_event_root_fixed_t root_fixed; /**< fixed root */ mesh_event_scan_done_t scan_done; /**< scan done */ } mesh_event_info_t; /** - * @brief mesh event + * @brief Mesh event */ typedef struct { mesh_event_id_t id; /**< mesh event id */ @@ -401,14 +401,14 @@ typedef struct { } mesh_event_t; /** - * @brief mesh event callback handler prototype definition + * @brief Mesh event callback handler prototype definition * * @param event mesh_event_t */ typedef void (*mesh_event_cb_t)(mesh_event_t event); /** - * @brief mesh option + * @brief Mesh option */ typedef struct { uint8_t type; /**< option type */ @@ -417,7 +417,7 @@ typedef struct { } __attribute__((packed)) mesh_opt_t; /** - * @brief mesh data for esp_mesh_send() and esp_mesh_recv() + * @brief Mesh data for esp_mesh_send() and esp_mesh_recv() */ typedef struct { uint8_t *data; /**< data */ @@ -427,7 +427,7 @@ typedef struct { } mesh_data_t; /** - * @brief router configuration + * @brief Router configuration */ typedef struct { uint8_t ssid[32]; /**< SSID */ @@ -437,7 +437,7 @@ typedef struct { } mesh_router_t; /** - * @brief mesh softAP configuration + * @brief Mesh softAP configuration */ typedef struct { uint8_t password[64]; /**< mesh softAP password */ @@ -445,7 +445,7 @@ typedef struct { } mesh_ap_cfg_t; /** - * @brief mesh initialization configuration + * @brief Mesh initialization configuration */ typedef struct { uint8_t channel; /**< channel, the mesh network on */ @@ -457,7 +457,7 @@ typedef struct { } mesh_cfg_t; /** - * @brief vote address configuration + * @brief Vote address configuration */ typedef union { int attempts; /**< max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) */ @@ -465,29 +465,29 @@ typedef union { } mesh_rc_config_t; /** - * @brief vote + * @brief Vote */ typedef struct { float percentage; /**< vote percentage threshold for approval of being a root */ - bool is_rc_specified; /**< if true, rc_addr shall be specified(Unimplemented). + bool is_rc_specified; /**< if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election. */ mesh_rc_config_t config; /**< vote address configuration */ } mesh_vote_t; /** - * @brief the number of packets pending in the queue waiting to be sent by the mesh stack + * @brief The number of packets pending in the queue waiting to be sent by the mesh stack */ typedef struct { int to_parent; /**< to parent queue */ - int to_parent_p2p; /**< to parent(P2P) queue */ + int to_parent_p2p; /**< to parent (P2P) queue */ int to_child; /**< to child queue */ - int to_child_p2p; /**< to child(P2P) queue */ + int to_child_p2p; /**< to child (P2P) queue */ int mgmt; /**< management queue */ int broadcast; /**< broadcast and multicast queue */ } mesh_tx_pending_t; /** - * @brief the number of packets available in the queue waiting to be received by applications + * @brief The number of packets available in the queue waiting to be received by applications */ typedef struct { int toDS; /**< to external DS */ @@ -497,7 +497,7 @@ typedef struct { /******************************************************* * Variable Declaration *******************************************************/ -/* mesh vendor IE crypto callback function */ +/* mesh IE crypto callback function */ extern const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs; /* mesh event callback handler */ @@ -511,11 +511,11 @@ extern mesh_event_cb_t g_mesh_event_cb; * Function Definitions *******************************************************/ /** - * @brief mesh initialization - * Check if WiFi is started. - * Initialize mesh global variables with default values. + * @brief Mesh initialization + * - Check whether Wi-Fi is started. + * - Initialize mesh global variables with default values. * - * @attention This API shall be called after WiFi is started. + * @attention This API shall be called after Wi-Fi is started. * * @return * - ESP_OK @@ -524,8 +524,9 @@ extern mesh_event_cb_t g_mesh_event_cb; esp_err_t esp_mesh_init(void); /** - * @brief mesh de-initialization - * Release resources and stop the mesh + * @brief Mesh de-initialization + * + * - Release resources and stop the mesh * * @return * - ESP_OK @@ -534,13 +535,13 @@ esp_err_t esp_mesh_init(void); esp_err_t esp_mesh_deinit(void); /** - * @brief start mesh - * Initialize mesh vendor IE - * Start mesh network management service - * Create TX and RX queues according to the configuration - * Register mesh packets receive callback + * @brief Start mesh + * - Initialize mesh IE. + * - Start mesh network management service. + * - Create TX and RX queues according to the configuration. + * - Register mesh packets receive callback. * - * @attention This API shall be called after esp_mesh_init() and esp_mesh_set_config(). + * @attention This API shall be called after esp_mesh_init() and esp_mesh_set_config(). * * @return * - ESP_OK @@ -552,15 +553,15 @@ esp_err_t esp_mesh_deinit(void); esp_err_t esp_mesh_start(void); /** - * @brief stop mesh - * Deinitialize mesh vendor IE - * Disconnect with current parent - * Disassociate all currently associated children - * Stop mesh network management service - * Unregister mesh packets receive callback - * Delete TX and RX queues - * Release resources - * Restore WiFi softAP to default settings if WiFi dual mode is enabled + * @brief Stop mesh + * - Deinitialize mesh IE. + * - Disconnect with current parent. + * - Disassociate all currently associated children. + * - Stop mesh network management service. + * - Unregister mesh packets receive callback. + * - Delete TX and RX queues. + * - Release resources. + * - Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. * * @return * - ESP_OK @@ -569,40 +570,42 @@ esp_err_t esp_mesh_start(void); esp_err_t esp_mesh_stop(void); /** - * @brief send a packet over the mesh network - * Send a packet to any device in the mesh network. - * Send a packet to external IP network. + * @brief Send a packet over the mesh network + * - Send a packet to any device in the mesh network. + * - Send a packet to external IP network. * - * @attention This API is not reentrant. + * @attention This API is not reentrant. * - * @param to the address of the final destination of the packet - * (1)if the packet is to root, just set "to" to NULL and set flag to zero. - * (2)if the packet is outgoing to external IP network such as an IP server address, translate IPv4:PORT known as "to". - * This packet will be delivered to root firstly, then root will forward this packet to the final IP server address. - * @param data pointer to a sending mesh packet - * Should specify the data protocol applications used, binary by default. - * Should specify the transmission tos(type of service), P2P reliable by default. - * @param flag - * (1)used to speed up the route selection - * if the packet is target to an internal device, MESH_DATA_P2P should be set. - * if the packet is outgoing to root or to external IP network, MESH_DATA_TODS should be set. - * if the packet is from root to an internal device, MESH_DATA_FROMDS should be set. - * (2)specify if this API is block or non-block, block by default - * if needs non-block, MESH_DATA_NONBLOCK should be set. - * (3)in the situation of root having been changed, MESH_DATA_DROP identifies this packet can be dropped by new root - * for upstream data to external IP network, we try our best to avoid data loss caused by root having been changed, but - * there is a risk that new root is running out of memory because most of memory is occupied by the pending data which - * isn't read out in time by esp_mesh_recv_toDS(). - * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing - * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * @param[in] to the address of the final destination of the packet + * - If the packet is to the root, set this parameter to NULL. + * - If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. + * This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. + * @param[in] data pointer to a sending mesh packet + * - Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). + * - Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). + * @param[in] flag bitmap for data sent + * - Speed up the route search + * - If the packet is to the root and "to" parameter is NULL, set this parameter to 0. + * - If the packet is to an internal device, MESH_DATA_P2P should be set. + * - If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. + * - If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. + * - Specify whether this API is block or non-block, block by default + * - If needs non-block, MESH_DATA_NONBLOCK should be set. + * - In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root + * for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but + * there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which + * isn't read out in time by esp_mesh_recv_toDS(). * - * @param opt options - * (1)in case of sending a packet to a specified group, MESH_OPT_SEND_GROUP is a good choice. - * In this option, the value field should specify the target receiver addresses in this group. - * (2)root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds - * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. - * @param opt_count option count - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing + * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * + * @param[in] opt options + * - In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. + * In this option, the value field should be set to the target receiver addresses in this group. + * - Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds + * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. + * @param[in] opt_count option count + * - Currently, this API only takes one option, so opt_count is only supported to be 1. * * @return * - ESP_OK @@ -622,21 +625,26 @@ esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[], int opt_count); /** - * @brief receive a packet targeted to self over the mesh network - * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting - * to be received by applications in case of running out of memory. + * @brief Receive a packet targeted to self over the mesh network * - * @param from the address of the original source of the packet - * @param data pointer to the received mesh packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_FROMDS represents data from external IP network - * MESH_DATA_TODS represents data directed upward within the mesh network - * @param opt options desired to receive - * MESH_OPT_RECV_DS_ADDR attaches the DS address - * @param opt_count option count desired to receive - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * @attention Mesh RX queue should be checked regularly to avoid running out of memory. + * - Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications. + * + * @param[out] from the address of the original source of the packet + * @param[out] data pointer to the received mesh packet + * - Field proto is the data protocol in use. Should follow it to parse the received data. + * - Field tos is the transmission tos (type of service) in use. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_FROMDS represents data from external IP network + * - MESH_DATA_TODS represents data directed upward within the mesh network + * + * flag could be MESH_DATA_FROMDS or MESH_DATA_TODS. + * @param[out] opt options desired to receive + * - MESH_OPT_RECV_DS_ADDR attaches the DS address + * @param[in] opt_count option count desired to receive + * - Currently, this API only takes one option, so opt_count is only supported to be 1. * * @return * - ESP_OK @@ -649,29 +657,33 @@ esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count); /** - * @brief receive a packet targeted to external IP network - * root uses this API to receive packets destined to external IP network - * root forwards the received packets to the final destination via socket. - * if no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() - * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. - * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting - * to be received by applications in case of running out of memory in root. - * Use esp_mesh_set_xon_qsize() could configure the RX queue size, default:72. If this size is too large, - * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied - * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to - * decide this value depends on the specific application scenarios. + * @brief Receive a packet targeted to external IP network + * - Root uses this API to receive packets destined to external IP network + * - Root forwards the received packets to the final destination via socket. + * - If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() + * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. * - * @attention This API is only called by root. + * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications in case of running out of memory in the root. * - * @param from the address of the original source of the packet - * @param to the address contains remote IP address and port(IPv4:PORT) - * @param data pointer to the received packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_TODS represents data to external IP network - * @param opt options desired to receive - * @param opt_count option count desired to receive + * Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large, + * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied + * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to + * decide this value depends on the specific application scenarios. + * + * @attention This API is only called by the root. + * + * @param[out] from the address of the original source of the packet + * @param[out] to the address contains remote IP address and port (IPv4:PORT) + * @param[out] data pointer to the received packet + * - Contain the protocol and applications should follow it to parse the data. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. + * + * flag could be MESH_DATA_TODS. + * @param[out] opt options desired to receive + * @param[in] opt_count option count desired to receive * * @return * - ESP_OK @@ -685,24 +697,26 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, int opt_count); /** - * @brief set mesh stack configuration - * Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh vendor IE is encrypted by default. - * mesh network is established on a fixed channel(1-14). - * mesh event callback is mandatory. - * mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. - * Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. - * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more - * roots than one connected with different BSSID will appear. It means more than one mesh network is established - * with the same mesh ID. - * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots - * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID - * for the future replacement. But in that case, if the above situations happen, please make sure applications - * implement forward functions on root to guarantee devices in different mesh network can communicate with each other. - * max_connection of mesh softAP is limited by the max number of WiFi softAP supported(max:10). + * @brief Set mesh stack configuration + * - Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. + * - Mesh network is established on a fixed channel (1-14). + * - Mesh event callback is mandatory. + * - Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. + * - Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. * - * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more + * roots than one connected with different BSSID will appear. It means more than one mesh network is established + * with the same mesh ID. * - * @param config pointer to mesh stack configuration + * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots + * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID + * for the future replacement. But in that case, if the above situations happen, please make sure applications + * implement forward functions on the root to guarantee devices in different mesh network can communicate with each other. + * max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10). + * + * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * + * @param[in] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -712,9 +726,9 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); /** - * @brief get mesh stack configuration + * @brief Get mesh stack configuration * - * @param config pointer to mesh stack configuration + * @param[out] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -723,11 +737,11 @@ esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); esp_err_t esp_mesh_get_config(mesh_cfg_t *config); /** - * @brief set router configuration + * @brief Get router configuration * - * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). * - * @param router pointer to router configuration + * @param[in] router pointer to router configuration * * @return * - ESP_OK @@ -736,9 +750,9 @@ esp_err_t esp_mesh_get_config(mesh_cfg_t *config); esp_err_t esp_mesh_set_router(const mesh_router_t *router); /** - * @brief get router configuration + * @brief Get router configuration * - * @param router pointer to router configuration + * @param[out] router pointer to router configuration * * @return * - ESP_OK @@ -747,11 +761,11 @@ esp_err_t esp_mesh_set_router(const mesh_router_t *router); esp_err_t esp_mesh_get_router(mesh_router_t *router); /** - * @brief set mesh network ID + * @brief Set mesh network ID * - * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). + * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). * - * @param id pointer to mesh network ID + * @param[in] id pointer to mesh network ID * * @return * - ESP_OK @@ -760,9 +774,9 @@ esp_err_t esp_mesh_get_router(mesh_router_t *router); esp_err_t esp_mesh_set_id(const mesh_addr_t *id); /** - * @brief get mesh network ID + * @brief Get mesh network ID * - * @param id pointer to mesh network ID + * @param[out] id pointer to mesh network ID * * @return * - ESP_OK @@ -771,13 +785,9 @@ esp_err_t esp_mesh_set_id(const mesh_addr_t *id); esp_err_t esp_mesh_get_id(mesh_addr_t *id); /** - * @brief specify device type over the mesh network - * - MESH_ROOT: designates the root node for a mesh network - * - MESH_LEAF: designates a device as a standalone Wi-Fi station + * @brief Designate device type over the mesh network * - * @attention This API shall be called before esp_mesh_start(). - * - * @param type device type (only support MESH_ROOT, MESH_LEAF) + * @param[in] type device type * * @return * - ESP_OK @@ -786,19 +796,22 @@ esp_err_t esp_mesh_get_id(mesh_addr_t *id); esp_err_t esp_mesh_set_type(mesh_type_t type); /** - * @brief get device type over the mesh network + * @brief Get device type over mesh network * - * @return mesh type + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @return mesh type * */ mesh_type_t esp_mesh_get_type(void); /** - * @brief set max layer configuration(max:25, default:25) + * @brief Set network max layer value (max:25, default:15) + * - Network max layer limits the max hop count. * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param max_layer max layer value + * @param[in] max_layer max layer value * * @return * - ESP_OK @@ -808,19 +821,19 @@ mesh_type_t esp_mesh_get_type(void); esp_err_t esp_mesh_set_max_layer(int max_layer); /** - * @brief get max layer configuration + * @brief Get max layer value * - * @return max layer value + * @return max layer value */ int esp_mesh_get_max_layer(void); /** - * @brief set mesh softAP password + * @brief Set mesh softAP password * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param pwd pointer to the password - * @param len password length + * @param[in] pwd pointer to the password + * @param[in] len password length * * @return * - ESP_OK @@ -830,11 +843,11 @@ int esp_mesh_get_max_layer(void); esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); /** - * @brief set mesh softAP authentication mode value + * @brief Set mesh softAP authentication mode * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param authmode authentication mode + * @param[in] authmode authentication mode * * @return * - ESP_OK @@ -844,19 +857,18 @@ esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode); /** - * @brief get mesh softAP authentication mode - * - * @return authentication mode + * @brief Get mesh softAP authentication mode * + * @return authentication mode */ wifi_auth_mode_t esp_mesh_get_ap_authmode(void); /** - * @brief set mesh softAP max connection value + * @brief Set mesh softAP max connection value * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param connections the number of max connections + * @param[in] connections the number of max connections * * @return * - ESP_OK @@ -865,29 +877,28 @@ wifi_auth_mode_t esp_mesh_get_ap_authmode(void); esp_err_t esp_mesh_set_ap_connections(int connections); /** - * @brief get mesh softAP max connection configuration - * - * @return the number of max connections + * @brief Get mesh softAP max connection configuration * + * @return the number of max connections */ int esp_mesh_get_ap_connections(void); /** - * @brief get current layer value over the mesh network + * @brief Get current layer value over the mesh network * - * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @return layer value + * @return layer value * */ int esp_mesh_get_layer(void); /** - * @brief get parent BSSID + * @brief Get the parent BSSID * - * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @param bssid pointer to parent BSSID + * @param[out] bssid pointer to parent BSSID * * @return * - ESP_OK @@ -896,22 +907,22 @@ int esp_mesh_get_layer(void); esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid); /** - * @brief return if the device is root - * - * @return true/false + * @brief Return whether the device is the root node of the network * + * @return true/false */ bool esp_mesh_is_root(void); /** - * @brief enable/disable mesh networking self-organized, self-organized by default - * if self-organized is disabled, users should set a parent for this device via - * esp_mesh_set_parent(); + * @brief Enable/disable mesh networking self-organized, self-organized by default + * - If self-organized is disabled, users shall set a parent for the device via + * esp_mesh_set_parent(); * - * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). + * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). * - * @param enable enable or disable self-organized networking - * @param select_parent if enable self-organized networking, let the device select a new parent or + * @param[in] enable enable or disable self-organized networking + * @param[in] select_parent + * - If self-organized networking is enabled, let the device search for a new parent or * keep connecting to the previous parent. * * @return @@ -921,35 +932,36 @@ bool esp_mesh_is_root(void); esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent); /** - * @brief return if mesh networking is self-organized or not - * - * @return true/false + * @brief Return whether enable self-organized networking or not * + * @return true/false */ bool esp_mesh_get_self_organized(void); /** - * @brief root waive itself - * A device is elected to be a root during the networking mostly because it has a strong RSSI with router. - * If such superior conditions change, users could call this API to perform a root switch. + * @brief Cause the root device to give up (waive) its mesh root status + * - A device is elected root primarily based on RSSI from the external router. + * - If external router conditions change, users can call this API to perform a root switch. + * - In this API, users could specify a desired root address to replace itself or specify an attempts value + * to ask current root to initiate a new round of voting. During the voting, a better root candidate would + * be expected to find to replace the current one. + * - If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better + * root candidate is found, keep the current one. If a better candidate is found, the new better one will + * send a root switch request to the current root, current root will respond with a root switch acknowledgment. + * - After that, the new candidate will connect to the router to be a new root, the previous root will disconnect + * with the router and choose another parent instead. * - * In this API, users could specify a desired root address to replace itself or specify an attempts value - * to ask current root to initiate a new round of voting. During the voting, a better root candidate would - * be expected to find to replace the current one. - * If no desired root candidate, the vote will try a specified attempts(at least 10 times), if no better - * root candidate is found, keep the current one. If a better candidate is found, the new better one will - * send a root switch request to the current root, current root will respond with a root switch acknowledgment. - * After that, the new candidate will connect to the router to be a new root, the previous root will disconnect - * with the router and choose another parent instead. - * So far, root switch is completed with minimal disruption to the whole mesh network. + * Root switch is completed with minimal disruption to the whole mesh network. * - * @attention This API is only called by root. + * @attention This API is only called by the root. * - * @param vote vote configuration - * Specify a desired root address(Unimplemented) - * Attempts should be at least 10 times. - * if "vote" is set NULL, the vote will perform the default 10 times. - * @param reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now + * @param[in] vote vote configuration + * - If this parameter is set NULL, the vote will perform the default 15 times. + * + * - Field percentage threshold is 0.9 by default. + * - Field is_rc_specified shall be false. + * - Field attempts shall be at least 15 times. + * @param[in] reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now * * @return * - ESP_OK @@ -960,13 +972,13 @@ bool esp_mesh_get_self_organized(void); esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason); /** - * @brief set vote percentage threshold for approval of being a root - * During the networking, only obtaining vote percentage reaches this threshold, - * the device could be a root. + * @brief Set vote percentage threshold for approval of being a root + * - During the networking, only obtaining vote percentage reaches this threshold, + * the device could be a root. * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param percentage vote percentage threshold + * @param[in] percentage vote percentage threshold * * @return * - ESP_OK @@ -975,18 +987,18 @@ esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason); esp_err_t esp_mesh_set_vote_percentage(float percentage); /** - * @brief get vote percentage threshold for approval of being a root + * @brief Get vote percentage threshold for approval of being a root * - * @return percentage threshold + * @return percentage threshold */ float esp_mesh_get_vote_percentage(void); /** - * @brief set mesh softAP associate expired time - * If mesh softAP hasn't received any data from an associated child within this time, - * mesh softAP will take this child inactive and disassociate it. + * @brief Set mesh softAP associate expired time + * - If mesh softAP hasn't received any data from an associated child within this time, + * mesh softAP will take this child inactive and disassociate it. * - * @param seconds + * @param[in] seconds the expired time * * @return * - ESP_OK @@ -995,34 +1007,34 @@ float esp_mesh_get_vote_percentage(void); esp_err_t esp_mesh_set_ap_assoc_expire(int seconds); /** - * @brief get mesh softAP associate expired time + * @brief Get mesh softAP associate expired time * - * @return seconds + * @return seconds */ int esp_mesh_get_ap_assoc_expire(void); /** - * @brief get total number of devices in current network(including root) + * @brief Get total number of devices in current network (including the root) * - * @attention The returned value might be incorrect when the network is changing. + * @attention The returned value might be incorrect when the network is changing. ** - * @return total number of devices(including root) + * @return total number of devices (including the root) */ int esp_mesh_get_total_node_num(void); /** - * @brief get the number of devices in this device's sub-network(including self) + * @brief Get the number of devices in this device's sub-network (including self) * - * @return the number of devices over this device's sub-network(including self) + * @return the number of devices over this device's sub-network (including self) */ int esp_mesh_get_routing_table_size(void); /** - * @brief get routing table of this device's sub-network(including itself) + * @brief Get routing table of this device's sub-network (including itself) * - * @param mac pointer to routing table - * @param len routing table size(in bytes) - * @param size pointer to the number of devices in routing table(including itself) + * @param[out] mac pointer to routing table + * @param[in] len routing table size(in bytes) + * @param[out] size pointer to the number of devices in routing table (including itself) * * @return * - ESP_OK @@ -1031,11 +1043,11 @@ int esp_mesh_get_routing_table_size(void); esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); /** - * @brief post the toDS state to the mesh stack + * @brief Post the toDS state to the mesh stack * - * @attention This API is only for root. + * @attention This API is only for the root. * - * @param reachable this state represents if root is able to access external IP network + * @param[in] reachable this state represents whether the root is able to access external IP network * * @return * - ESP_OK @@ -1044,9 +1056,9 @@ esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); esp_err_t esp_mesh_post_toDS_state(bool reachable); /** - * @brief return the number of packets pending in the queue waiting to be sent by the mesh stack + * @brief Return the number of packets pending in the queue waiting to be sent by the mesh stack * - * @param pending pointer to the TX pending + * @param[out] pending pointer to the TX pending * * @return * - ESP_OK @@ -1055,9 +1067,9 @@ esp_err_t esp_mesh_post_toDS_state(bool reachable); esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); /** - * @brief return the number of packets available in the queue waiting to be received by applications + * @brief Return the number of packets available in the queue waiting to be received by applications * - * @param pending pointer to the RX pending + * @param[out] pending pointer to the RX pending * * @return * - ESP_OK @@ -1066,21 +1078,21 @@ esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending); /** - * @brief return the number of packets could be accepted from the specified address + * @brief Return the number of packets could be accepted from the specified address * - * @param addr self address or an associate children address - * @param xseqno_in sequence number of the last received packet from the specified address + * @param[in] addr self address or an associate children address + * @param[out] xseqno_in sequence number of the last received packet from the specified address * - * @return the number of upQ for a specified address + * @return the number of upQ for a certain address */ int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); /** - * @brief set queue size + * @brief Set the number of queue * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param qsize default:32(min:16) + * @param[in] qsize default:32 (min:16) * * @return * - ESP_OK @@ -1089,16 +1101,16 @@ int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); esp_err_t esp_mesh_set_xon_qsize(int qsize); /** - * @brief get queue size + * @brief Get queue size * - * @return qsize + * @return the number of queue */ int esp_mesh_get_xon_qsize(void); /** - * @brief set if allow more than one root existing in one network + * @brief Set whether allow more than one root existing in one network * - * @param allowed allow or not + * @param[in] allowed allow or not * * @return * - ESP_OK @@ -1108,17 +1120,17 @@ int esp_mesh_get_xon_qsize(void); esp_err_t esp_mesh_allow_root_conflicts(bool allowed); /** - * @brief check if allow more than one root to exist in one network + * @brief Check whether allow more than one root to exist in one network * - * @return true/false + * @return true/false */ bool esp_mesh_is_root_conflicts_allowed(void); /** - * @brief set group ID addresses + * @brief Set group ID addresses * - * @param addr pointer to new group ID addresses - * @param num the number of group ID addresses + * @param[in] addr pointer to new group ID addresses + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1127,10 +1139,10 @@ bool esp_mesh_is_root_conflicts_allowed(void); esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); /** - * @brief delete group ID addresses + * @brief Delete group ID addresses * - * @param addr pointer to deleted group ID address - * @param num the number of group ID addresses + * @param[in] addr pointer to deleted group ID address + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1139,17 +1151,17 @@ esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num); /** - * @brief get the number of group ID addresses + * @brief Get the number of group ID addresses * - * @return the number of group ID addresses + * @return the number of group ID addresses */ int esp_mesh_get_group_num(void); /** - * @brief get group ID addresses + * @brief Get group ID addresses * - * @param addr pointer to group ID addresses - * @param num the number of group ID addresses + * @param[out] addr pointer to group ID addresses + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1158,18 +1170,18 @@ int esp_mesh_get_group_num(void); esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num); /** - * @brief check if the specified group address is my group + * @brief Check whether the specified group address is my group * - * @return true/false + * @return true/false */ bool esp_mesh_is_my_group(const mesh_addr_t *addr); /** - * @brief set mesh network capacity + * @brief Set mesh network capacity * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param num mesh network capacity + * @param[in] num mesh network capacity * * @return * - ESP_OK @@ -1179,16 +1191,16 @@ bool esp_mesh_is_my_group(const mesh_addr_t *addr); esp_err_t esp_mesh_set_capacity_num(int num); /** - * @brief get mesh network capacity + * @brief Get mesh network capacity * - * @return mesh network capacity + * @return mesh network capacity */ int esp_mesh_get_capacity_num(void); /** - * @brief set mesh ie crypto functions + * @brief Set mesh IE crypto functions * - * @param crypto_funcs crypto functions for mesh ie + * @param[in] crypto_funcs crypto functions for mesh IE * * @return * - ESP_OK @@ -1196,12 +1208,12 @@ int esp_mesh_get_capacity_num(void); esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); /** - * @brief set mesh ie crypto key + * @brief Set mesh IE crypto key * - * @attention This API shall be called after esp_mesh_set_config() and before esp_mesh_start(). + * @attention This API shall be called after esp_mesh_set_config() and before esp_mesh_start(). * - * @param key ASCII crypto key - * @param len length in bytes, range:8~64 + * @param[in] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 * * @return * - ESP_OK @@ -1212,10 +1224,10 @@ esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); /** - * @brief get mesh ie crypto key + * @brief Get mesh IE crypto key * - * @param key ASCII crypto key - * @param len length in bytes, range:8~64 + * @param[out] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 * * @return * - ESP_OK @@ -1224,9 +1236,9 @@ esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); /** - * @brief set delay time before starting root healing + * @brief Set delay time before network starts root healing * - * @param delay_ms delay time in milliseconds + * @param[in] delay_ms delay time in milliseconds * * @return * - ESP_OK @@ -1234,16 +1246,16 @@ esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); esp_err_t esp_mesh_set_root_healing_delay(int delay_ms); /** - * @brief get delay time before starting root healing + * @brief Get delay time before network starts root healing * - * @return delay time in milliseconds + * @return delay time in milliseconds */ int esp_mesh_get_root_healing_delay(void); /** - * @brief set mesh event callback + * @brief Set mesh event callback * - * @param event_cb mesh event call back + * @param[in] event_cb mesh event call back * * @return * - ESP_OK @@ -1251,11 +1263,12 @@ int esp_mesh_get_root_healing_delay(void); esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); /** - * @brief set Fixed Root setting for the device - * If Fixed Root setting of the device is enabled, it won't compete to be a root. - * If a scenario needs a fixed root, all devices in this network shall enable this setting. + * @brief Enable network Fixed Root Setting + * - Enabling fixed root disables automatic election of the root node via voting. + * - All devices in the network shall use the same Fixed Root Setting (enabled or disabled). + * - If Fixed Root is enabled, users should make sure a root node is designated for the network. * - * @param enable enable or not + * @param[in] enable enable or not * * @return * - ESP_OK @@ -1263,21 +1276,21 @@ esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); esp_err_t esp_mesh_fix_root(bool enable); /** - * @brief check if Fixed Root setting is enabled - * Fixed Root setting can be changed by API esp_mesh_fix_root(). - * Fixed Root setting can also be changed by event MESH_EVENT_ROOT_FIXED. + * @brief Check whether network Fixed Root Setting is enabled + * - Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). + * - Network Fixed Root Setting also changes with the "flag" value in parent networking IE. * - * @return true/false + * @return true/false */ bool esp_mesh_is_root_fixed(void); /** - * @brief set a specified parent + * @brief Specify a parent for the device * - * @param parent parent configuration, the ssid and the channel of the parent are mandatory. - * @param parent_mesh_id parent mesh ID, if not set, use the device default one. - * @param my_type my mesh type - * @param my_layer my mesh layer + * @param[in] parent parent configuration, the SSID and the channel of the parent are mandatory. + * @param[in] parent_mesh_id parent mesh ID, if not set, use the device default one. + * @param[in] my_type my mesh type + * @param[in] my_layer my mesh layer * * @return * - ESP_OK @@ -1287,9 +1300,9 @@ bool esp_mesh_is_root_fixed(void); esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer); /** - * @brief get mesh networking IE length of one AP + * @brief Get mesh networking IE length of one AP * - * @param len mesh networking IE length + * @param[out] len mesh networking IE length * * @return * - ESP_OK @@ -1300,11 +1313,13 @@ esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *pa esp_err_t esp_mesh_scan_get_ap_ie_len(int *len); /** - * @brief get AP record - * Different from esp_wifi_scan_get_ap_records(), this API only gets one of scanned APs each time. + * @brief Get AP record * - * @param ap_record pointer to the AP record - * @param buffer pointer to the mesh networking IE of this AP + * @attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. + * See "manual_networking" example. + * + * @param[out] ap_record pointer to one AP record + * @param[out] buffer pointer to the mesh networking IE of this AP * * @return * - ESP_OK diff --git a/components/esp32/include/esp_mesh_internal.h b/components/esp32/include/esp_mesh_internal.h index 5f73984a1..e1dbf7f72 100644 --- a/components/esp32/include/esp_mesh_internal.h +++ b/components/esp32/include/esp_mesh_internal.h @@ -33,22 +33,20 @@ extern "C" { * Structures *******************************************************/ typedef struct { - int scan; /**< minimum scan times before being a root, default:10. */ - int vote; /**< max vote times in self-healing, default:1000. */ - int fail; /**< parent selection fail times. If the scan times reach this value, - device will disconnect with associated children and join self-healing, default:120. */ - int monitor_ie; /**< acceptable times of parent networking IE change before update self networking IE, default:10. */ + int scan; /**< minimum scan times before being a root, default:10 */ + int vote; /**< max vote times in self-healing, default:1000 */ + int fail; /**< parent selection fail times, if the scan times reach this value, + device will disconnect with associated children and join self-healing. default:60 */ + int monitor_ie; /**< acceptable times of parent networking IE change before update its own networking IE. default:3 */ } mesh_attempts_t; typedef struct { - int duration_ms; /* parent weak RSSI monitor duration. If the RSSI with current parent is less than cnx_rssi continuously - within this duration_ms, device will search for a better parent. */ + int duration_ms; /* parent weak RSSI monitor duration, if the RSSI continues to be weak during this duration_ms, + device will search for a new parent. */ int cnx_rssi; /* RSSI threshold for keeping a good connection with parent. - If set a value greater than -120 dBm, device will arm a timer to monitor current RSSI at a period time of - duration_ms. */ - int select_rssi; /* RSSI threshold for parent selection, should be a value greater than switch_rssi. */ - int switch_rssi; /* RSSI threshold for parent switch. Device will disassociate current parent and switch to a new parent when - the RSSI with the new parent is greater than this set threshold. */ + If set a value greater than -120 dBm, a timer will be armed to monitor parent RSSI at a period time of duration_ms. */ + int select_rssi; /* RSSI threshold for parent selection. It should be a value greater than switch_rssi. */ + int switch_rssi; /* Disassociate with current parent and switch to a new parent when the RSSI is greater than this set threshold. */ int backoff_rssi; /* RSSI threshold for connecting to the root */ } mesh_switch_parent_t; @@ -59,7 +57,7 @@ typedef struct { } mesh_rssi_threshold_t; /** - * @brief mesh networking IE + * @brief Mesh networking IE */ typedef struct { /**< mesh networking IE head */ @@ -82,7 +80,7 @@ typedef struct { uint16_t root_cap; /**< root capacity */ uint16_t self_cap; /**< self capacity */ uint16_t layer2_cap; /**< layer2 capacity */ - uint16_t scan_ap_num; /**< the number of scanned APs */ + uint16_t scan_ap_num; /**< the number of scanning APs */ int8_t rssi; /**< RSSI of the parent */ int8_t router_rssi; /**< RSSI of the router */ uint8_t flag; /**< flag of networking */ @@ -102,9 +100,9 @@ typedef struct { * Function Definitions *******************************************************/ /** - * @brief set mesh softAP beacon interval + * @brief Set mesh softAP beacon interval * - * @param interval beacon interval(ms) (100ms ~ 60000ms) + * @param[in] interval beacon interval (msecs) (100 msecs ~ 60000 msecs) * * @return * - ESP_OK @@ -114,9 +112,9 @@ typedef struct { esp_err_t esp_mesh_set_beacon_interval(int interval_ms); /** - * @brief get mesh softAP beacon interval + * @brief Get mesh softAP beacon interval * - * @param interval beacon interval(ms) + * @param[out] interval beacon interval (msecs) * * @return * - ESP_OK @@ -124,9 +122,9 @@ esp_err_t esp_mesh_set_beacon_interval(int interval_ms); esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); /** - * @brief set attempts for mesh self-organized networking + * @brief Set attempts for mesh self-organized networking * - * @param attempts + * @param[in] attempts * * @return * - ESP_OK @@ -135,9 +133,9 @@ esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); /** - * @brief get attempts for mesh self-organized networking + * @brief Get attempts for mesh self-organized networking * - * @param attempts + * @param[out] attempts * * @return * - ESP_OK @@ -146,9 +144,9 @@ esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); /** - * @brief set parameters for parent switch + * @brief Set parameters for parent switch * - * @param paras parameters for parent switch + * @param[in] paras parameters for parent switch * * @return * - ESP_OK @@ -157,9 +155,9 @@ esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief get parameters for parent switch + * @brief Get parameters for parent switch * - * @param paras parameters for parent switch + * @param[out] paras parameters for parent switch * * @return * - ESP_OK @@ -168,12 +166,12 @@ esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief set RSSI threshold - * The default high RSSI threshold value is -78 dBm. - * The default medium RSSI threshold value is -82 dBm. - * The default low RSSI threshold value is -85 dBm. + * @brief Set RSSI threshold + * - The default high RSSI threshold value is -78 dBm. + * - The default medium RSSI threshold value is -82 dBm. + * - The default low RSSI threshold value is -85 dBm. * - * @param threshold RSSI threshold + * @param[in] threshold RSSI threshold * * @return * - ESP_OK @@ -182,8 +180,9 @@ esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); esp_err_t esp_mesh_set_rssi_threshold(const mesh_rssi_threshold_t *threshold); /** - * @brief get RSSI threshold - * @param threshold RSSI threshold + * @brief Get RSSI threshold + * + * @param[out] threshold RSSI threshold * * @return * - ESP_OK @@ -192,11 +191,11 @@ esp_err_t esp_mesh_set_rssi_threshold(const mesh_rssi_threshold_t *threshold); esp_err_t esp_mesh_get_rssi_threshold(mesh_rssi_threshold_t *threshold); /** - * @brief enable the minimum rate to 6Mbps + * @brief Enable the minimum rate to 6 Mbps * - * @attention This API shall be called before WiFi start. + * @attention This API shall be called before Wi-Fi is started. * - * @param is_6m enable or not + * @param[in] is_6m enable or not * * @return * - ESP_OK @@ -204,7 +203,7 @@ esp_err_t esp_mesh_get_rssi_threshold(mesh_rssi_threshold_t *threshold); esp_err_t esp_mesh_set_6m_rate(bool is_6m); /** - * @brief print the number of txQ waiting + * @brief Print the number of txQ waiting * * @return * - ESP_OK @@ -213,7 +212,7 @@ esp_err_t esp_mesh_set_6m_rate(bool is_6m); esp_err_t esp_mesh_print_txQ_waiting(void); /** - * @brief print the number of rxQ waiting + * @brief Print the number of rxQ waiting * * @return * - ESP_OK @@ -222,9 +221,9 @@ esp_err_t esp_mesh_print_txQ_waiting(void); esp_err_t esp_mesh_print_rxQ_waiting(void); /** - * @brief set passive scan time + * @brief Set passive scan time * - * @param interval_ms passive scan time(ms) + * @param[in] interval_ms passive scan time (msecs) * * @return * - ESP_OK @@ -234,19 +233,19 @@ esp_err_t esp_mesh_print_rxQ_waiting(void); esp_err_t esp_mesh_set_passive_scan_time(int time_ms); /** - * @brief get passive scan time + * @brief Get passive scan time * - * @return interval_ms passive scan time(ms) + * @return interval_ms passive scan time (msecs) */ int esp_mesh_get_passive_scan_time(void); /** - * @brief set announce interval - * The default short interval is 500 milliseconds. - * The default long interval is 3000 milliseconds. + * @brief Set announce interval + * - The default short interval is 500 milliseconds. + * - The default long interval is 3000 milliseconds. * - * @param short_ms shall be greater than the default value - * @param long_ms shall be greater than the default value + * @param[in] short_ms shall be greater than the default value + * @param[in] long_ms shall be greater than the default value * * @return * - ESP_OK @@ -254,10 +253,10 @@ int esp_mesh_get_passive_scan_time(void); esp_err_t esp_mesh_set_announce_interval(int short_ms, int long_ms); /** - * @brief get announce interval + * @brief Get announce interval * - * @param short_ms short interval - * @param long_ms long interval + * @param[out] short_ms short interval + * @param[out] long_ms long interval * * @return * - ESP_OK diff --git a/components/esp32/include/esp_system.h b/components/esp32/include/esp_system.h index b43dbebb8..05214c8f5 100644 --- a/components/esp32/include/esp_system.h +++ b/components/esp32/include/esp_system.h @@ -151,18 +151,31 @@ uint32_t esp_get_minimum_free_heap_size( void ); /** * @brief Get one random 32-bit word from hardware RNG * - * The hardware RNG is fully functional whenever an RF subsystem is running (ie Bluetooth or WiFi is enabled). For secure + * The hardware RNG is fully functional whenever an RF subsystem is running (ie Bluetooth or WiFi is enabled). For * random values, call this function after WiFi or Bluetooth are started. * - * When the app is running without an RF subsystem enabled, it should be considered a PRNG. To help improve this - * situation, the RNG is pre-seeded with entropy while the IDF bootloader is running. However no new entropy is - * available during the window of time between when the bootloader exits and an RF subsystem starts. It may be possible - * to discern a non-random pattern in a very large amount of output captured during this window of time. + * If the RF subsystem is not used by the program, the function bootloader_random_enable() can be called to enable an + * entropy source. bootloader_random_disable() must be called before RF subsystem or I2S peripheral are used. See these functions' + * documentation for more details. + * + * Any time the app is running without an RF subsystem (or bootloader_random) enabled, RNG hardware should be + * considered a PRNG. A very small amount of entropy is available due to pre-seeding while the IDF + * bootloader is running, but this should not be relied upon for any use. * * @return Random value between 0 and UINT32_MAX */ uint32_t esp_random(void); +/** + * @brief Fill a buffer with random bytes from hardware RNG + * + * @note This function has the same restrictions regarding available entropy as esp_random() + * + * @param buf Pointer to buffer to fill with random numbers. + * @param len Length of buffer in bytes + */ +void esp_fill_random(void *buf, size_t len); + /** * @brief Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or * external storage e.g. flash and EEPROM. diff --git a/components/esp32/include/esp_wifi.h b/components/esp32/include/esp_wifi.h index 04b999803..66ccdcdd0 100644 --- a/components/esp32/include/esp_wifi.h +++ b/components/esp32/include/esp_wifi.h @@ -223,7 +223,9 @@ esp_err_t esp_wifi_init(const wifi_init_config_t *config); * * @attention 1. This API should be called if you want to remove WiFi driver from the system * - * @return ESP_OK: succeed + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_deinit(void); diff --git a/components/esp32/ld/esp32.rom.ld b/components/esp32/ld/esp32.rom.ld index 82007fec4..fe5a4e7c7 100644 --- a/components/esp32/ld/esp32.rom.ld +++ b/components/esp32/ld/esp32.rom.ld @@ -272,6 +272,9 @@ PROVIDE ( r_E1 = 0x400108e8 ); PROVIDE ( r_E21 = 0x40010968 ); PROVIDE ( r_E22 = 0x400109b4 ); PROVIDE ( r_E3 = 0x40010a58 ); +PROVIDE ( lm_n192_mod_mul = 0x40011dc0 ); +PROVIDE ( lm_n192_mod_add = 0x40011e9c ); +PROVIDE ( lm_n192_mod_sub = 0x40011eec ); PROVIDE ( r_ea_alarm_clear = 0x40015ab4 ); PROVIDE ( r_ea_alarm_set = 0x40015a10 ); PROVIDE ( _read_r = 0x4000bda8 ); @@ -301,6 +304,7 @@ PROVIDE ( r_ecc_gen_new_public_key = 0x400170c0 ); PROVIDE ( r_ecc_gen_new_secret_key = 0x400170e4 ); PROVIDE ( r_ecc_get_debug_Keys = 0x40017224 ); PROVIDE ( r_ecc_init = 0x40016dbc ); +PROVIDE ( ecc_point_multiplication_uint8_256 = 0x40016804); PROVIDE ( RecvBuff = 0x3ffe009c ); PROVIDE ( r_em_buf_init = 0x4001729c ); PROVIDE ( r_em_buf_rx_buff_addr_get = 0x400173e8 ); @@ -599,6 +603,14 @@ PROVIDE ( r_lc_util_get_offset_clke = 0x4002f538 ); PROVIDE ( r_lc_util_get_offset_clkn = 0x4002f51c ); PROVIDE ( r_lc_util_set_loc_trans_coll = 0x4002f500 ); PROVIDE ( r_lc_version = 0x40020a30 ); +PROVIDE ( lc_set_encap_pdu_data_p192 = 0x4002e4c8 ); +PROVIDE ( lc_set_encap_pdu_data_p256 = 0x4002e454 ); +PROVIDE ( lm_get_auth_method = 0x40023420); +PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); +PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); +PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); +PROVIDE ( lmp_clk_adj_ack_handler = 0x400274f4 ); +PROVIDE ( lm_get_auth_method = 0x40023420); PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); diff --git a/components/esp32/lib b/components/esp32/lib index 4c69c1ad8..ea4bb37b0 160000 --- a/components/esp32/lib +++ b/components/esp32/lib @@ -1 +1 @@ -Subproject commit 4c69c1ad8da7a9cbe8e27598b8c91780ac0b5068 +Subproject commit ea4bb37b0f3df868608295cf6a5c08a0585a3881 diff --git a/components/esp32/phy_init.c b/components/esp32/phy_init.c index 2da98c31b..62f82f6fa 100644 --- a/components/esp32/phy_init.c +++ b/components/esp32/phy_init.c @@ -531,6 +531,18 @@ static esp_err_t store_cal_data_to_nvs_handle(nvs_handle handle, return err; } +#if CONFIG_REDUCE_PHY_TX_POWER +static void esp_phy_reduce_tx_power(esp_phy_init_data_t* init_data) +{ + uint8_t i; + + for(i = 0; i < PHY_TX_POWER_NUM; i++) { + // LOWEST_PHY_TX_POWER is the lowest tx power + init_data->params[PHY_TX_POWER_OFFSET+i] = PHY_TX_POWER_LOWEST; + } +} +#endif + void esp_phy_load_cal_and_init(phy_rf_module_t module) { esp_phy_calibration_data_t* cal_data = @@ -540,11 +552,30 @@ void esp_phy_load_cal_and_init(phy_rf_module_t module) abort(); } +#if CONFIG_REDUCE_PHY_TX_POWER + const esp_phy_init_data_t* phy_init_data = esp_phy_get_init_data(); + if (phy_init_data == NULL) { + ESP_LOGE(TAG, "failed to obtain PHY init data"); + abort(); + } + + esp_phy_init_data_t* init_data = (esp_phy_init_data_t*) malloc(sizeof(esp_phy_init_data_t)); + if (init_data == NULL) { + ESP_LOGE(TAG, "failed to allocate memory for phy init data"); + abort(); + } + + memcpy(init_data, phy_init_data, sizeof(esp_phy_init_data_t)); + if (esp_reset_reason() == ESP_RST_BROWNOUT) { + esp_phy_reduce_tx_power(init_data); + } +#else const esp_phy_init_data_t* init_data = esp_phy_get_init_data(); if (init_data == NULL) { ESP_LOGE(TAG, "failed to obtain PHY init data"); abort(); } +#endif #ifdef CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE esp_phy_calibration_mode_t calibration_mode = PHY_RF_CAL_PARTIAL; @@ -571,7 +602,12 @@ void esp_phy_load_cal_and_init(phy_rf_module_t module) esp_phy_rf_init(init_data, PHY_RF_CAL_FULL, cal_data, module); #endif +#if CONFIG_REDUCE_PHY_TX_POWER + esp_phy_release_init_data(phy_init_data); + free(init_data); +#else esp_phy_release_init_data(init_data); +#endif free(cal_data); // PHY maintains a copy of calibration data, so we can free this } diff --git a/components/esp32/phy_init_data.h b/components/esp32/phy_init_data.h index 9213020ca..c44307505 100644 --- a/components/esp32/phy_init_data.h +++ b/components/esp32/phy_init_data.h @@ -22,6 +22,11 @@ #define PHY_INIT_MAGIC "PHYINIT" +// define the lowest tx power as LOWEST_PHY_TX_POWER +#define PHY_TX_POWER_LOWEST LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 52) +#define PHY_TX_POWER_OFFSET 44 +#define PHY_TX_POWER_NUM 5 + static const char phy_init_magic_pre[] = PHY_INIT_MAGIC; /** diff --git a/components/esp32/spiram.c b/components/esp32/spiram.c index 72198734e..98effb127 100644 --- a/components/esp32/spiram.c +++ b/components/esp32/spiram.c @@ -185,7 +185,7 @@ esp_err_t esp_spiram_reserve_dma_pool(size_t size) { return ESP_ERR_NO_MEM; } - uint32_t caps[] = { MALLOC_CAP_DMA|MALLOC_CAP_INTERNAL, 0, MALLOC_CAP_8BIT|MALLOC_CAP_32BIT }; + uint32_t caps[] = { 0, MALLOC_CAP_DMA|MALLOC_CAP_INTERNAL, MALLOC_CAP_8BIT|MALLOC_CAP_32BIT }; esp_err_t e = heap_caps_add_region_with_caps(caps, (intptr_t) dma_heap, (intptr_t) dma_heap+next_size-1); if (e != ESP_OK) { return e; diff --git a/components/esp32/test/test_esp32.c b/components/esp32/test/test_esp32.c index cdca805df..82e24b12c 100644 --- a/components/esp32/test/test_esp32.c +++ b/components/esp32/test/test_esp32.c @@ -6,6 +6,7 @@ #include "esp_system.h" #include "esp_event_loop.h" #include "esp_wifi.h" +#include "esp_wifi_types.h" #include "esp_log.h" #include "nvs_flash.h" @@ -42,6 +43,11 @@ static esp_err_t event_handler(void *ctx, system_event_t *event) static void test_wifi_init_deinit(wifi_init_config_t *cfg, wifi_config_t* wifi_config) { + ESP_LOGI(TAG, EMPH_STR("esp_wifi_deinit")); + TEST_ESP_ERR(ESP_ERR_WIFI_NOT_INIT, esp_wifi_deinit()); + ESP_LOGI(TAG, EMPH_STR("esp_wifi_get_mode")); + wifi_mode_t mode_get; + TEST_ESP_ERR(ESP_ERR_WIFI_NOT_INIT, esp_wifi_get_mode(&mode_get)); ESP_LOGI(TAG, EMPH_STR("esp_wifi_init")); TEST_ESP_OK(esp_wifi_init(cfg)); ESP_LOGI(TAG, EMPH_STR("esp_wifi_set_mode")); @@ -54,6 +60,8 @@ static void test_wifi_init_deinit(wifi_init_config_t *cfg, wifi_config_t* wifi_c static void test_wifi_start_stop(wifi_init_config_t *cfg, wifi_config_t* wifi_config) { + ESP_LOGI(TAG, EMPH_STR("esp_wifi_stop")); + TEST_ESP_ERR(ESP_ERR_WIFI_NOT_INIT, esp_wifi_stop()); ESP_LOGI(TAG, EMPH_STR("esp_wifi_init")); TEST_ESP_OK(esp_wifi_init(cfg)); ESP_LOGI(TAG, EMPH_STR("esp_wifi_set_mode")); diff --git a/components/esp32/test/test_random.c b/components/esp32/test/test_random.c new file mode 100644 index 000000000..b0ce1a039 --- /dev/null +++ b/components/esp32/test/test_random.c @@ -0,0 +1,67 @@ +#include +#include +#include "unity.h" +#include "esp_system.h" + +/* Note: these are just sanity tests, not the same as + entropy tests +*/ + +TEST_CASE("call esp_random()", "[random]") +{ + const size_t NUM_RANDOM = 128; /* in most cases this is massive overkill */ + + uint32_t zeroes = UINT32_MAX; + uint32_t ones = 0; + for (int i = 0; i < NUM_RANDOM - 1; i++) { + uint32_t r = esp_random(); + ones |= r; + zeroes &= ~r; + } + + /* assuming a 'white' random distribution, we can expect + usually at least one time each bit will be zero and at + least one time each will be one. Statistically this + can still fail, just *very* unlikely to. */ + TEST_ASSERT_EQUAL_HEX32(0, zeroes); + TEST_ASSERT_EQUAL_HEX32(UINT32_MAX, ones); +} + +TEST_CASE("call esp_fill_random()", "[random]") +{ + const size_t NUM_BUF = 200; + const size_t BUF_SZ = 16; + uint8_t buf[NUM_BUF][BUF_SZ]; + uint8_t zero_buf[BUF_SZ]; + uint8_t one_buf[BUF_SZ]; + + bzero(buf, sizeof(buf)); + bzero(one_buf, sizeof(zero_buf)); + memset(zero_buf, 0xFF, sizeof(one_buf)); + + for (int i = 0; i < NUM_BUF; i++) { + esp_fill_random(buf[i], BUF_SZ); + } + /* No two 128-bit buffers should be the same + (again, statistically this could happen but it's very unlikely) */ + for (int i = 0; i < NUM_BUF; i++) { + for (int j = 0; j < NUM_BUF; j++) { + if (i != j) { + TEST_ASSERT_NOT_EQUAL(0, memcmp(buf[i], buf[j], BUF_SZ)); + } + } + } + + /* Do the same all bits are zero and one at least once test across the buffers */ + for (int i = 0; i < NUM_BUF; i++) { + for (int x = 0; x < BUF_SZ; x++) { + zero_buf[x] &= ~buf[i][x]; + one_buf[x] |= buf[i][x]; + } + } + for (int x = 0; x < BUF_SZ; x++) { + TEST_ASSERT_EQUAL_HEX8(0, zero_buf[x]); + TEST_ASSERT_EQUAL_HEX8(0xFF, one_buf[x]); + } +} + diff --git a/components/esptool_py/Makefile.projbuild b/components/esptool_py/Makefile.projbuild index 5e082a2e9..c3ce445dd 100644 --- a/components/esptool_py/Makefile.projbuild +++ b/components/esptool_py/Makefile.projbuild @@ -58,14 +58,14 @@ APP_BIN_UNSIGNED ?= $(APP_BIN) $(APP_BIN_UNSIGNED): $(APP_ELF) $(ESPTOOLPY_SRC) | check_python_dependencies $(ESPTOOLPY) elf2image $(ESPTOOL_FLASH_OPTIONS) $(ESPTOOL_ELF2IMAGE_OPTIONS) -o $@ $< -flash: all_binaries $(ESPTOOLPY_SRC) $(call prereq_if_explicit,erase_flash) partition_table_get_info check_python_dependencies +flash: all_binaries $(ESPTOOLPY_SRC) $(call prereq_if_explicit,erase_flash) partition_table_get_info | check_python_dependencies @echo "Flashing binaries to serial port $(ESPPORT) (app at offset $(APP_OFFSET))..." ifdef CONFIG_SECURE_BOOT_ENABLED @echo "(Secure boot enabled, so bootloader not flashed automatically. See 'make bootloader' output)" endif $(ESPTOOLPY_WRITE_FLASH) $(ESPTOOL_ALL_FLASH_ARGS) -app-flash: $(APP_BIN) $(ESPTOOLPY_SRC) $(call prereq_if_explicit,erase_flash) partition_table_get_info check_python_dependencies +app-flash: $(APP_BIN) $(ESPTOOLPY_SRC) $(call prereq_if_explicit,erase_flash) partition_table_get_info | check_python_dependencies @echo "Flashing app to serial port $(ESPPORT), offset $(APP_OFFSET)..." $(ESPTOOLPY_WRITE_FLASH) $(APP_OFFSET) $(APP_BIN) @@ -73,7 +73,7 @@ app-flash: $(APP_BIN) $(ESPTOOLPY_SRC) $(call prereq_if_explicit,erase_flash) pa # at the project level as long as qualified path COMPONENT_SUBMODULES += $(COMPONENT_PATH)/esptool -erase_flash: check_python_dependencies +erase_flash: | check_python_dependencies @echo "Erasing entire flash..." $(ESPTOOLPY_SERIAL) erase_flash @@ -90,14 +90,14 @@ endif # note: if you want to run miniterm from command line, can simply run # miniterm.py on the console. The '$(PYTHON) -m serial.tools.miniterm' # is to allow for the $(PYTHON) variable overriding the python path. -simple_monitor: check_python_dependencies $(call prereq_if_explicit,%flash) +simple_monitor: $(call prereq_if_explicit,%flash) | check_python_dependencies $(MONITOR_PYTHON) -m serial.tools.miniterm --rts 0 --dtr 0 --raw $(ESPPORT) $(MONITORBAUD) PRINT_FILTER ?= MONITOR_OPTS := --baud $(MONITORBAUD) --port $(ESPPORT) --toolchain-prefix $(CONFIG_TOOLPREFIX) --make "$(MAKE)" --print_filter "$(PRINT_FILTER)" -monitor: check_python_dependencies $(call prereq_if_explicit,%flash) +monitor: $(call prereq_if_explicit,%flash) | check_python_dependencies $(summary) MONITOR [ -f $(APP_ELF) ] || echo "*** 'make monitor' target requires an app to be compiled and flashed first." [ -f $(APP_ELF) ] || echo "*** Run 'make flash monitor' to build, flash and monitor" diff --git a/components/fatfs/test/test_fatfs_sdmmc.c b/components/fatfs/test/test_fatfs_sdmmc.c index 2ab31f087..74ef2207b 100644 --- a/components/fatfs/test/test_fatfs_sdmmc.c +++ b/components/fatfs/test/test_fatfs_sdmmc.c @@ -167,9 +167,7 @@ TEST_CASE("(SD) write/read speed test", "[fatfs][sd][test_env=UT_T1_SDMODE][time const size_t buf_size = 16 * 1024; uint32_t* buf = (uint32_t*) calloc(1, buf_size); - for (size_t i = 0; i < buf_size / 4; ++i) { - buf[i] = esp_random(); - } + esp_fill_random(buf, buf_size); const size_t file_size = 1 * 1024 * 1024; speed_test(buf, 4 * 1024, file_size, true); diff --git a/components/fatfs/test/test_fatfs_spiflash.c b/components/fatfs/test/test_fatfs_spiflash.c index 38ea765dd..9d0724948 100644 --- a/components/fatfs/test/test_fatfs_spiflash.c +++ b/components/fatfs/test/test_fatfs_spiflash.c @@ -162,9 +162,7 @@ TEST_CASE("(WL) write/read speed test", "[fatfs][wear_levelling][timeout=60]") const size_t buf_size = 16 * 1024; uint32_t* buf = (uint32_t*) calloc(1, buf_size); - for (size_t i = 0; i < buf_size / 4; ++i) { - buf[i] = esp_random(); - } + esp_fill_random(buf, buf_size); const size_t file_size = 256 * 1024; const char* file = "/spiflash/256k.bin"; diff --git a/components/freertos/tasks.c b/components/freertos/tasks.c index ac0b732a8..b86fa4e77 100644 --- a/components/freertos/tasks.c +++ b/components/freertos/tasks.c @@ -2040,16 +2040,19 @@ BaseType_t i; /* Add the per-core idle tasks at the lowest priority. */ for ( i=0; iheap = multi_heap_register((void *)start, end - start); SLIST_NEXT(p_new, next) = NULL; if (p_new->heap == NULL) { - err = ESP_FAIL; + err = ESP_ERR_INVALID_SIZE; goto done; } multi_heap_set_lock(p_new->heap, &p_new->heap_mux); diff --git a/components/heap/include/esp_heap_caps_init.h b/components/heap/include/esp_heap_caps_init.h index 3cf23ff7f..3ae6b8e4f 100644 --- a/components/heap/include/esp_heap_caps_init.h +++ b/components/heap/include/esp_heap_caps_init.h @@ -81,6 +81,7 @@ esp_err_t heap_caps_add_region(intptr_t start, intptr_t end); * - ESP_OK on success * - ESP_ERR_INVALID_ARG if a parameter is invalid * - ESP_ERR_NO_MEM if no memory to register new heap. + * - ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap * - ESP_FAIL if region overlaps the start and/or end of an existing region */ esp_err_t heap_caps_add_region_with_caps(const uint32_t caps[], intptr_t start, intptr_t end); diff --git a/components/heap/multi_heap_poisoning.c b/components/heap/multi_heap_poisoning.c index 3c8cff241..dabf6cc24 100644 --- a/components/heap/multi_heap_poisoning.c +++ b/components/heap/multi_heap_poisoning.c @@ -147,6 +147,12 @@ static bool verify_fill_pattern(void *data, size_t size, bool print_errors, bool MULTI_HEAP_STDERR_PRINTF("CORRUPT HEAP: Invalid data at %p. Expected 0x%08x got 0x%08x\n", p, EXPECT_WORD, *p); } valid = false; +#ifndef NDEBUG + /* If an assertion is going to fail as soon as we're done verifying the pattern, leave the rest of the + buffer contents as-is for better post-mortem analysis + */ + swap_pattern = false; +#endif } if (swap_pattern) { *p = REPLACE_WORD; @@ -164,6 +170,9 @@ static bool verify_fill_pattern(void *data, size_t size, bool print_errors, bool MULTI_HEAP_STDERR_PRINTF("CORRUPT HEAP: Invalid data at %p. Expected 0x%02x got 0x%02x\n", p, (uint8_t)EXPECT_WORD, *p); } valid = false; +#ifndef NDEBUG + swap_pattern = false; // same as above +#endif } if (swap_pattern) { p[i] = (uint8_t)REPLACE_WORD; diff --git a/components/libsodium/port/randombytes_esp32.c b/components/libsodium/port/randombytes_esp32.c index 9ff5493cc..73c77ec69 100644 --- a/components/libsodium/port/randombytes_esp32.c +++ b/components/libsodium/port/randombytes_esp32.c @@ -14,14 +14,6 @@ #include "randombytes_default.h" #include "esp_system.h" -static void randombytes_esp32_random_buf(void * const buf, const size_t size) -{ - uint8_t *p = (uint8_t *)buf; - for (size_t i = 0; i < size; i++) { - p[i] = esp_random(); - } -} - static const char *randombytes_esp32_implementation_name(void) { return "esp32"; @@ -39,7 +31,7 @@ const struct randombytes_implementation randombytes_esp32_implementation = { .random = esp_random, .stir = NULL, .uniform = NULL, - .buf = randombytes_esp32_random_buf, + .buf = esp_fill_random, .close = NULL, }; diff --git a/components/mbedtls/port/esp_hardware.c b/components/mbedtls/port/esp_hardware.c index 915766249..09ededb18 100644 --- a/components/mbedtls/port/esp_hardware.c +++ b/components/mbedtls/port/esp_hardware.c @@ -7,17 +7,18 @@ #include #include #include +#include -#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT) +#ifndef MBEDTLS_ENTROPY_HARDWARE_ALT +#error "MBEDTLS_ENTROPY_HARDWARE_ALT should always be set in ESP-IDF" +#endif -extern int os_get_random(unsigned char *buf, size_t len); int mbedtls_hardware_poll( void *data, unsigned char *output, size_t len, size_t *olen ) { - os_get_random(output, len); + esp_fill_random(output, len); *olen = len; - return 0; } -#endif + diff --git a/components/newlib/platform_include/sys/termios.h b/components/newlib/platform_include/sys/termios.h new file mode 100644 index 000000000..fd0eb5ca8 --- /dev/null +++ b/components/newlib/platform_include/sys/termios.h @@ -0,0 +1,296 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// 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 header file is based on the termios header of +// "The Single UNIX (r) Specification, Version 2, Copyright (c) 1997 The Open Group". + +#ifndef __ESP_SYS_TERMIOS_H__ +#define __ESP_SYS_TERMIOS_H__ + +// ESP-IDF NOTE: This header provides only a compatibility layer for macros and functions defined in sys/termios.h. +// Not everything has a defined meaning for ESP-IDF (e.g. process leader IDs) and therefore are likely to be stubbed +// in actual implementations. + + +#include +#include +#include "sdkconfig.h" + +#ifdef CONFIG_SUPPORT_TERMIOS + +// subscripts for the array c_cc: +#define VEOF 0 /** EOF character */ +#define VEOL 1 /** EOL character */ +#define VERASE 2 /** ERASE character */ +#define VINTR 3 /** INTR character */ +#define VKILL 4 /** KILL character */ +#define VMIN 5 /** MIN value */ +#define VQUIT 6 /** QUIT character */ +#define VSTART 7 /** START character */ +#define VSTOP 8 /** STOP character */ +#define VSUSP 9 /** SUSP character */ +#define VTIME 10 /** TIME value */ +#define NCCS (VTIME + 1) /** Size of the array c_cc for control characters */ + +// input modes for use as flags in the c_iflag field +#define BRKINT (1u << 0) /** Signal interrupt on break. */ +#define ICRNL (1u << 1) /** Map CR to NL on input. */ +#define IGNBRK (1u << 2) /** Ignore break condition. */ +#define IGNCR (1u << 3) /** Ignore CR. */ +#define IGNPAR (1u << 4) /** Ignore characters with parity errors. */ +#define INLCR (1u << 5) /** Map NL to CR on input. */ +#define INPCK (1u << 6) /** Enable input parity check. */ +#define ISTRIP (1u << 7) /** Strip character. */ +#define IUCLC (1u << 8) /** Map upper-case to lower-case on input (LEGACY). */ +#define IXANY (1u << 9) /** Enable any character to restart output. */ +#define IXOFF (1u << 10) /** Enable start/stop input control. */ +#define IXON (1u << 11) /** Enable start/stop output control. */ +#define PARMRK (1u << 12) /** Mark parity errors. */ + +// output Modes for use as flags in the c_oflag field +#define OPOST (1u << 0) /** Post-process output */ +#define OLCUC (1u << 1) /** Map lower-case to upper-case on output (LEGACY). */ +#define ONLCR (1u << 2) /** Map NL to CR-NL on output. */ +#define OCRNL (1u << 3) /** Map CR to NL on output. */ +#define ONOCR (1u << 4) /** No CR output at column 0. */ +#define ONLRET (1u << 5) /** NL performs CR function. */ +#define OFILL (1u << 6) /** Use fill characters for delay. */ +#define NLDLY (1u << 7) /** Select newline delays: */ +#define NL0 (0u << 7) /** Newline character type 0. */ +#define NL1 (1u << 7) /** Newline character type 1. */ +#define CRDLY (3u << 8) /** Select carriage-return delays: */ +#define CR0 (0u << 8) /** Carriage-return delay type 0. */ +#define CR1 (1u << 8) /** Carriage-return delay type 1. */ +#define CR2 (2u << 8) /** Carriage-return delay type 2. */ +#define CR3 (3u << 8) /** Carriage-return delay type 3. */ +#define TABDLY (3u << 10) /** Select horizontal-tab delays: */ +#define TAB0 (0u << 10) /** Horizontal-tab delay type 0. */ +#define TAB1 (1u << 10) /** Horizontal-tab delay type 1. */ +#define TAB2 (2u << 10) /** Horizontal-tab delay type 2. */ +#define TAB3 (3u << 10) /** Expand tabs to spaces. */ +#define BSDLY (1u << 12) /** Select backspace delays: */ +#define BS0 (0u << 12) /** Backspace-delay type 0. */ +#define BS1 (1u << 12) /** Backspace-delay type 1. */ +#define VTDLY (1u << 13) /** Select vertical-tab delays: */ +#define VT0 (0u << 13) /** Vertical-tab delay type 0. */ +#define VT1 (1u << 13) /** Vertical-tab delay type 1. */ +#define FFDLY (1u << 14) /** Select form-feed delays: */ +#define FF0 (0u << 14) /** Form-feed delay type 0. */ +#define FF1 (1u << 14) /** Form-feed delay type 1. */ + +// Baud Rate Selection. Valid values for objects of type speed_t: +// CBAUD range B0 - B38400 +#define B0 0 /** Hang up */ +#define B50 1 +#define B75 2 +#define B110 3 +#define B134 4 +#define B150 5 +#define B200 6 +#define B300 7 +#define B600 8 +#define B1200 9 +#define B1800 10 +#define B2400 11 +#define B4800 12 +#define B9600 13 +#define B19200 14 +#define B38400 15 +// CBAUDEX range B57600 - B4000000 +#define B57600 16 +#define B115200 17 +#define B230400 18 +#define B460800 19 +#define B500000 20 +#define B576000 21 +#define B921600 22 +#define B1000000 23 +#define B1152000 24 +#define B1500000 25 +#define B2000000 26 +#define B2500000 27 +#define B3000000 28 +#define B3500000 29 +#define B4000000 30 + +// Control Modes for the c_cflag field: +#define CSIZE (3u << 0) /* Character size: */ +#define CS5 (0u << 0) /** 5 bits. */ +#define CS6 (1u << 0) /** 6 bits. */ +#define CS7 (2u << 0) /** 7 bits. */ +#define CS8 (3u << 0) /** 8 bits. */ +#define CSTOPB (1u << 2) /** Send two stop bits, else one. */ +#define CREAD (1u << 3) /** Enable receiver. */ +#define PARENB (1u << 4) /** Parity enable. */ +#define PARODD (1u << 5) /** Odd parity, else even. */ +#define HUPCL (1u << 6) /** Hang up on last close. */ +#define CLOCAL (1u << 7) /** Ignore modem status lines. */ +#define CBAUD (1u << 8) /** Use baud rates defined by B0-B38400 macros. */ +#define CBAUDEX (1u << 9) /** Use baud rates defined by B57600-B4000000 macros. */ +#define BOTHER (1u << 10) /** Use custom baud rates */ + +// Local Modes for c_lflag field: +#define ECHO (1u << 0) /** Enable echo. */ +#define ECHOE (1u << 1) /** Echo erase character as error-correcting backspace. */ +#define ECHOK (1u << 2) /** Echo KILL. */ +#define ECHONL (1u << 3) /** Echo NL. */ +#define ICANON (1u << 4) /** Canonical input (erase and kill processing). */ +#define IEXTEN (1u << 5) /** Enable extended input character processing. */ +#define ISIG (1u << 6) /** Enable signals. */ +#define NOFLSH (1u << 7) /** Disable flush after interrupt or quit. */ +#define TOSTOP (1u << 8) /** Send SIGTTOU for background output. */ +#define XCASE (1u << 9) /** Canonical upper/lower presentation (LEGACY). */ + +// Attribute Selection constants for use with tcsetattr(): +#define TCSANOW 0 /** Change attributes immediately. */ +#define TCSADRAIN 1 /** Change attributes when output has drained. */ +#define TCSAFLUSH 2 /** Change attributes when output has drained; also flush pending input. */ + +// Line Control constants for use with tcflush(): +#define TCIFLUSH 0 /** Flush pending input. Flush untransmitted output. */ +#define TCIOFLUSH 1 /** Flush both pending input and untransmitted output. */ +#define TCOFLUSH 2 /** Flush untransmitted output. */ + +// constants for use with tcflow(): +#define TCIOFF 0 /** Transmit a STOP character, intended to suspend input data. */ +#define TCION 1 /** Transmit a START character, intended to restart input data. */ +#define TCOOFF 2 /** Suspend output. */ +#define TCOON 3 /** Restart output. */ + +typedef uint8_t cc_t; +typedef uint32_t speed_t; +typedef uint16_t tcflag_t; + +struct termios +{ + tcflag_t c_iflag; /** Input modes */ + tcflag_t c_oflag; /** Output modes */ + tcflag_t c_cflag; /** Control modes */ + tcflag_t c_lflag; /** Local modes */ + cc_t c_cc[NCCS]; /** Control characters */ + speed_t c_ispeed; /** input baud rate */ + speed_t c_ospeed; /** output baud rate */ +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Extracts the input baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return input baud rate + */ +speed_t cfgetispeed(const struct termios *p); + +/** + * @brief Extracts the output baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return output baud rate + */ +speed_t cfgetospeed(const struct termios *p); + +/** + * @brief Set input baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp input baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetispeed(struct termios *p, speed_t sp); + +/** + * @brief Set output baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp output baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetospeed(struct termios *p, speed_t sp); + +/** + * @brief Wait for transmission of output + * + * @param fd file descriptor of the terminal + * @return 0 when successful, -1 otherwise with errno set + */ +int tcdrain(int fd); + +/** + * @brief Suspend or restart the transmission or reception of data + * + * @param fd file descriptor of the terminal + * @param action selects actions to do + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflow(int fd, int action); + +/** + * @brief Flush non-transmitted output data and non-read input data + * + * @param fd file descriptor of the terminal + * @param select selects what should be flushed + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflush(int fd, int select); + +/** + * @brief Gets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param p output termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcgetattr(int fd, struct termios *p); + +/** + * @brief Get process group ID for session leader for controlling terminal + * + * @param fd file descriptor of the terminal + * @return process group ID when successful, -1 otherwise with errno set + */ +pid_t tcgetsid(int fd); + +/** + * @brief Send a break for a specific duration + * + * @param fd file descriptor of the terminal + * @param duration duration of break + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsendbreak(int fd, int duration); + +/** + * @brief Sets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param optional_actions optional actions + * @param p input termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsetattr(int fd, int optional_actions, const struct termios *p); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // CONFIG_SUPPORT_TERMIOS + +#endif //__ESP_SYS_TERMIOS_H__ diff --git a/components/newlib/random.c b/components/newlib/random.c index 47ebb23ca..5d3e6175c 100644 --- a/components/newlib/random.c +++ b/components/newlib/random.c @@ -36,17 +36,8 @@ ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) return -1; } - uint8_t *dst = (uint8_t *) buf; - ssize_t ret = 0; + esp_fill_random(buf, buflen); - while (ret < buflen) { - const uint32_t random = esp_random(); - const int needed = buflen - ret; - const int copy_len = MIN(sizeof(random), needed); - memcpy(dst + ret, &random, copy_len); - ret += copy_len; - } - - ESP_LOGD(TAG, "getrandom returns %d", ret); - return ret; + ESP_LOGD(TAG, "getrandom returns %d", buflen); + return buflen; } diff --git a/components/newlib/termios.c b/components/newlib/termios.c new file mode 100644 index 000000000..bccd5bf83 --- /dev/null +++ b/components/newlib/termios.c @@ -0,0 +1,54 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "sdkconfig.h" + +#ifdef CONFIG_SUPPORT_TERMIOS + +#include +#include + +speed_t cfgetispeed(const struct termios *p) +{ + return p ? p->c_ispeed : B0; +} + +speed_t cfgetospeed(const struct termios *p) +{ + return p ? p->c_ospeed : B0; +} + +int cfsetispeed(struct termios *p, speed_t sp) +{ + if (p) { + p->c_ispeed = sp; + return 0; + } else { + errno = EINVAL; + return -1; + } +} + +int cfsetospeed(struct termios *p, speed_t sp) +{ + if (p) { + p->c_ospeed = sp; + return 0; + } else { + errno = EINVAL; + return -1; + } +} + +#endif // CONFIG_SUPPORT_TERMIOS diff --git a/components/partition_table/Makefile.projbuild b/components/partition_table/Makefile.projbuild index 5d04636b1..db60ee738 100644 --- a/components/partition_table/Makefile.projbuild +++ b/components/partition_table/Makefile.projbuild @@ -76,7 +76,7 @@ export OTA_DATA_SIZE PARTITION_TABLE_FLASH_CMD = $(ESPTOOLPY_SERIAL) write_flash $(PARTITION_TABLE_OFFSET) $(PARTITION_TABLE_BIN) ESPTOOL_ALL_FLASH_ARGS += $(PARTITION_TABLE_OFFSET) $(PARTITION_TABLE_BIN) -partition_table: $(PARTITION_TABLE_BIN) partition_table_get_info check_python_dependencies +partition_table: $(PARTITION_TABLE_BIN) partition_table_get_info | check_python_dependencies @echo "Partition table binary generated. Contents:" @echo $(SEPARATOR) $(GEN_ESP32PART) $< @@ -84,7 +84,7 @@ partition_table: $(PARTITION_TABLE_BIN) partition_table_get_info check_python_de @echo "Partition flashing command:" @echo "$(PARTITION_TABLE_FLASH_CMD)" -partition_table-flash: $(PARTITION_TABLE_BIN) check_python_dependencies +partition_table-flash: $(PARTITION_TABLE_BIN) | check_python_dependencies @echo "Flashing partition table..." $(PARTITION_TABLE_FLASH_CMD) diff --git a/components/soc/esp32/rtc_wdt.c b/components/soc/esp32/rtc_wdt.c index 5fea2fd55..67770709b 100644 --- a/components/soc/esp32/rtc_wdt.c +++ b/components/soc/esp32/rtc_wdt.c @@ -87,6 +87,27 @@ esp_err_t rtc_wdt_set_time(rtc_wdt_stage_t stage, unsigned int timeout_ms) return ESP_OK; } +esp_err_t rtc_wdt_get_timeout(rtc_wdt_stage_t stage, unsigned int* timeout_ms) +{ + if (stage > 3) { + return ESP_ERR_INVALID_ARG; + } + uint32_t time_tick; + if (stage == RTC_WDT_STAGE0) { + time_tick = READ_PERI_REG(RTC_CNTL_WDTCONFIG1_REG); + } else if (stage == RTC_WDT_STAGE1) { + time_tick = READ_PERI_REG(RTC_CNTL_WDTCONFIG2_REG); + } else if (stage == RTC_WDT_STAGE2) { + time_tick = READ_PERI_REG(RTC_CNTL_WDTCONFIG3_REG); + } else { + time_tick = READ_PERI_REG(RTC_CNTL_WDTCONFIG4_REG); + } + + *timeout_ms = time_tick * 1000 / rtc_clk_slow_freq_get_hz(); + + return ESP_OK; +} + esp_err_t rtc_wdt_set_stage(rtc_wdt_stage_t stage, rtc_wdt_stage_action_t stage_sel) { if (stage > 3 || stage_sel > 4) { diff --git a/components/soc/include/soc/rtc_wdt.h b/components/soc/include/soc/rtc_wdt.h index 9094a305a..ec7175a00 100644 --- a/components/soc/include/soc/rtc_wdt.h +++ b/components/soc/include/soc/rtc_wdt.h @@ -142,6 +142,18 @@ void rtc_wdt_feed(); */ esp_err_t rtc_wdt_set_time(rtc_wdt_stage_t stage, unsigned int timeout_ms); +/** + * @brief Get the timeout set for the required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[out] timeout_ms Timeout set for this stage. (not elapsed time). + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage has invalid value + */ +esp_err_t rtc_wdt_get_timeout(rtc_wdt_stage_t stage, unsigned int* timeout_ms); + /** * @brief Set an action for required stage. * diff --git a/components/spi_flash/flash_ops.c b/components/spi_flash/flash_ops.c index aab0c1210..89f9ef5e1 100644 --- a/components/spi_flash/flash_ops.c +++ b/components/spi_flash/flash_ops.c @@ -218,7 +218,7 @@ esp_err_t IRAM_ATTR spi_flash_erase_range(uint32_t start_addr, uint32_t size) if (rc == ESP_ROM_SPIFLASH_RESULT_OK) { for (size_t sector = start; sector != end && rc == ESP_ROM_SPIFLASH_RESULT_OK; ) { spi_flash_guard_start(); - if (sector % sectors_per_block == 0 && end - sector > sectors_per_block) { + if (sector % sectors_per_block == 0 && end - sector >= sectors_per_block) { rc = esp_rom_spiflash_erase_block(sector / sectors_per_block); sector += sectors_per_block; COUNTER_ADD_BYTES(erase, sectors_per_block * SPI_FLASH_SEC_SIZE); diff --git a/components/vfs/Kconfig b/components/vfs/Kconfig index d3d4ae9ad..19a565b2b 100644 --- a/components/vfs/Kconfig +++ b/components/vfs/Kconfig @@ -9,4 +9,10 @@ config SUPPRESS_SELECT_DEBUG_OUTPUT It is possible to suppress these debug outputs by enabling this option. +config SUPPORT_TERMIOS + bool "Add support for termios.h" + default y + help + Disabling this option can save memory when the support for termios.h is not required. + endmenu diff --git a/components/vfs/include/esp_vfs.h b/components/vfs/include/esp_vfs.h index 4d847274b..d7467d227 100644 --- a/components/vfs/include/esp_vfs.h +++ b/components/vfs/include/esp_vfs.h @@ -26,8 +26,10 @@ #include #include #include +#include #include #include +#include "sdkconfig.h" #ifdef __cplusplus extern "C" { @@ -178,6 +180,37 @@ typedef struct int (*truncate_p)(void* ctx, const char *path, off_t length); int (*truncate)(const char *path, off_t length); }; +#ifdef CONFIG_SUPPORT_TERMIOS + union { + int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p); + int (*tcsetattr)(int fd, int optional_actions, const struct termios *p); + }; + union { + int (*tcgetattr_p)(void *ctx, int fd, struct termios *p); + int (*tcgetattr)(int fd, struct termios *p); + }; + union { + int (*tcdrain_p)(void *ctx, int fd); + int (*tcdrain)(int fd); + }; + union { + int (*tcflush_p)(void *ctx, int fd, int select); + int (*tcflush)(int fd, int select); + }; + union { + int (*tcflow_p)(void *ctx, int fd, int action); + int (*tcflow)(int fd, int action); + }; + union { + pid_t (*tcgetsid_p)(void *ctx, int fd); + pid_t (*tcgetsid)(int fd); + }; + union { + int (*tcsendbreak_p)(void *ctx, int fd, int duration); + int (*tcsendbreak)(int fd, int duration); + }; +#endif // CONFIG_SUPPORT_TERMIOS + /** start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS */ esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, SemaphoreHandle_t *signal_sem); /** socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS */ diff --git a/components/vfs/test/test_vfs_uart.c b/components/vfs/test/test_vfs_uart.c index 20684cc2b..2e45d76bf 100644 --- a/components/vfs/test/test_vfs_uart.c +++ b/components/vfs/test/test_vfs_uart.c @@ -15,6 +15,9 @@ #include #include #include +#include +#include +#include #include "unity.h" #include "rom/uart.h" #include "soc/uart_struct.h" @@ -23,6 +26,7 @@ #include "freertos/semphr.h" #include "driver/uart.h" #include "esp_vfs_dev.h" +#include "esp_vfs.h" #include "sdkconfig.h" static void fwrite_str_loopback(const char* str, size_t size) @@ -198,3 +202,131 @@ TEST_CASE("can write to UART while another task is reading", "[vfs]") vSemaphoreDelete(read_arg.done); vSemaphoreDelete(write_arg.done); } + +#ifdef CONFIG_SUPPORT_TERMIOS +TEST_CASE("Can use termios for UART", "[vfs]") +{ + uart_config_t uart_config = { + .baud_rate = 115200, + .data_bits = UART_DATA_8_BITS, + .parity = UART_PARITY_DISABLE, + .stop_bits = UART_STOP_BITS_1, + .flow_ctrl = UART_HW_FLOWCTRL_DISABLE + }; + uart_param_config(UART_NUM_1, &uart_config); + uart_driver_install(UART_NUM_1, 256, 256, 0, NULL, 0); + + const int uart_fd = open("/dev/uart/1", O_RDWR); + TEST_ASSERT_NOT_EQUAL_MESSAGE(uart_fd, -1, "Cannot open UART"); + esp_vfs_dev_uart_use_driver(1); + + TEST_ASSERT_EQUAL(-1, tcgetattr(uart_fd, NULL)); + TEST_ASSERT_EQUAL(EINVAL, errno); + + struct termios tios, tios_result; + + TEST_ASSERT_EQUAL(-1, tcgetattr(-1, &tios)); + TEST_ASSERT_EQUAL(EBADF, errno); + + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios)); + + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSADRAIN, &tios)); + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSAFLUSH, &tios)); + + tios.c_iflag |= IGNCR; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + tios.c_iflag &= (~IGNCR); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(IGNCR, tios_result.c_iflag & IGNCR); + memset(&tios_result, 0xFF, sizeof(struct termios)); + + tios.c_iflag |= ICRNL; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + tios.c_iflag &= (~ICRNL); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(ICRNL, tios_result.c_iflag & ICRNL); + memset(&tios_result, 0xFF, sizeof(struct termios)); + + { + uart_word_length_t data_bit; + uart_stop_bits_t stop_bits; + uart_parity_t parity_mode; + + tios.c_cflag &= (~CSIZE); + tios.c_cflag &= (~CSTOPB); + tios.c_cflag &= (~PARENB); + tios.c_cflag |= CS6; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + tios.c_cflag &= (~CSIZE); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(CS6, tios_result.c_cflag & CS6); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_word_length(UART_NUM_1, &data_bit)); + TEST_ASSERT_EQUAL(UART_DATA_6_BITS, data_bit); + TEST_ASSERT_EQUAL(0, tios_result.c_cflag & CSTOPB); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_stop_bits(UART_NUM_1, &stop_bits)); + TEST_ASSERT_EQUAL(UART_STOP_BITS_1, stop_bits); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_parity(UART_NUM_1, &parity_mode)); + TEST_ASSERT_EQUAL(UART_PARITY_DISABLE, parity_mode); + memset(&tios_result, 0xFF, sizeof(struct termios)); + } + + { + uart_stop_bits_t stop_bits; + uart_parity_t parity_mode; + + tios.c_cflag |= CSTOPB; + tios.c_cflag |= (PARENB | PARODD); + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + tios.c_cflag &= (~(CSTOPB | PARENB | PARODD)); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(CSTOPB, tios_result.c_cflag & CSTOPB); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_stop_bits(UART_NUM_1, &stop_bits)); + TEST_ASSERT_EQUAL(UART_STOP_BITS_2, stop_bits); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_parity(UART_NUM_1, &parity_mode)); + TEST_ASSERT_EQUAL(UART_PARITY_ODD, parity_mode); + memset(&tios_result, 0xFF, sizeof(struct termios)); + } + + { + uint32_t baudrate; + + tios.c_cflag &= (~BOTHER); + tios.c_cflag |= CBAUD; + tios.c_ispeed = tios.c_ospeed = B38400; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(CBAUD, tios_result.c_cflag & CBAUD); + TEST_ASSERT_EQUAL(B38400, tios_result.c_ispeed); + TEST_ASSERT_EQUAL(B38400, tios_result.c_ospeed); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_baudrate(UART_NUM_1, &baudrate)); + TEST_ASSERT_EQUAL(38400, baudrate); + + tios.c_cflag |= CBAUDEX; + tios.c_ispeed = tios.c_ospeed = B230400; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(BOTHER, tios_result.c_cflag & BOTHER); + // Setting the speed to 230400 will set it actually to 230423 + TEST_ASSERT_EQUAL(230423, tios_result.c_ispeed); + TEST_ASSERT_EQUAL(230423, tios_result.c_ospeed); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_baudrate(UART_NUM_1, &baudrate)); + TEST_ASSERT_EQUAL(230423, baudrate); + + tios.c_cflag |= BOTHER; + tios.c_ispeed = tios.c_ospeed = 213; + TEST_ASSERT_EQUAL(0, tcsetattr(uart_fd, TCSANOW, &tios)); + TEST_ASSERT_EQUAL(0, tcgetattr(uart_fd, &tios_result)); + TEST_ASSERT_EQUAL(BOTHER, tios_result.c_cflag & BOTHER); + TEST_ASSERT_EQUAL(213, tios_result.c_ispeed); + TEST_ASSERT_EQUAL(213, tios_result.c_ospeed); + TEST_ASSERT_EQUAL(ESP_OK, uart_get_baudrate(UART_NUM_1, &baudrate)); + TEST_ASSERT_EQUAL(213, baudrate); + + memset(&tios_result, 0xFF, sizeof(struct termios)); + } + + esp_vfs_dev_uart_use_nonblocking(1); + close(uart_fd); + uart_driver_delete(UART_NUM_1); +} +#endif // CONFIG_SUPPORT_TERMIOS diff --git a/components/vfs/vfs.c b/components/vfs/vfs.c index f0a195992..e8b99eff2 100644 --- a/components/vfs/vfs.c +++ b/components/vfs/vfs.c @@ -994,3 +994,103 @@ void esp_vfs_select_triggered_isr(SemaphoreHandle_t *signal_sem, BaseType_t *wok } } } + +#ifdef CONFIG_SUPPORT_TERMIOS +int tcgetattr(int fd, struct termios *p) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcgetattr, local_fd, p); + return ret; +} + +int tcsetattr(int fd, int optional_actions, const struct termios *p) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcsetattr, local_fd, optional_actions, p); + return ret; +} + +int tcdrain(int fd) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcdrain, local_fd); + return ret; +} + +int tcflush(int fd, int select) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcflush, local_fd, select); + return ret; +} + +int tcflow(int fd, int action) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcflow, local_fd, action); + return ret; +} + +pid_t tcgetsid(int fd) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcgetsid, local_fd); + return ret; +} + +int tcsendbreak(int fd, int duration) +{ + const vfs_entry_t* vfs = get_vfs_for_fd(fd); + const int local_fd = get_local_fd(vfs, fd); + struct _reent* r = __getreent(); + if (vfs == NULL || local_fd < 0) { + __errno_r(r) = EBADF; + return -1; + } + int ret; + CHECK_AND_CALL(ret, r, vfs, tcsendbreak, local_fd, duration); + return ret; +} +#endif // CONFIG_SUPPORT_TERMIOS diff --git a/components/vfs/vfs_uart.c b/components/vfs/vfs_uart.c index d53de7597..e407de475 100644 --- a/components/vfs/vfs_uart.c +++ b/components/vfs/vfs_uart.c @@ -80,14 +80,15 @@ static esp_line_endings_t s_tx_mode = #endif // Newline conversion mode when receiving -static esp_line_endings_t s_rx_mode = +static esp_line_endings_t s_rx_mode[UART_NUM] = { [0 ... UART_NUM-1] = #if CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF - ESP_LINE_ENDINGS_CRLF; + ESP_LINE_ENDINGS_CRLF #elif CONFIG_NEWLIB_STDIN_LINE_ENDING_CR - ESP_LINE_ENDINGS_CR; + ESP_LINE_ENDINGS_CR #else - ESP_LINE_ENDINGS_LF; + ESP_LINE_ENDINGS_LF #endif +}; static void uart_end_select(); @@ -213,9 +214,9 @@ static ssize_t uart_read(int fd, void* data, size_t size) while (received < size) { int c = uart_read_char(fd); if (c == '\r') { - if (s_rx_mode == ESP_LINE_ENDINGS_CR) { + if (s_rx_mode[fd] == ESP_LINE_ENDINGS_CR) { c = '\n'; - } else if (s_rx_mode == ESP_LINE_ENDINGS_CRLF) { + } else if (s_rx_mode[fd] == ESP_LINE_ENDINGS_CRLF) { /* look ahead */ int c2 = uart_read_char(fd); if (c2 == NONE) { @@ -420,6 +421,456 @@ static void uart_end_select() _lock_release(&s_one_select_lock); } +#ifdef CONFIG_SUPPORT_TERMIOS +static int uart_tcsetattr(int fd, int optional_actions, const struct termios *p) +{ + if (fd < 0 || fd >= UART_NUM) { + errno = EBADF; + return -1; + } + + if (p == NULL) { + errno = EINVAL; + return -1; + } + + switch (optional_actions) { + case TCSANOW: + // nothing to do + break; + case TCSADRAIN: + if (uart_wait_tx_done(fd, portMAX_DELAY) != ESP_OK) { + errno = EINVAL; + return -1; + } + // intentional fall-through to the next case + case TCSAFLUSH: + if (uart_flush_input(fd) != ESP_OK) { + errno = EINVAL; + return -1; + } + break; + default: + errno = EINVAL; + return -1; + } + + if (p->c_iflag & IGNCR) { + s_rx_mode[fd] = ESP_LINE_ENDINGS_CRLF; + } else if (p->c_iflag & ICRNL) { + s_rx_mode[fd] = ESP_LINE_ENDINGS_CR; + } else { + s_rx_mode[fd] = ESP_LINE_ENDINGS_LF; + } + + // output line endings are not supported because there is no alternative in termios for converting LF to CR + + { + uart_word_length_t data_bits; + const tcflag_t csize_bits = p->c_cflag & CSIZE; + + switch (csize_bits) { + case CS5: + data_bits = UART_DATA_5_BITS; + break; + case CS6: + data_bits = UART_DATA_6_BITS; + break; + case CS7: + data_bits = UART_DATA_7_BITS; + break; + case CS8: + data_bits = UART_DATA_8_BITS; + break; + default: + errno = EINVAL; + return -1; + } + + if (uart_set_word_length(fd, data_bits) != ESP_OK) { + errno = EINVAL; + return -1; + } + } + + if (uart_set_stop_bits(fd, (p->c_cflag & CSTOPB) ? UART_STOP_BITS_2 : UART_STOP_BITS_1) != ESP_OK) { + errno = EINVAL; + return -1; + } + + if (uart_set_parity(fd, (p->c_cflag & PARENB) ? + ((p->c_cflag & PARODD) ? UART_PARITY_ODD : UART_PARITY_EVEN) + : + UART_PARITY_DISABLE) != ESP_OK) { + errno = EINVAL; + return -1; + } + + if (p->c_cflag & (CBAUD | CBAUDEX)) { + if (p->c_ispeed != p->c_ospeed) { + errno = EINVAL; + return -1; + } else { + uint32_t b; + if (p->c_cflag & BOTHER) { + b = p->c_ispeed; + } else { + switch (p->c_ispeed) { + case B0: + b = 0; + break; + case B50: + b = 50; + break; + case B75: + b = 75; + break; + case B110: + b = 110; + break; + case B134: + b = 134; + break; + case B150: + b = 150; + break; + case B200: + b = 200; + break; + case B300: + b = 300; + break; + case B600: + b = 600; + break; + case B1200: + b = 1200; + break; + case B1800: + b = 1800; + break; + case B2400: + b = 2400; + break; + case B4800: + b = 4800; + break; + case B9600: + b = 9600; + break; + case B19200: + b = 19200; + break; + case B38400: + b = 38400; + break; + case B57600: + b = 57600; + break; + case B115200: + b = 115200; + break; + case B230400: + b = 230400; + break; + case B460800: + b = 460800; + break; + case B500000: + b = 500000; + break; + case B576000: + b = 576000; + break; + case B921600: + b = 921600; + break; + case B1000000: + b = 1000000; + break; + case B1152000: + b = 1152000; + break; + case B1500000: + b = 1500000; + break; + case B2000000: + b = 2000000; + break; + case B2500000: + b = 2500000; + break; + case B3000000: + b = 3000000; + break; + case B3500000: + b = 3500000; + break; + case B4000000: + b = 4000000; + break; + default: + errno = EINVAL; + return -1; + } + } + + if (uart_set_baudrate(fd, b) != ESP_OK) { + errno = EINVAL; + return -1; + } + } + } + + return 0; +} + +static int uart_tcgetattr(int fd, struct termios *p) +{ + if (fd < 0 || fd >= UART_NUM) { + errno = EBADF; + return -1; + } + + if (p == NULL) { + errno = EINVAL; + return -1; + } + + memset(p, 0, sizeof(struct termios)); + + if (s_rx_mode[fd] == ESP_LINE_ENDINGS_CRLF) { + p->c_iflag |= IGNCR; + } else if (s_rx_mode[fd] == ESP_LINE_ENDINGS_CR) { + p->c_iflag |= ICRNL; + } + + { + uart_word_length_t data_bits; + + if (uart_get_word_length(fd, &data_bits) != ESP_OK) { + errno = EINVAL; + return -1; + } + + p->c_cflag &= (~CSIZE); + + switch (data_bits) { + case UART_DATA_5_BITS: + p->c_cflag |= CS5; + break; + case UART_DATA_6_BITS: + p->c_cflag |= CS6; + break; + case UART_DATA_7_BITS: + p->c_cflag |= CS7; + break; + case UART_DATA_8_BITS: + p->c_cflag |= CS8; + break; + default: + errno = ENOSYS; + return -1; + } + } + + { + uart_stop_bits_t stop_bits; + if (uart_get_stop_bits(fd, &stop_bits) != ESP_OK) { + errno = EINVAL; + return -1; + } + + switch (stop_bits) { + case UART_STOP_BITS_1: + // nothing to do + break; + case UART_STOP_BITS_2: + p->c_cflag |= CSTOPB; + break; + default: + // UART_STOP_BITS_1_5 is unsupported by termios + errno = ENOSYS; + return -1; + } + } + + { + uart_parity_t parity_mode; + if (uart_get_parity(fd, &parity_mode) != ESP_OK) { + errno = EINVAL; + return -1; + } + + switch (parity_mode) { + case UART_PARITY_EVEN: + p->c_cflag |= PARENB; + break; + case UART_PARITY_ODD: + p->c_cflag |= (PARENB | PARODD); + break; + case UART_PARITY_DISABLE: + // nothing to do + break; + default: + errno = ENOSYS; + return -1; + } + } + + { + uint32_t baudrate; + if (uart_get_baudrate(fd, &baudrate) != ESP_OK) { + errno = EINVAL; + return -1; + } + + p->c_cflag |= (CBAUD | CBAUDEX); + + speed_t sp; + switch (baudrate) { + case 0: + sp = B0; + break; + case 50: + sp = B50; + break; + case 75: + sp = B75; + break; + case 110: + sp = B110; + break; + case 134: + sp = B134; + break; + case 150: + sp = B150; + break; + case 200: + sp = B200; + break; + case 300: + sp = B300; + break; + case 600: + sp = B600; + break; + case 1200: + sp = B1200; + break; + case 1800: + sp = B1800; + break; + case 2400: + sp = B2400; + break; + case 4800: + sp = B4800; + break; + case 9600: + sp = B9600; + break; + case 19200: + sp = B19200; + break; + case 38400: + sp = B38400; + break; + case 57600: + sp = B57600; + break; + case 115200: + sp = B115200; + break; + case 230400: + sp = B230400; + break; + case 460800: + sp = B460800; + break; + case 500000: + sp = B500000; + break; + case 576000: + sp = B576000; + break; + case 921600: + sp = B921600; + break; + case 1000000: + sp = B1000000; + break; + case 1152000: + sp = B1152000; + break; + case 1500000: + sp = B1500000; + break; + case 2000000: + sp = B2000000; + break; + case 2500000: + sp = B2500000; + break; + case 3000000: + sp = B3000000; + break; + case 3500000: + sp = B3500000; + break; + case 4000000: + sp = B4000000; + break; + default: + p->c_cflag |= BOTHER; + sp = baudrate; + break; + } + + p->c_ispeed = p->c_ospeed = sp; + } + + return 0; +} + +static int uart_tcdrain(int fd) +{ + if (fd < 0 || fd >= UART_NUM) { + errno = EBADF; + return -1; + } + + if (uart_wait_tx_done(fd, portMAX_DELAY) != ESP_OK) { + errno = EINVAL; + return -1; + } + + return 0; +} + +static int uart_tcflush(int fd, int select) +{ + if (fd < 0 || fd >= UART_NUM) { + errno = EBADF; + return -1; + } + + if (select == TCIFLUSH) { + if (uart_flush_input(fd) != ESP_OK) { + errno = EINVAL; + return -1; + } + } else { + // output flushing is not supported + errno = EINVAL; + return -1; + } + + return 0; +} +#endif // CONFIG_SUPPORT_TERMIOS + void esp_vfs_dev_uart_register() { esp_vfs_t vfs = { @@ -433,13 +884,21 @@ void esp_vfs_dev_uart_register() .access = &uart_access, .start_select = &uart_start_select, .end_select = &uart_end_select, +#ifdef CONFIG_SUPPORT_TERMIOS + .tcsetattr = &uart_tcsetattr, + .tcgetattr = &uart_tcgetattr, + .tcdrain = &uart_tcdrain, + .tcflush = &uart_tcflush, +#endif // CONFIG_SUPPORT_TERMIOS }; ESP_ERROR_CHECK(esp_vfs_register("/dev/uart", &vfs, NULL)); } void esp_vfs_dev_uart_set_rx_line_endings(esp_line_endings_t mode) { - s_rx_mode = mode; + for (int i = 0; i < UART_NUM; ++i) { + s_rx_mode[i] = mode; + } } void esp_vfs_dev_uart_set_tx_line_endings(esp_line_endings_t mode) diff --git a/components/wpa_supplicant/port/os_xtensa.c b/components/wpa_supplicant/port/os_xtensa.c index 9ecde1f11..7c2177c4d 100644 --- a/components/wpa_supplicant/port/os_xtensa.c +++ b/components/wpa_supplicant/port/os_xtensa.c @@ -39,26 +39,9 @@ unsigned long os_random(void) return esp_random(); } -unsigned long r_rand(void) __attribute__((alias("os_random"))); - - int os_get_random(unsigned char *buf, size_t len) { - int i, j; - unsigned long tmp; - - for (i = 0; i < ((len + 3) & ~3) / 4; i++) { - tmp = r_rand(); - - for (j = 0; j < 4; j++) { - if ((i * 4 + j) < len) { - buf[i * 4 + j] = (uint8_t)(tmp >> (j * 8)); - } else { - break; - } - } - } - + esp_fill_random(buf, len); return 0; } diff --git a/docs/_static/mesh-asynchronous-power-on-example.png b/docs/_static/mesh-asynchronous-power-on-example.png new file mode 100644 index 000000000..7e4833e14 Binary files /dev/null and b/docs/_static/mesh-asynchronous-power-on-example.png differ diff --git a/docs/_static/mesh-beacon-frame-rssi.png b/docs/_static/mesh-beacon-frame-rssi.png new file mode 100644 index 000000000..753189dad Binary files /dev/null and b/docs/_static/mesh-beacon-frame-rssi.png differ diff --git a/docs/_static/mesh-bidirectional-data-stream.png b/docs/_static/mesh-bidirectional-data-stream.png new file mode 100644 index 000000000..056dbd4da Binary files /dev/null and b/docs/_static/mesh-bidirectional-data-stream.png differ diff --git a/docs/_static/mesh-esp-mesh-network-architecture.png b/docs/_static/mesh-esp-mesh-network-architecture.png new file mode 100644 index 000000000..06164b4df Binary files /dev/null and b/docs/_static/mesh-esp-mesh-network-architecture.png differ diff --git a/docs/_static/mesh_events_delivery.png b/docs/_static/mesh-events-delivery.png similarity index 100% rename from docs/_static/mesh_events_delivery.png rename to docs/_static/mesh-events-delivery.png diff --git a/docs/_static/mesh-network-building.png b/docs/_static/mesh-network-building.png new file mode 100644 index 000000000..7d1508111 Binary files /dev/null and b/docs/_static/mesh-network-building.png differ diff --git a/docs/_static/mesh-node-types.png b/docs/_static/mesh-node-types.png new file mode 100644 index 000000000..7d28cb746 Binary files /dev/null and b/docs/_static/mesh-node-types.png differ diff --git a/docs/_static/mesh-packet.png b/docs/_static/mesh-packet.png new file mode 100644 index 000000000..903827af1 Binary files /dev/null and b/docs/_static/mesh-packet.png differ diff --git a/docs/_static/mesh-parent-node-failure.png b/docs/_static/mesh-parent-node-failure.png new file mode 100644 index 000000000..658bbc5f1 Binary files /dev/null and b/docs/_static/mesh-parent-node-failure.png differ diff --git a/docs/_static/mesh-preferred-parent-node.png b/docs/_static/mesh-preferred-parent-node.png new file mode 100644 index 000000000..700038d3b Binary files /dev/null and b/docs/_static/mesh-preferred-parent-node.png differ diff --git a/docs/_static/mesh-root-node-designated-example.png b/docs/_static/mesh-root-node-designated-example.png new file mode 100644 index 000000000..e16594dec Binary files /dev/null and b/docs/_static/mesh-root-node-designated-example.png differ diff --git a/docs/_static/mesh-root-node-election-example.png b/docs/_static/mesh-root-node-election-example.png new file mode 100644 index 000000000..1255c52a4 Binary files /dev/null and b/docs/_static/mesh-root-node-election-example.png differ diff --git a/docs/_static/mesh-root-node-failure.png b/docs/_static/mesh-root-node-failure.png new file mode 100644 index 000000000..cc6576031 Binary files /dev/null and b/docs/_static/mesh-root-node-failure.png differ diff --git a/docs/_static/mesh-root-node-switch-example.png b/docs/_static/mesh-root-node-switch-example.png new file mode 100644 index 000000000..9074bab01 Binary files /dev/null and b/docs/_static/mesh-root-node-switch-example.png differ diff --git a/docs/_static/mesh-routing-tables-example.png b/docs/_static/mesh-routing-tables-example.png new file mode 100644 index 000000000..2e6673cce Binary files /dev/null and b/docs/_static/mesh-routing-tables-example.png differ diff --git a/docs/_static/mesh_software_stack.png b/docs/_static/mesh-software-stack.png similarity index 100% rename from docs/_static/mesh_software_stack.png rename to docs/_static/mesh-software-stack.png diff --git a/docs/_static/mesh-traditional-network-architecture.png b/docs/_static/mesh-traditional-network-architecture.png new file mode 100644 index 000000000..d3dc9901f Binary files /dev/null and b/docs/_static/mesh-traditional-network-architecture.png differ diff --git a/docs/_static/mesh-tree-topology.png b/docs/_static/mesh-tree-topology.png new file mode 100644 index 000000000..ad70b8377 Binary files /dev/null and b/docs/_static/mesh-tree-topology.png differ diff --git a/docs/_static/mesh_network_architecture.png b/docs/_static/mesh_network_architecture.png deleted file mode 100644 index 4c54db128..000000000 Binary files a/docs/_static/mesh_network_architecture.png and /dev/null differ diff --git a/docs/_static/mesh_network_topology.png b/docs/_static/mesh_network_topology.png deleted file mode 100644 index 5bdf7a145..000000000 Binary files a/docs/_static/mesh_network_topology.png and /dev/null differ diff --git a/docs/conf_common.py b/docs/conf_common.py index 86073c6cf..25f048adf 100644 --- a/docs/conf_common.py +++ b/docs/conf_common.py @@ -30,6 +30,11 @@ builddir = builddir if 'BUILDDIR' in os.environ: builddir = os.environ['BUILDDIR'] +def call_with_python(cmd): + # using sys.executable ensures that the scripts are called with the same Python interpreter + if os.system('{} {}'.format(sys.executable, cmd)) != 0: + raise RuntimeError('{} failed'.format(cmd)) + # Call Doxygen to get XML files from the header files print("Calling Doxygen to generate latest XML files") if os.system("doxygen ../Doxyfile") != 0: @@ -40,8 +45,7 @@ if os.system("doxygen ../Doxyfile") != 0: copy_if_modified('xml/', 'xml_in/') # Generate 'api_name.inc' files using the XML files by Doxygen -if os.system('python ../gen-dxd.py') != 0: - raise RuntimeError('gen-dxd.py failed') +call_with_python('../gen-dxd.py') # Generate 'kconfig.inc' file from components' Kconfig files print("Generating kconfig.inc from kconfig contents") @@ -49,22 +53,19 @@ kconfig_inc_path = '{}/inc/kconfig.inc'.format(builddir) temp_sdkconfig_path = '{}/sdkconfig.tmp'.format(builddir) kconfigs = subprocess.check_output(["find", "../../components", "-name", "Kconfig"]).decode() kconfig_projbuilds = subprocess.check_output(["find", "../../components", "-name", "Kconfig.projbuild"]).decode() -confgen_args = ["python", +call_with_python(" ".join( "../../tools/kconfig_new/confgen.py", "--kconfig", "../../Kconfig", "--config", temp_sdkconfig_path, "--create-config-if-missing", "--env", "COMPONENT_KCONFIGS={}".format(kconfigs), "--env", "COMPONENT_KCONFIGS_PROJBUILD={}".format(kconfig_projbuilds), - "--output", "docs", kconfig_inc_path + '.in' -] -subprocess.check_call(confgen_args) + "--output", "docs", kconfig_inc_path + '.in')) copy_if_modified(kconfig_inc_path + '.in', kconfig_inc_path) # Generate 'esp_err_defs.inc' file with ESP_ERR_ error code definitions esp_err_inc_path = '{}/inc/esp_err_defs.inc'.format(builddir) -if os.system('python ../../tools/gen_esp_err_to_name.py --rst_output ' + esp_err_inc_path + '.in') != 0: - raise RuntimeError('gen_esp_err_to_name.py failed') +call_with_python('../../tools/gen_esp_err_to_name.py --rst_output ' + esp_err_inc_path + '.in') copy_if_modified(esp_err_inc_path + '.in', esp_err_inc_path) # Generate version-related includes @@ -73,8 +74,7 @@ copy_if_modified(esp_err_inc_path + '.in', esp_err_inc_path) def generate_version_specific_includes(app): print("Generating version-specific includes...") version_tmpdir = '{}/version_inc'.format(builddir) - if os.system('python ../gen-version-specific-includes.py {} {}'.format(app.config.language, version_tmpdir)): - raise RuntimeError('gen-version-specific-includes.py failed') + call_with_python('../gen-version-specific-includes.py {} {}'.format(app.config.language, version_tmpdir)) copy_if_modified(version_tmpdir, '{}/inc'.format(builddir)) diff --git a/docs/docs_common.mk b/docs/docs_common.mk index c79cb0d4b..d4d623ec8 100644 --- a/docs/docs_common.mk +++ b/docs/docs_common.mk @@ -28,7 +28,7 @@ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) -w # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext dependencies version-specific-includes +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext dependencies version-specific-includes check_python_packages help: @echo "Please use \`make \' where is one of" @@ -58,38 +58,44 @@ help: clean: rm -rf $(BUILDDIR)/* -html: +# Notify users when some of the required python packages are not installed. +# Note: This is intended to help developers who generate the documentation on their local machine. Read The Docs uses +# the requirements.txt file directly and calls sphinx also directly without the use of the makefile! +check_python_packages: + $(IDF_PATH)/tools/check_python_dependencies.py -r $(IDF_PATH)/docs/requirements.txt + +html: | check_python_packages $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." -dirhtml: +dirhtml: | check_python_packages $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." -singlehtml: +singlehtml: | check_python_packages $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." -pickle: +pickle: | check_python_packages $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." -json: +json: | check_python_packages $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." -htmlhelp: +htmlhelp: | check_python_packages $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." -qthelp: +qthelp: | check_python_packages $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ @@ -98,7 +104,7 @@ qthelp: @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhc" -devhelp: +devhelp: | check_python_packages $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @@ -107,70 +113,70 @@ devhelp: @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ReadtheDocsTemplate" @echo "# devhelp" -epub: +epub: | check_python_packages $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." -latex: +latex: | check_python_packages $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." -latexpdf: +latexpdf: | check_python_packages $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." -latexpdfja: +latexpdfja: | check_python_packages $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." -text: +text: | check_python_packages $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." -man: +man: | check_python_packages $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." -texinfo: +texinfo: | check_python_packages $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." -info: +info: | check_python_packages $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." -gettext: +gettext: | check_python_packages $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." -changes: +changes: | check_python_packages $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." -linkcheck: +linkcheck: | check_python_packages $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." -gh-linkcheck: +gh-linkcheck: | check_python_packages @echo "Checking for hardcoded GitHub links" @if (find ../ -name '*.rst' | xargs grep \ 'https://github.com/espressif/esp-idf/tree\|https://github.com/espressif/esp-idf/blob\|https://github.com/espressif/esp-idf/raw'\ @@ -194,17 +200,17 @@ gh-linkcheck: fi @echo "No hardcoded links found" -doctest: +doctest: | check_python_packages $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." -xml: +xml: | check_python_packages $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." -pseudoxml: +pseudoxml: | check_python_packages $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/docs/en/api-guides/index.rst b/docs/en/api-guides/index.rst index 0a0f9c8e9..dd3dfeb2c 100644 --- a/docs/en/api-guides/index.rst +++ b/docs/en/api-guides/index.rst @@ -25,6 +25,6 @@ API Guides Console Component ROM debug console WiFi Driver - Mesh Stack + ESP-MESH BluFi External SPI-connected RAM diff --git a/docs/en/api-guides/mesh.rst b/docs/en/api-guides/mesh.rst index 4c252e792..87488be12 100644 --- a/docs/en/api-guides/mesh.rst +++ b/docs/en/api-guides/mesh.rst @@ -1,281 +1,1013 @@ ESP-MESH ======== +This guide provides information regarding the ESP-MESH protocol. Please see the +:doc:`MESH API Reference<../api-reference/mesh/esp_mesh>` for more information +about API usage. + +.. ------------------------------- Overview ----------------------------------- + Overview -------- -ESP-MESH is a "multi-hop" network, meaning that two or more wireless hops (intermediate connections of two Internet devices) are needed for conveying information from a source to a destination. Mesh networking (or mesh routing) is a type of network topology in which a device (node) transmits its own data, while serving as a relay for other nodes at the same time. The prerequisite for successful wireless mesh routing is that all mesh nodes need to be interconnected on the physical layer first. The mesh routing algorithm, then, chooses the transmission path among these physical-layer links. As a highly reliable, widely-covered Wireless Local-Area Network (WLAN) network, the ESP-MESH is ideal for wireless solutions covering a large open area (both outdoors and indoors). -ESP-MESH network is different from traditional wireless networks. The traditional wireless access technology implements a point-to-point or multipoint topology. There is generally one central node in such a topology, for example, a base station in a mobile communication system or an access point (AP) in an 802.11 WLAN. The central node and each wireless terminal are connected through single-hop wireless routing which controls each wireless terminal's access to the wireless network. Besides, the central node is connected to the backbone network through a wired link. In comparison, the ESP-MESH adopts a tree topology, with a root node, intermediate nodes and leaf nodes, making the network more expandable and fault-tolerant. Any mesh device on the network can compete to be the root node. Should the root node break down, the network will automatically select a new root node. This effectively decreases the tree topology’s dependence on a single node and allows every node to participate in the relay of information. +ESP-MESH is a networking protocol built atop the Wi-Fi protocol. ESP-MESH allows +numerous devices (henceforth referred to as nodes) spread over a large physical +area (both indoors and outdoors) to be interconnected under a single WLAN (Wireless +Local-Area Network). ESP-MESH is self-organizing and self-healing meaning the network +can be built and maintained autonomously. -.. figure:: ../../_static/mesh_network_architecture.png - :align: center - :alt: Mesh Network Architecture +The ESP-MESH guide is split into the following sections: - ESP-MESH Network Architecture +1. :ref:`mesh-introduction` + +2. :ref:`mesh-concepts` + +3. :ref:`mesh-building-a-network` + +4. :ref:`mesh-managing-a-network` + +5. :ref:`mesh-data-transmission` + +6. :ref:`mesh-network-performance` + +7. :ref:`mesh-further-notes` + + +.. ----------------------------- Introduction --------------------------------- + +.. _mesh-introduction: Introduction ------------ -ESP-MESH defines a network that organizes and heals itself, enabling faster networking and better control. -There are three types of nodes in a mesh network, in terms of their function within the mesh network: root node, intermediate node and leaf node. - -- Root node: this is the top node in the mesh network, which serves as the only interface between the mesh network and an external IP network. It functions as a gateway that relays packets outside the mesh network. - -- Intermediate node: a mesh node other than the root node and leaf nodes in a mesh network. An intermediate node can receive, send and forward the packets coming from its parent (immediately preceding) node, as well as its child (immediately following) nodes. - -- Leaf node: this is a mesh node that can only receive or send packets, but cannot forward packets. - -Each node that forwards data forms a parent/child node relationship with other nodes according to their position in the mesh network. The root node, through which the mesh network can communicate with an external IP network, is a node directly connected to the router and can transmit data between its child nodes and the router. The number of access devices and the bandwidth of the router directly affect the throughput of the root-node device, when accessing the external IP network. - -.. figure:: ../../_static/mesh_network_topology.png +.. figure:: ../../_static/mesh-traditional-network-architecture.png :align: center - :alt: Mesh Network Topology + :alt: Diagram of Traditional Network Architectures + :figclass: align-center - ESP-MESH Network Topology and Data Stream + Traditional Wi-Fi Network Architectures -As the above figure shows, node C and node D are intermediate nodes, while also being child nodes to the root node. Leaf E is the child node of node D. Leaf nodes A, B, and E have no child nodes. ESP-MESH is based on data link layer packet-forwarding, and no TCP/IP layer is needed in the mesh system except for the root node. See the figure “ESP-MESH Software Stack” for reference. +A traditional infrastructure Wi-Fi network is a point-to-multipoint network where a single +central node known as the access point (AP) is directly connected to all other +nodes known as stations. The AP is responsible for arbitrating and forwarding +transmissions between the stations. Some APs also relay transmissions to/from an +external IP network via a router. Traditional infrastructure Wi-Fi networks suffer the +disadvantage of limited coverage area due to the requirement that every station +must be in range to directly connect with the AP. Furthermore, traditional Wi-Fi +networks are susceptible to overloading as the maximum number of stations permitted +in the network is limited by the capacity of the AP. -Function Description --------------------- +.. figure:: ../../_static/mesh-esp-mesh-network-architecture.png + :align: center + :alt: Diagram of ESP-MESH Network Architecture + :figclass: align-center -1. Mesh Networking -^^^^^^^^^^^^^^^^^^^^^ -**(1) Mesh Configuration** + ESP-MESH Network Architecture -A router is mandatory during the ESP-MESH networking. Users need to configure the Service Set Identification (SSID), password and channel of the router for each node. If the router is hidden, users will need to configure the Basic Service Set Identification (BSSID) for the nodes.(For mesh configuration solutions, please refer to the link to Mesh IoT solutions. The link will be released soon.) - -The information needed for mesh networking is carried by the Vendor Information Element (VIE) in beacon frame, which includes the node type, the layer of the node in the network, the maximum number of layers allowed in the network, the number of child nodes, the maximum number of nodes allowed to be connected to a single node, and more. - -**(2) Root Node Election** - -If there is no root node in the network, all the mesh devices will broadcast the real-time signal strength (RSSI) with the router. Each device networking information, including the signal strength with the router, is transmitted to the entire mesh network, so that all mesh devices can use that infromation to choose the one with the strongest signal as the root node. - -POR, all devices are scanned separately. Each device selects the device with the greatest real-time signal strength, compared to the signal received by other devices from the router as well as to the strength of the router itself. The selection is, then, broadcast as a root-node candidate. - -Subsequently, each mesh device scans the mesh network for a second time, and selects the device with the greatest real-time signal strength as root-node candidate. The selection is broadcast again. This process is repeated until only one root-node candidate remains in the end. - -ESP-MESH also employs methods to accelerate the convergence of the root node election. - -**(3) Parent Node Selection** - -ESP-MESH provides a method for selecting the strongest parent node in a mesh network. According to this method, a node obtains information about other nodes from received VIE messages, and generates a set of parent nodes. If the parent set comprises at least two nodes, the one with the highest performance parameter is selected as the preferred parent. According to this method, a preferred parent node is selected because of the node type and the performance parameter of each node in the parent set. This method ensures that the preferred parent is the optimal one, thus reducing packet loss rate which, in turn, improves network performance. - -2. Routing Generation and Maintenance -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +ESP-MESH differs from traditional infrastructure Wi-Fi networks in that nodes are not required +to connect to a central node. Instead, nodes are permitted to connect with +neighboring nodes. Nodes are mutually responsible for relaying each others +transmissions. This allows an ESP-MESH network to have much greater coverage area +as nodes can still achieve interconnectivity without needing to be in range of +the central node. Likewise, ESP-MESH is also less susceptible to overloading as +the number of nodes permitted on the network is no longer limited by a single +central node. -3. Network Management +.. -------------------------- ESP-MESH Concepts ------------------------------- + +.. _mesh-concepts: + +ESP-MESH Concepts +----------------- + +Terminology +^^^^^^^^^^^ + ++--------------------------+----------------------------------------------------------------+ +| Term | Description | ++==========================+================================================================+ +| Node | Any device that **is** or **can be** part of an ESP-MESH | +| | network | ++--------------------------+----------------------------------------------------------------+ +| Root Node | The top node in the network | ++--------------------------+----------------------------------------------------------------+ +| Child Node | A node X is a child node when it is connected to another node | +| | Y where the connection makes node X more distant from the root | +| | node than node Y (in terms of number of connections). | ++--------------------------+----------------------------------------------------------------+ +| Parent Node | The converse notion of a child node | ++--------------------------+----------------------------------------------------------------+ +| Sub-Child Node | Any node reachable by repeated proceeding from parent to child | ++--------------------------+----------------------------------------------------------------+ +| Sibling Nodes | Nodes that share the same parent node | ++--------------------------+----------------------------------------------------------------+ +| Connection | A traditional Wi-Fi association between an AP and a station. | +| | A node in ESP-MESH will use its station interface to associate | +| | with the softAP interface of another node, thus forming a | +| | connection. The connection process includes the authentication | +| | and association processes in Wi-Fi. | ++--------------------------+----------------------------------------------------------------+ +| Upstream Connection | The connection from a node to its parent node | ++--------------------------+----------------------------------------------------------------+ +| Downstream Connection | The connection from a node to one of its child nodes | ++--------------------------+----------------------------------------------------------------+ +| Wireless Hop | The portion of the path between source and destination nodes | +| | that corresponds to a single wireless connection. A data | +| | packet that traverses a single connection is known as | +| | **single-hop** whereas traversing multiple connections is | +| | known as **multi-hop**. | ++--------------------------+----------------------------------------------------------------+ +| Subnetwork | A subnetwork is subdivision of an ESP-MESH network which | +| | consists of a node and all of its descendant nodes. Therefore | +| | the subnetwork of the root node consists of all nodes in an | +| | ESP-MESH network. | ++--------------------------+----------------------------------------------------------------+ +| MAC Address | Media Access Control Address used to uniquely identify each | +| | node or router within an ESP-MESH network. | ++--------------------------+----------------------------------------------------------------+ +| DS | Distribution System (External IP Network) | ++--------------------------+----------------------------------------------------------------+ + +Tree Topology +^^^^^^^^^^^^^ + +ESP-MESH is built atop the infrastructure Wi-Fi protocol and can be thought of +as a networking protocol that combines many individual Wi-Fi networks into a single +WLAN. In Wi-Fi, stations are limited to a single connection with an AP (upstream +connection) at any time, whilst an AP can be simultaneously connected to multiple +stations (downstream connections). However ESP-MESH allows nodes to simultaneously +act as a station and an AP. Therefore a node in ESP-MESH can have **multiple downstream +connections using its softAP interface**, whilst simultaneously having **a single +upstream connection using its station interface**. This naturally results in a +tree network topology with a parent-child hierarchy consisting of multiple layers. + +.. figure:: ../../_static/mesh-tree-topology.png + :align: center + :alt: Diagram of ESP-MESH Tree Topology + :figclass: align-center + + ESP-MESH Tree Topology + +ESP-MESH is a multiple hop (multi-hop) network meaning nodes can transmit packets +to other nodes in the network through one or more wireless hops. Therefore, nodes +in ESP-MESH not only transmit their own packets, but simultaneously serve as relays +for other nodes. Provided that a path exists between any two nodes on the physical +layer (via one or more wireless hops), any pair of nodes within an ESP-MESH network +can communicate. + +.. note:: + The size (total number of nodes) in an ESP-MESH network is dependent on the + maximum number of layers permitted in the network, and the maximum number of + downstream connections each node can have. Both of these variables can be + configured to limit the size of the network. + +Node Types +^^^^^^^^^^ + +.. figure:: ../../_static/mesh-node-types.png + :align: center + :alt: Diagram of ESP-MESH Node Types + :figclass: align-center + + ESP-MESH Node Types + +**Root Node:** The root node is the top node in the network and serves as the only +interface between the ESP-MESH network and an external IP network. The root node +is connected to a conventional Wi-Fi router and relays packets to/from the external +IP network to nodes within the ESP-MESH network. **There can only be one root node +within an ESP-MESH network** and the root node's upstream connection may only be +with the router. Referring to the diagram above, node A is the root node of the +network. + +**Leaf Nodes:** A leaf node is a node that is not permitted to have any child nodes +(no downstream connections). Therefore a leaf node can only transmit or receive +its own packets, but cannot forward the packets of other nodes. If a node is situated +on the network's maximum permitted layer, it will be assigned as a leaf node. This +prevents the node from forming any downstream connections thus ensuring the network +does not add an extra layer. Some nodes without a softAP interface (station only) +will also be assigned as leaf nodes due to the requirement of a softAP interface +for any downstream connections. Referring to the diagram above, nodes L/M/N are +situated on the networks maximum permitted layer hence have been assigned as leaf nodes . + +**Intermediate Parent Nodes:** Connected nodes that are neither the root node or +a leaf node are intermediate parent nodes. An intermediate parent node must have +a single upstream connection (a single parent node), but can have zero to multiple +downstream connections (zero to multiple child nodes). Therefore an intermediate +parent node can transmit and receive packets, but also forward packets sent from its +upstream and downstream connections. Referring to the diagram above, nodes +B to J are intermediate parent nodes. **Intermediate parent nodes without downstream +connections such as nodes E/F/G/I/J are not equivalent to leaf nodes** as they +are still permitted to form downstream connections in the future. + +**Idle Nodes:** Nodes that have yet to join the network are assigned as idle nodes. +Idle nodes will attempt to form an upstream connection with an intermediate parent +node or attempt to become the root node under the correct circumstances (see +`Automatic Root Node Selection`_). Referring to the diagram above, nodes K and O +are idle nodes. + +Beacon Frames & RSSI Thresholding +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Every node in ESP-MESH that is able to form downstream connections (i.e. has a +softAP interface) will periodically transmit Wi-Fi beacon frames. A node uses +beacon frames to allow other nodes to detect its presence and know of its status. +Idle nodes will listen for beacon frames to generate a list of potential parent nodes, +one of which the idle node will form an upstream connection with. ESP-MESH uses +the Vendor Information Element to store metadata such as: + +- Node Type (Root, Intermediate Parent, Leaf, Idle) +- Current layer of Node +- Maximum number of layers permitted in the network +- Current number of child nodes +- Maximum number of downstream connections to accept + +The signal strength of a potential upstream connection is represented by RSSI +(Received Signal Strength Indication) of the beacon frames of the potential parent +node. To prevent nodes from forming a weak upstream connection, ESP-MESH implements +an RSSI threshold mechanism for beacon frames. If a node detects a beacon frame +with an RSSI below a preconfigured threshold, the transmitting node will be +disregarded when forming an upstream connection. + +.. figure:: ../../_static/mesh-beacon-frame-rssi.png + :align: center + :alt: Diagram of the Effects of RSSI Thresholding + :figclass: align-center + + Effects of RSSI Thresholding + +**Panel A** of the illustration above demonstrates how the RSSI threshold affects +the number of parent node candidates an idle node has. + +**Panel B** of the illustration above demonstrates how an RF shielding object can +lower the RSSI of a potential parent node. Due to the RF shielding object, the +area in which the RSSI of node X is above the threshold is significantly reduced. +This causes the idle node to disregard node X even though node X is physically +adjacent. The idle node will instead form an upstream connection with the physically +distant node Y due to a stronger RSSI. + +.. note:: + Nodes technically still receive all beacon frames on the MAC layer. The RSSI + threshold is an ESP-MESH feature that simply filters out all received beacon + frames that are below the preconfigured threshold. + +Preferred Parent Node ^^^^^^^^^^^^^^^^^^^^^ -+-----------------------+------------------------------------------------------------------------------------------+ -| Function | Description | -+=======================+==========================================================================================+ -|Self-healing |Self-healing allows such routing-based network to operate when a node breaks down or when | -| |a connection becomes unreliable. | -| | | -| |If a root node breaks down, the nodes directly connected with it on the second layer will | -| |detect the root-node failure quickly and initialize a new round of root node election. If | -| |the root node and all the nodes on the second layer break down, the nodes on the third | -| |layer will initialize root node election and a new root node will be elected eventually. | -| | | -| |In the event of a failure of the intermediate nodes and the leaf nodes, failed nodes will | -| |reconnect their parent nodes respectively for a predefined number of times and will, then,| -| |reselect a new parent node to join the mesh network. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Root node switch |Users can call :cpp:func:`esp_mesh_waive_root` to switch root nodes in the network. | -| |The new root node can be specified by the users or be automatically elected by the | -| |network. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Root conflicts handling|Only the conflicts of root nodes connecting to the same router are handled. Conflicts of | -| |root nodes having the same router SSID, but different router BSSID, are not handled. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Parent node switch |Changing the physical position of a node in the mesh network will lead to declined signal | -| |strength of the parent node and problematic communication. Upon detecting such a problem, | -| |this function will automatically choose a better parent node for this node. | -| | | -| |When the position of a mobile node changes constantly, communication with the parent node | -| |deteriorates or even drops. After such a situation is detected, the parent of the mobile | -| |node is automatically reselected, so that communication with the network is maintained. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Loopback avoidance, |During the parent selection, the nodes covered in its own routing table are excluded, | -|detection and handling |so that the occurrence of a loopback is avoided. | -| | | -| |The path verification mechanism and the energy transfer mechanism are used for detecting | -| |the loopback. | -| | | -| |When a loopback is detected, the parent node will disconnect with the child node and | -| |inform it about the occurrence of the loop with a predefined reason code. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Channel switch |TO-DO | -+-----------------------+------------------------------------------------------------------------------------------+ -|Isolated node avoidance|TO-DO | -|and handling | | -+-----------------------+------------------------------------------------------------------------------------------+ +When an idle node has multiple parent nodes candidates (potential parent nodes), +the idle node will form an upstream connection with the **preferred parent node**. +The preferred parent node is determined based on the following criteria: -4. Data Transmission -^^^^^^^^^^^^^^^^^^^^ +- Which layer the parent node candidate is situated on +- The number of downstream connections (child nodes) the parent node candidate currently has -+-----------------------+------------------------------------------------------------------------------------------+ -| Function | Description | -+=======================+==========================================================================================+ -|Reliability |ESP-MESH provides P2P(point-to-point) retransmission on mesh layer. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Upstream flow control |When a node in the mesh network is chosen as a parent node, the upstream data of each of | -| |its child nodes is allocated a receiving window, the size of which can be dynamically | -| |adjusted. The child node sends a window request to the parent node before sending data | -| |packets. The parent node compares the request’s sequence number, which corresponds to the | -| |child node's pending packet in the window request, with the sequence number of the parent | -| |node's most recently received packet from the child node. The size of the receiving window| -| |is calculated and returned to the child node. The child node, then, sends the packet, | -| |according to the reply’s receiving-window size. | -| | | -| |In addition, considering that there is only one exit from the entire mesh network, which | -| |is the root node, it is only the root node which can access external IP networks. If the | -| |other nodes are uninformed of the connection status between the root node and the external| -| |network, and keep sending packets to the root node, there is a possibility of packet loss | -| |or unnecessary packet-sending. ESP-MESH provides a method of flow control on the upstream | -| |data, which stabilizes the throughput of the mesh network’s exit by monitoring the | -| |connection status between the root node and the external network, thus avoiding packet | -| |loss or unnecessary packet-sending. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Supporting multicast |Only specified devices can receive multicast packets. Thus, users need to specify these | -|packets |devices by configuring the relevant input parameters for the API :cpp:func:`esp_mesh_send`| -+-----------------------+------------------------------------------------------------------------------------------+ -|Supporting broadcast |ESP-MESH provides a method to avoid a waste of bandwidth. | -|packets | | -| |1. When the broadcast packet transmitted by the intermediate node has been received from | -| |its parent node, the intermediate node sends itself a copy of the broadcast packet, while | -| |sending the original broadcast packet to its child nodes. | -| | | -| |2. When a broadcast packet transmitted by an intermediate node has been generated by | -| |itself, the broadcast packet is sent both to its parent and child nodes. | -| | | -| |3. When a broadcast packet transmitted by an intermediate node has been received from its | -| |child node, the broadcast packet is delivered to the intermediate node itself and its | -| |remaining child nodes, while a copy of the broadcast packet is transmitted to the | -| |intermediate’s parent node. | -| | | -| |4. When a leaf node generates a broadcast packet, the leaf node sends the broadcast packet| -| |to its parent node directly. | -| | | -| |5. When the broadcast packet transmitted by the root node has been generated by the root | -| |node itself, the broadcast packet is delivered to the root’s child node. | -| | | -| |6. When the broadcast packet transmitted by the root node has been received from its child| -| |node, the broadcast packet is sent to the remaining child nodes of the root node. | -| | | -| |7. When a node receives a broadcast packet initially sent from the address of the node | -| |itself, it discards this broadcast packet. | -| | | -| |8. When a node receives a broadcast packet from its parent node, which has been originally| -| |sent from its own child node, it discards this broadcast packet. | -+-----------------------+------------------------------------------------------------------------------------------+ -|Group control |Firsty users must specify a group ID for the device via :cpp:func:`esp_mesh_set_group_id`.| -| |Then when one packet is sent target to this group, only devices in this group can receive | -| |it. | -+-----------------------+------------------------------------------------------------------------------------------+ +The selection of the preferred parent node will always prioritize the parent node +candidate on the shallowest layer of the network (including the root node). This +helps minimize the total number of layers in an ESP-MESH network when upstream +connections are formed. For example, given a second layer node and a third layer +node, the second layer node will always be preferred. -5. Performance +If there are multiple parent node candidates within the same layer, the parent +node candidate with the least child nodes will be preferred. This criteria has +the effect of balancing the number of downstream connections amongst nodes of +the same layer. + +.. figure:: ../../_static/mesh-preferred-parent-node.png + :align: center + :alt: Diagram of Preferred Parent Node Selection + :figclass: align-center + + Preferred Parent Node Selection + +**Panel A** of the illustration above demonstrates an example of how the idle +node G selects a preferred parent node given the five parent node candidates +B/C/D/E/F. Nodes on the shallowest layer are preferred, hence nodes B/C are +prioritized since they are second layer nodes whereas nodes D/E/F are on the +third layer. Node C is selected as the preferred parent node due it having fewer +downstream connections (fewer child nodes) compared to node B. + +**Panel B** of the illustration above demonstrates the case where the root node +is within range of the idle node G. In other words, the root node's beacon frames +are above the RSSI threshold when received by node G. The root node is always the +shallowest node in an ESP-MESH network hence is always the preferred parent node +given multiple parent node candidates. + +.. note:: + Users may also define their own algorithm for selecting a preferred parent + node, or force a node to only connect with a specific parent node (see the + :example:`Mesh Manual Networking Example`). + +Routing Tables ^^^^^^^^^^^^^^ -+--------------------+------------------------------------------------------------------------------------------+ -| Function | Description | -+====================+==========================================================================================+ -|Networking time |Less than 15 seconds. The time is from tests executed on a network with 50 devices. | -+--------------------+------------------------------------------------------------------------------------------+ -|Healing time |If a root node breaks down, less than 10 seconds is taken for the network to detect that | -| |and generate a new root. If a parent node breaks down, less than 5 seconds is taken for | -| |its child nodes to detect that and reselect a new parent node. | -| |The time is also from tests executed on a network with 50 devices. | -+--------------------+------------------------------------------------------------------------------------------+ -|Layer forward delay |30ms. The delay is from tests executed on a network with 100 devices and all devices did | -| |not enable AMPDU. | -+--------------------+------------------------------------------------------------------------------------------+ -|Packet loss rate |max: %0.32 in data transmitted from layer 2 to layer 4; min: %0.00 | -| |The results are also from tests executed on a network with 100 devices. | -+--------------------+------------------------------------------------------------------------------------------+ -|Network capacity |The network capacity is terminated by the maximum number of devices allowed to be | -| |connected to the softAP, and by the maximum number of network layers allowed in the | -| |network. | -+--------------------+------------------------------------------------------------------------------------------+ +Each node within an ESP-MESH network will maintain its individual routing table +used to correctly route ESP-MESH packets (see `ESP-MESH Packet`_) to the correct +destination node. The routing table of a particular node will **consist of the +MAC addresses of all nodes within the particular node's subnetwork** (including +the MAC address of the particular node itself). Each routing table is internally +partitioned into multiple subtables with each subtable corresponding to the +subnetwork of each child node. -**Note:** All device are configured 6 connections and 6 layers during the above mentioned tests. +.. figure:: ../../_static/mesh-routing-tables-example.png + :align: center + :alt: Diagram of ESP-MESH Routing Tables Example + :figclass: align-center -6. Security and Encryption -^^^^^^^^^^^^^^^^^^^^^^^^^^ -**(1) Uses WPA2-PSK** + ESP-MESH Routing Tables Example -**(2) AES Encryption for Mesh VIE** +Using the diagram above as an example, the routing table of node B would consist +of the MAC addresses of nodes B to I (i.e. equivalent to the subnetwork of node +B). Node B's routing table is internally partitioned into two subtables containing +of nodes C to F and nodes G to I (i.e. equivalent to the subnetworks of nodes C +and G respectively). -7. Power Management (TO-DO) +**ESP-MESH utilizes routing tables to determine whether an ESP-MESH packet should +be forwarded upstream or downstream based on the following rules.** + +**1.** If the packet's destination MAC address is within the current node's routing +table and is not the current node, select the subtable that contains the destination +MAC address and forward the data packet downstream to the child node corresponding +to the subtable. + +**2.** If the destination MAC address is not within the current node's routing table, +forward the data packet upstream to the current node's parent node. Doing so repeatedly +will result in the packet arriving at the root node where the routing table should +contain all nodes within the network. + +.. note:: + Users can call :cpp:func:`esp_mesh_get_routing_table` to obtain a node's routing + table, or :cpp:func:`esp_mesh_get_routing_table_size` to obtain the size of a + node's routing table. + + :cpp:func:`esp_mesh_get_subnet_nodes_list` can be used to obtain the corresponding + subtable of a specific child node. Likewise, :cpp:func:`esp_mesh_get_subnet_nodes_num` + can be used to obtain the size of the subtable. + + +.. ------------------------ Building a Mesh Network --------------------------- + +.. _mesh-building-a-network: + +Building a Network +------------------ + +General Process +^^^^^^^^^^^^^^^ + +.. warning:: + Before the ESP-MESH network building process can begin, certain parts of the + configuration must be uniform across each node in the network (see + :cpp:type:`mesh_cfg_t`). Each node must be configured with **the same Mesh + Network ID, router configuration, and softAP configuration**. + +An ESP-MESH network building process involves selecting a root node, then forming +downstream connections layer by layer until all nodes have joined the network. The exact +layout of the network can be dependent on factors such as root node selection, +parent node selection, and asynchronous power-on reset. However, the ESP-MESH network +building process can be generalized into the following steps: + +.. figure:: ../../_static/mesh-network-building.png + :align: center + :alt: Diagram of ESP-MESH Network Building Process + :figclass: align-center + + ESP-MESH Network Building Process + +1. Root Node Selection +"""""""""""""""""""""" +The root node can be designated during configuration (see section on +`User Designated Root Node`_), or dynamically elected based on the signal strength +between each node and the router (see `Automatic Root Node Selection`_). Once selected, +the root node will connect with the router and begin allowing downstream connections +to form. Referring to the figure above, node A is selected to be the root node +hence node A forms an upstream connection with the router. + +2. Second Layer Formation +""""""""""""""""""""""""" +Once the root node has connected to the router, idle nodes in range of the root +node will begin connecting with the root node thereby forming the second layer +of the network. Once connected, the second layer nodes become intermediate parent +nodes (assuming maximum permitted layers > 2) hence the next layer to form. Referring +to the figure above, nodes B to D are in range of the root node. Therefore nodes +B to D form upstream connections with the root node and become intermediate parent +nodes. + +3. Formation of remaining layers +"""""""""""""""""""""""""""""""" +The remaining idle nodes will connect with intermediate parent nodes within range +thereby forming a new layer in the network. Once connected, the idles nodes become +intermediate parent node or leaf nodes depending on the networks maximum permitted +layers. This step is repeated until there are no more idle nodes within the network +or until the maximum permitted layer of the network has been reached. Referring to +the figure above, nodes E/F/G connect with nodes B/C/D respectively and become +intermediate parent nodes themselves. + +4. Limiting Tree Depth +"""""""""""""""""""""" +To prevent the network from exceeding the maximum permitted number of layers, nodes +on the maximum layer will automatically become leaf nodes once connected. This +prevents any other idle node from connecting with the leaf node thereby prevent +a new layer form forming. However if an idle node has no other potential parent +node, it will remain idle indefinitely. Referring to the figure above, the network's +maximum permitted layers is set to four. Therefore when node H connects, it becomes +a leaf node to prevent any downstream connections from forming. + +Automatic Root Node Selection +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The automatic selection of a root node involves an election process amongst +all idle nodes based on their signal strengths with the router. Each idle node +will transmit their MAC addresses and router RSSI values via Wi-Fi beacon frames. +**The MAC address is used to uniquely identify each node in the network** whilst +the **router RSSI** is used to indicate a node's signal strength with reference to +the router. + +Each node will then simultaneously scan for the beacon frames from other idle nodes. +If a node detects a beacon frame with a stronger router RSSI, the node will begin +transmitting the contents of that beacon frame (i.e. voting for the node with +the stronger router RSSI). The process of transmission and scanning will repeat +for a preconfigured minimum number of iterations (10 iterations by default) and result +in the beacon frame with the strongest router RSSI being propagated throughout +the network. + +After all iterations, each node will individually check for its **vote percentage** +(``number of votes/number of nodes participating in election``) to determine if it should become the +root node. **If a node has a vote percentage larger than a preconfigured threshold +(90% by default), the node will become a root node**. + +The following diagram demonstrates how an ESP-MESH network is built when the root +node is automatically selected. + +.. figure:: ../../_static/mesh-root-node-election-example.png + :align: center + :alt: Diagram of Root Node Election Process Example + :figclass: align-center + + Root Node Election Example + +**1.** On power-on reset, each node begins transmitting beacon frames consisting +of their own MAC addresses and their router RSSIs. + +**2.** Over multiple iterations of transmission and scanning, the beacon frame +with the strongest router RSSI is propagated throughout the network. Node C has +the strongest router RSSI (-10db) hence its beacon frame is propagated throughout the +network. All nodes participating in the election vote for node C thus giving node +C a vote percentage of 100%. Therefore node C becomes a root node and connects with +the router. + +**3.** Once Node C has connected with the router, nodes A/B/D/E connect +with node C as it is the preferred parent node (i.e. the shallowest node). Nodes +A/B/D/E form the second layer of the network. + +**4.** Node F and G connect with nodes D and E respectively and the network building +process is complete. + +.. note:: + The minimum number of iterations for the election process can be configured + using :cpp:func:`esp_mesh_set_attempts`. Users should adjust the number + of iterations based on the number of nodes within the network (i.e. the larger + the network the larger number of scan iterations required). + +.. warning:: + **Vote percentage threshold** can also be configured using + :cpp:func:`esp_mesh_set_vote_percentage`. Setting a low vote percentage + threshold **can result in two or more nodes becoming root nodes** within the + same ESP-MESH network leading to the building of multiple networks. If + such is the case, ESP-MESH has internal mechanisms to autonomously resolve + the **root node conflict**. The networks of the multiple root nodes will be + combined into a single network with a single root node. However, root node + conflicts where two or more root nodes have the same router SSID but different + router BSSID are not handled. + +User Designated Root Node +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The root node can also be designated by user which will entail the designated root node +to directly connect with the router and forgo the election process. When a root +node is designated, all other nodes within the network must also forgo the election +process to prevent the occurrence of a root node conflict. The following diagram demonstrates +how an ESP-MESH network is built when the root node is designated by the user. + +.. figure:: ../../_static/mesh-root-node-designated-example.png + :align: center + :alt: Diagram of Root Node Designation Process Example + :figclass: align-center + + Root Node Designation Example (Root Node = A, Max Layers = 4) + +**1.** Node A is designated the root node by the user therefore directly connects +with the router. All other nodes forgo the election process. + +**2.** Nodes C/D connect with node A as their preferred parent node. Both +nodes form the second layer of the network. + +**3.** Likewise, nodes B/E connect with node C, and node F connects with +node D. Nodes B/E/F form the third layer of the network. + +**4.** Node G connects with node E, forming the fourth layer of the network. +However the maximum permitted number of layers in this network is configured as +four, therefore node G becomes a leaf node to prevent any new layers from forming. + +.. note:: + When designating a root node, the root node should call :cpp:func:`esp_mesh_set_parent` + in order to directly connect with the router. Likewise, all other nodes should + call :cpp:func:`esp_mesh_fix_root` to forgo the election process. + +Parent Node Selection +^^^^^^^^^^^^^^^^^^^^^ + +By default, ESP-MESH is self organizing meaning that each node will autonomously +select which potential parent node to form an upstream connection with. The autonomously +selected parent node is known as the preferred parent node. The criteria used for +selecting the preferred parent node is designed to reduce the number of layers in +the ESP-MESH network and to balance the number of downstream connections between +potential parent nodes (see section on `Preferred Parent Node`_). + +However ESP-MESH also allows users to disable self-organizing behavior which will +allow users to define their own criteria for parent node selection, or to configure +nodes to have designated parent nodes (see the +:example:`Mesh Manual Networking Example`). + +Asynchronous Power-on Reset ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -**(1) Network Sleep** -**(2) Standalone Station** +ESP-MESH network building can be affected by the order in which nodes power-on. +If certain nodes within the network power-on asynchronously (i.e. separated by +several minutes), **the final structure of the network could differ from the ideal +case where all nodes are powered on synchronously**. Nodes that are delayed in +powering on will adhere to the following rules: -8. User Intervention Network (TO-DO) -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -+-----------------------+---------------------------------------------------------------------------------------+ -| Function | Description | -+=======================+=======================================================================================+ -|Specifying the node |The user designates a node in the network as the root node, intermediate node or leaf | -|type |node. | -+-----------------------+---------------------------------------------------------------------------------------+ -|Specifying the parent |The user designates a parent node for a certain node. | -|type | | -+-----------------------+---------------------------------------------------------------------------------------+ -|Specifying the layer |The user designates the layer in which the above-mentioned node is to be located. | -+-----------------------+---------------------------------------------------------------------------------------+ +**Rule 1:** If a root node already exists in the network, the delayed node will +not attempt to elect a new root node, even if it has a stronger RSSI with the router. +The delayed node will instead join the network like any other idle node by connecting +with a preferred parent node. If the delayed node is the designated root node, +all other nodes in the network will remain idle until the delayed node powers-on. -How to Write a Mesh Application -------------------------------- +**Rule 2:** If a delayed node forms an upstream connection and becomes an intermediate +parent node, it may also become the new preferred parent of other nodes (i.e. being +a shallower node). This will cause the other nodes to switch their upstream connections +to connect with the delayed node (see `Parent Node Switching`_). -**ESP-MESH API Error Code** +**Rule 3:** If an idle node has a designated parent node which is delayed in powering-on, +the idle node will not attempt to form any upstream connections in the absence of +its designated parent node. The idle node will remain idle indefinitely until its +designated parent node powers-on. -We suggest that users regularly check the error code and add relevant handlers accordingly. +The following example demonstrates the effects of asynchronous power-on with regards +to network building. -ESP-MESH Programming Model --------------------------- - -**Software Stack is demonstrated below:** - -.. figure:: ../../_static/mesh_software_stack.png +.. figure:: ../../_static/mesh-asynchronous-power-on-example.png :align: center - :alt: ESP-MESH Software Stack + :alt: Diagram of Asynchronous Power On Example + :figclass: align-center - ESP-MESH Software Stack + Network Building with Asynchronous Power On Example -**System Events delivery is demonstrated below:** +**1.** Nodes A/C/D/F/G/H are powered-on synchronously and begin the root +node election process by broadcasting their MAC addresses and router RSSIs. Node +A is elected as the root node as it has the strongest RSSI. -.. figure:: ../../_static/mesh_events_delivery.png +**2.** Once node A becomes the root node, the remaining nodes begin forming upstream +connections layer by layer with their preferred parent nodes. The result is a network +with five layers. + +**3.** Node B/E are delayed in powering-on but neither attempt to become the root +node even though they have stronger router RSSIs (-20db and -10db) compared to +node A. Instead both delayed nodes form upstream connections with their preferred +parent nodes A and C respectively. Both Nodes B/E become intermediate parent nodes +after connecting. + +**4.** Nodes D/G switch their upstream connections as node B is the new preferred +parent node due to it being on a shallower layer (second layer node). Due to the +switch, the resultant network has three layers instead of the original five layers. + +**Synchronous Power-On:** Had all nodes powered-on synchronously, node E would +have become the root node as it has the strongest router RSSI (-10db). This +would result in a significantly different network layout compared to the network +formed under the conditions of asynchronous power-on. **However the synchronous +power-on network layout can still be reached if the user manually switches the +root node** (see :cpp:func:`esp_mesh_waive_root`). + +.. note:: + Differences in parent node selection caused by asynchronous power-on are + autonomously corrected for to some extent in ESP-MESH (see `Parent Node Switching`_) + +Loop-back Avoidance, Detection, and Handling +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A loop-back is the situation where a particular node forms an upstream connection +with one of its descendant nodes (a node within the particular node's subnetwork). +This results in a circular connection path thereby breaking the tree topology. +ESP-MESH prevents loop-back during parent selection by excluding nodes already +present in the selecting node's routing table (see `Routing Tables`_) thus prevents +a particular node from attempting to connect to any node within its subnetwork. + +In the event that a loop-back occurs, ESP-MESH utilizes a path verification +mechanism and energy transfer mechanism to detect the loop-back occurrence. The +parent node of the upstream connection that caused the loop-back will then inform +the child node of the loop-back and initiate a disconnection. + +.. -------------------------- Network Management ------------------------------ + +.. _mesh-managing-a-network: + +Managing a Network +------------------ + +**ESP-MESH is a self healing network meaning it can detect and correct for failures +in network routing**. Failures occur when a parent node with one or more child +nodes breaks down, or when the connection between a parent node and its child nodes +becomes unstable. Child nodes in ESP-MESH will autonomously select a new parent +node and form an upstream connection with it to maintain network interconnectivity. +ESP-MESH can handle both Root Node Failures and Intermediate Parent Node Failures. + +Root Node Failure +^^^^^^^^^^^^^^^^^ + +If the root node breaks down, the nodes connected with it (second layer nodes) +will promptly detect the failure of the root node. The second layer nodes +will initially attempt to reconnect with the root node. However after multiple failed +attempts, the second layer nodes will initialize a new round of root node election. +**The second layer node with the strongest router RSSI will be elected as the new +root node** whilst the remaining second layer nodes will form an upstream connection +with the new root node (or a neighboring parent node if not in range). + +If the root node and multiple downstream layers simultaneously break down (e.g. +root node, second layer, and third layer), the shallowest layer that is still +functioning will initialize the root node election. The following example illustrates +an example of self healing from a root node break down. + +.. figure:: ../../_static/mesh-root-node-failure.png :align: center - :alt: System Events Delivery + :alt: Diagram of Self Healing From Root Node Failure + :figclass: align-center - ESP-MESH System Events Delivery + Self Healing From Root Node Failure + +**1.** Node C is the root node of the network. Nodes A/B/D/E are second layer +nodes connected to node C. + +**2.** Node C breaks down. After multiple failed attempts to reconnect, the second +layer nodes begin the election process by broadcasting their router RSSIs. Node +B has the strongest router RSSI. + +**3.** Node B is elected as the root node and begins accepting downstream +connections. The remaining second layer nodes A/D/E form upstream connections with +node B thus the network is healed and can continue operating normally. + +.. note:: + If a designated root node breaks down, the remaining nodes **will not autonomously + attempt to elect a new root node** as an election process will never be attempted + whilst a designated root node is used. + +Intermediate Parent Node Failure +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If an intermediate parent node breaks down, the disconnected child nodes will initially +attempt to reconnect with the parent node. After multiple failed attempts to reconnect, +each child node will begin to scan for potential parent nodes (see +`Beacon Frames & RSSI Thresholding`_). + +If other potential parent nodes are available, each child node will individually +select a new preferred parent node (see `Preferred Parent Node`_) and form an upstream +connection with it. If there are no other potential parent nodes for a particular +child node, it will remain idle indefinitely. + +The following diagram illustrates an example of self healing from an Intermediate +Parent Node break down. + +.. figure:: ../../_static/mesh-parent-node-failure.png + :align: center + :alt: Diagram of Self Healing From Intermediate Parent Node Failure + :figclass: align-center + + Self Healing From Intermediate Parent Node Failure + +**1.** The following branch of the network consists of nodes A to G. + +**2.** Node C breaks down. Nodes F/G detect the break down and attempt to +reconnect with node C. After multiple failed attempts to reconnect, nodes F/G begin +to select a new preferred parent node. + +**3.** Node G is out of range from any other parent node hence remains idle for +the time being. Node F is in range of nodes B/E, however node B is selected as +it is the shallower node. Node F becomes an intermediate parent node after +connecting with Node B thus node G can connect with node F. The network is healed, +however the network routing as been affected and an extra layer has been added. + +.. note:: + If a child node has a designated parent node that breaks down, the child node + will make no attempt to connect with a new parent node. The child node will + remain idle indefinitely. + +Root Node Switching +^^^^^^^^^^^^^^^^^^^ + +ESP-MESH does not automatically switch the root node unless the root node breaks down. Even +if the root node's router RSSI degrades to the point of disconnection, the root node +will remain unchanged. Root node switching is the act of explicitly starting +a new election such that a node with a stronger router RSSI will be elected as the +new root node. This can be a useful method of adapting to degrading root node performance. + +To trigger a root node switch, the current root node must explicitly call :cpp:func:`esp_mesh_waive_root` +to trigger a new election. The current root node will signal all nodes within +the network to begin transmitting and scanning for beacon frames (see `Automatic +Root Node Selection`_) **whilst remaining connected to the network (i.e. not idle)**. +If another node receives more votes than the current root node, a root node switch +will be initiated. **The root node will remain unchanged otherwise**. + +A newly elected root node sends a **switch request** to the current root node +which in turn will respond with an acknowledgment signifying both nodes are ready to +switch. Once the acknowledgment is received, the newly elected root node will +disconnect from its parent and promptly form an upstream connection with the router +thereby becoming the new root node of the network. The previous root node will +disconnect from the router **whilst maintaining all of its downstream connections** +and enter the idle state. The previous root node will then begin scanning for +potential parent nodes and selecting a preferred parent. + +The following diagram illustrates an example of a root node switch. + +.. figure:: ../../_static/mesh-root-node-switch-example.png + :align: center + :alt: Diagram of Root Node Switch Example + :figclass: align-center + + Root Node Switch Example + +**1.** Node C is the current root node but has degraded signal strength with the +router (-85db). The node C triggers a new election and all nodes begin transmitting +and scanning for beacon frames **whilst still being connected**. + +**2.** After multiple rounds of transmission and scanning, node B is elected as +the new root node. Node B sends node C a **switch request** and node C responds +with an acknowledgment. + +**3.** Node B disconnects from its parent and connects with the router becoming +the networks new root node. Node C disconnects from the router, enters the idle +state, and begins scanning for and selecting a new preferred parent node. **Node +C maintains all its downstream connections throughout this process**. + +**4.** Node C selects node B as its preferred parent node, forms an upstream +connection, and becomes a second layer node. The network layout is similar after +the switch as node C still maintains the same subnetwork. However each node in +node C's subnetwork has been placed one layer deeper as a result of the switch. +`Parent Node Switching`_ may adjust the network layout afterwards if any nodes have +a new preferred parent node as a result of the root node switch. + +.. note:: + Root node switching must require an election hence is only supported when using + a self-organized ESP-MESH network. In other words, root node switching cannot + occur if a designated root node is used. + +Parent Node Switching +^^^^^^^^^^^^^^^^^^^^^ + +Parent Node Switching entails a child node switching its upstream connection to +another parent node of a shallower layer. **Parent Node Switching occurs autonomously** +meaning that a child node will change its upstream connection automatically if a +potential parent node of a shallower layer becomes available (i.e. due to a +`Asynchronous Power-on Reset`_). + +All potential parent nodes periodically transmit beacon frames (see `Beacon Frames +& RSSI Thresholding`_) allowing for a child node to scan for the availability of +a shallower parent node. Due to parent node switching, a self-organized ESP-MESH +network can dynamically adjust its network layout to ensure each connection has a good +RSSI and that the number of layers in the network is minimized. + +.. --------------------------- Data Transmission ------------------------------ + +.. _mesh-data-transmission: + +Data Transmission +----------------- + +ESP-MESH Packet +^^^^^^^^^^^^^^^ + +ESP-MESH network data transmissions use ESP-MESH packets. ESP-MESH packets +are **entirely contained within the frame body of a Wi-Fi data frame**. A multi-hop +data transmission in an ESP-MESH network will involve a single ESP-MESH packet +being carried over each wireless hop by a different Wi-Fi data frame. + +The following diagram shows the structure of an ESP-MESH packet and its relation +with a Wi-Fi data frame. + +.. figure:: ../../_static/mesh-packet.png + :align: center + :alt: Diagram of ESP-MESH Packet + :figclass: align-center + + ESP-MESH Packet + +**The header** of an ESP-MESH packet contains the MAC addresses of the source and +destination nodes. The options field contains information pertaining to the special +types of ESP-MESH packets such as a group transmission or a packet originating +from the external IP network (see :c:macro:`MESH_OPT_SEND_GROUP` and +:c:macro:`MESH_OPT_RECV_DS_ADDR`). + +**The payload** of an ESP-MESH packet contains the actual application data. This +data can be raw binary data, or encoded under an application layer protocol such +as HTTP, MQTT, and JSON (see :cpp:type:`mesh_proto_t`). + +.. note:: + When sending an ESP-MESH packet to the external IP network, the destination + address field of the header will contain the IP address and port of the target server + rather than the MAC address of a node (see :cpp:type:`mesh_addr_t`). Furthermore + the root node will handle the formation of the outgoing TCP/IP packet. + +Group Control & Multicasting +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Multicasting is a feature that allows a single ESP-MESH packet to be transmitted +simultaneously to multiple nodes within the network. Multicasting in ESP-MESH can +be achieved by either specifying a list of target nodes, or specifying a preconfigured +group of nodes. Both methods of multicasting are called via :cpp:func:`esp_mesh_send`. + +To multicast by specifying a list of target nodes, users must first set the ESP-MESH +packet's destination address to the **Multicast-Group Address** (``01:00:5E:xx:xx:xx``). +This signifies that the ESP-MESH packet is a multicast packet with a group of addresses, +and that the address should be obtained from the header options. Users must then +list the MAC addresses of the target nodes as options (see :cpp:type:`mesh_opt_t` +and :c:macro:`MESH_OPT_SEND_GROUP`). This method of multicasting requires no prior +setup but can incur a large amount of overhead data as each target node's MAC address +must be listed in the options field of the header. + +Multicasting by group allows a ESP-MESH packet to be transmitted to a preconfigured +group of nodes. Each grouping is identified by a unique ID, and a node can be placed +into a group via :cpp:func:`esp_mesh_set_group_id`. Multicasting to a group involves +setting the destination address of the ESP-MESH packet to the target group ID. +Furthermore, the :c:macro:`MESH_DATA_GROUP` flag must set. Using groups to multicast +incurs less overhead, but requires nodes to previously added into groups. + +.. note:: + During a multicast, all nodes within the network still receive the ESP-MESH + packet on the MAC layer. However, nodes not included in the MAC address list + or the target group will simply filter out the packet. + +Broadcasting +^^^^^^^^^^^^ + +Broadcasting is a feature that allows a single ESP-MESH packet to be transmitted +simultaneously to all nodes within the network. Each node essentially forwards +a broadcast packet to all of its upstream and downstream connections such that +the packet propagates throughout the network as quickly as possible. However, +ESP-MESH utilizes the following methods to avoid wasting bandwidth during a broadcast. + +**1.** When an intermediate parent node receives a broadcast packet from its parent, +it will forward the packet to each of its child nodes whilst storing a copy of the +packet for itself. + +**2.** When an intermediate parent node is the source node of the broadcast, it +will transmit the broadcast packet upstream to is parent node and downstream to +each of its child nodes. + +**3.** When an intermediate parent node receives a broadcast packet from one of its +child nodes, it will forward the packet to its parent node and each of its remaining +child nodes whilst storing a copy of the packet for itself. + +**4.** When a leaf node is the source node of a broadcast, it will directly +transmit the packet to its parent node. + +**5.** When the root node is the source node of a broadcast, the root node will transmit +the packet to all of its child nodes. + +**6.** When the root node receives a broadcast packet from one of its child nodes, it +will forward the packet to each of its remaining child nodes whilst storing a copy +of the packet for itself. + +**7.** When a node receives a broadcast packet with a source address matching its +own MAC address, the node will discard the broadcast packet. + +**8.** When an intermediate parent node receives a broadcast packet from its parent +node which was originally transmitted from one of its child nodes, it will discard +the broadcast packet + +Upstream Flow Control +^^^^^^^^^^^^^^^^^^^^^ + +ESP-MESH relies on parent nodes to control the upstream data flow of their immediate +child nodes. To prevent a parent node's message buffer from overflowing due to an overload +of upstream transmissions, a parent node will allocate a quota for upstream transmissions +known as a **receiving window** for each of its child nodes. **Each child node must +apply for a receiving window before it is permitted to transmit upstream**. The size +of a receiving window can be dynamically adjusted. An upstream transmission from +a child node to the parent node consists of the following steps: + +**1.** Before each transmission, the child node sends a window request to its parent +node. The window request consists of a sequence number which corresponds to the child +node's data packet that is pending transmission. + +**2.** The parent node receives the window request and compares the sequence number +with the sequence number of the previous packet sent by the child node. The comparison +is used to calculate the size of the receiving window which is transmitted back +to the child node. + +**3.** The child node transmits the data packet in accordance with the window size +specified by the parent node. If the child node depletes its receiving window, it +must obtain another receiving windows by sending a request before it is permitted +to continue transmitting. + +.. note:: + ESP-MESH does not support any downstream flow control. + +.. warning:: + Due to `Parent Node Switching`_, packet loss may occur during upstream + transmissions. + +Due to the fact that the root node acts as the sole interface to an external IP +network, it is critical that downstream nodes are aware of the root node's connection +status with the external IP network. Failing to do so can lead to nodes attempting +to pass data upstream to the root node whilst it is disconnected from the IP network. +This results in unnecessary transmissions and packet loss. ESP-MESH address this +issue by providing a mechanism to stabilize the throughput of outgoing data based +on the connection status between the root node and the external IP network. The root +node can broadcast its external IP network connection status to all other nodes +by calling :cpp:func:`esp_mesh_post_toDS_state`. + +Bi-Directional Data Stream +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The following diagram illustrates the various network layers involved in an ESP-MESH +Bidirectional Data Stream. + +.. figure:: ../../_static/mesh-bidirectional-data-stream.png + :align: center + :alt: Diagram of ESP-MESH Bidirectional Data Stream + :figclass: align-center + + ESP-MESH Bidirectional Data Stream + +Due to the use of `Routing Tables`_, **ESP-MESH is able to handle pack forwarding +entirely on the mesh layer**. A TCP/IP layer is only required on the root +node when it transmits/receives a packet to/from an external IP network. + +.. ------------------------------ Performance --------------------------------- + +.. _mesh-network-performance: + +Performance +----------- + +The performance of an ESP-MESH network can be evaluated based on multiple metrics +such as the following: + +**Network Building Time:** The amount of time taken to build an ESP-MESH network from +scratch. + +**Healing Time:** The amount of time taken for the network to detect a node break +down and carry out appropriate actions to heal the network (such as generating a +new root node or forming new connections). + +**Per-hop latency:** The latency of data transmission over one wireless hop. In +other words, the time taken to transmit a data packet from a parent node to a +child node or vice versa. + +**Network Node Capacity:** The total number of nodes the ESP-MESH network can simultaneously +support. This number is determined by the maximum number of downstream connections +a node can accept and the maximum number of layers permissible in the network. + +The following table lists the common performance figures of an ESP-MESH network. +However users should note that performance numbers can vary greatly between +installations based on network configuration and operating environment. + ++-------------------------+------------------------------------+ +| Function | Description | ++=========================+====================================+ +|Networking Building Time | < 60 seconds | ++-------------------------+------------------------------------+ +|Healing time | Root Node Break Down: < 10 seconds | +| | | +| | Child Node Break Down: < 5 seconds | ++-------------------------+------------------------------------+ +|Per-hop latency | 10 to 30 milliseconds | ++-------------------------+------------------------------------+ + +.. note:: + The following test conditions were used to generate the performance figures + above. + + - Number of test devices: **100** + - Maximum Downstream Connections to Accept: **6** + - Maximum Permissible Layers: **6** + +.. note:: + Throughput depends on packet error rate and hop count. + +.. note:: + The throughput of root node's access to the external IP network is directly + affected by the number of nodes in the ESP-MESH network and the bandwidth of + the router. + +.. ----------------------------- Further Notes -------------------------------- + +.. _mesh-further-notes: + +Further Notes +------------- + +- Data transmission uses Wi-Fi WPA2-PSK encryption + +- Mesh networking IE uses AES encryption -ESP-MESH events define almost all system events for any application tasks needed. The events include the Wi-Fi connection status of the station interface, the connection status of child nodes on the softAP interface, and the like. Firstly, application tasks need to register a mesh event callback handler via the API :cpp:func:`esp_mesh_set_config`. This handler is used for receiving events posted from the mesh stack and the LwIP stack. Application tasks can add relevant handlers to each event. - -**Examples:** - -(1) Application tasks can use Wi-Fi station connect statuses to determine when to send data to a parent node, to a root node or to external IP network. -(2) Application tasks can use Wi-Fi softAP statuses to determine when to send data to child nodes. - -Application tasks can access the mesh stack directly without having to go through the LwIP stack. The LwIP stack is not necessery for non-root nodes. -:cpp:func:`esp_mesh_send` and :cpp:func:`esp_mesh_recv` are used in the application tasks to send and receive messages over the mesh network. - -**Notes:** - -Since current ESP-IDF does not support system initializing without calling :cpp:func:`tcpip_adapter_init`, application tasks still need to perform the LwIP initialization and do remember firstly -1. stoping the DHCP server service on the softAP interface -2. stoping the DHCP client service on the station interface. - -Code Example: - -:cpp:func:`tcpip_adapter_init`; - -:cpp:func:`tcpip_adapter_dhcps_stop`; - -:cpp:func:`tcpip_adapter_dhcpc_stop`; - -The root node is connected with a router. Thus, in the application mesh event handler, once a node becomes the root, the DHCP client service must be started immediately to obtain IP address unless static IP settings is used. +Router and internet icon made by `Smashicons `_ from `www.flaticon.com `_ \ No newline at end of file diff --git a/docs/en/api-reference/mesh/esp_mesh.rst b/docs/en/api-reference/mesh/esp_mesh.rst index d22e86d67..2d5349c5e 100644 --- a/docs/en/api-reference/mesh/esp_mesh.rst +++ b/docs/en/api-reference/mesh/esp_mesh.rst @@ -1,11 +1,266 @@ -Mesh -===== +ESP-MESH Programming Guide +========================== + +This is a programming guide for ESP-MESH, including the API reference and coding +examples. This guide is split into the following parts: + +1. :ref:`mesh-programming-model` + +2. :ref:`mesh-writing-mesh-application` + +3. :ref:`mesh-application-examples` + +4. :ref:`mesh-api-reference` + +For documentation regarding the ESP-MESH protocol, please see the +:doc:`ESP-MESH API Guide<../../api-guides/mesh>`. + + +.. ---------------------- ESP-MESH Programming Model -------------------------- + +.. _mesh-programming-model: + +ESP-MESH Programming Model +-------------------------- + +Software Stack +^^^^^^^^^^^^^^ + +The ESP-MESH software stack is built atop the Wi-Fi Driver/FreeRTOS and may use +the LwIP Stack in some instances (i.e. the root node). The following diagram +illustrates the ESP-MESH software stack. + +.. _mesh-going-to-software-stack: + +.. figure:: ../../../_static/mesh-software-stack.png + :align: center + :alt: ESP-MESH Software Stack + :figclass: align-center + + ESP-MESH Software Stack + +System Events +^^^^^^^^^^^^^ + +An application interfaces with ESP-MESH via **ESP-MESH Events**. Since ESP-MESH +is built atop the Wi-Fi stack, it is also possible for the application to interface +with the Wi-Fi driver via the **Wi-Fi Event Task**. The following diagram illustrates +the interfaces for the various System Events in an ESP-MESH application. + +.. figure:: ../../../_static/mesh-events-delivery.png + :align: center + :alt: ESP-MESH System Events Delivery + :figclass: align-center + + ESP-MESH System Events Delivery + +The :cpp:type:`mesh_event_id_t` defines all possible ESP-MESH system events and +can indicate events such as the connection/disconnection of parent/child. Before +ESP-MESH system events can be used, the application must register a **Mesh Event +Callback** via :cpp:func:`esp_mesh_set_config`. The callback is used to receive +events from the ESP-MESH stack as well as the LwIP Stack and should contain handlers +for each event relevant to the application. + +Typical use cases of system events include using events such as +:cpp:enumerator:`MESH_EVENT_PARENT_CONNECTED` and :cpp:enumerator:`MESH_EVENT_CHILD_CONNECTED` +to indicate when a node can begin transmitting data upstream and downstream respectively. Likewise, +:cpp:enumerator:`MESH_EVENT_ROOT_GOT_IP` and :cpp:enumerator:`MESH_EVENT_ROOT_LOST_IP` can be +used to indicate when the root node can and cannot transmit data to the external IP +network. + +.. warning:: + When using ESP-MESH under self-organized mode, users must ensure that no calls + to Wi-Fi API are made. This is due to the fact that the self-organizing mode + will internally make Wi-Fi API calls to connect/disconnect/scan etc. + **Any Wi-Fi calls from the application (including calls from callbacks and + handlers of Wi-Fi events) may interfere with ESP-MESH's self-organizing behavior**. + Therefore, user's should not call Wi-Fi APIs after :cpp:func:`esp_mesh_start` + is called, and before :cpp:func:`esp_mesh_stop` is called. + +LwIP & ESP-MESH +^^^^^^^^^^^^^^^ + +The application can access the ESP-MESH stack directly without having to go through +the LwIP stack. The LwIP stack is only required by the root node to transmit/receive +data to/from an external IP network. However, since every node can potentially +become the root node (due to automatic root node selection), each node must still +initialize the LwIP stack. + +**Each node is required to initialize LwIP by calling** :cpp:func:`tcpip_adapter_init`. +In order to prevent non-root node access to LwIP, the application should stop the +following services after LwIP initialization: + + - DHCP server service on the softAP interface. + - DHCP client service on the station interface. + +The following code snippet demonstrates how to initialize LwIP for ESP-MESH applications. + +.. code-block:: c + + /* tcpip initialization */ + tcpip_adapter_init(); + /* + * for mesh + * stop DHCP server on softAP interface by default + * stop DHCP client on station interface by default + */ + ESP_ERROR_CHECK(tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP)); + ESP_ERROR_CHECK(tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA)); + /* do not specify system event callback, use NULL instead. */ + ESP_ERROR_CHECK(esp_event_loop_init(NULL, NULL)); + +.. note:: + + ESP-MESH requires a root node to be connected with a router. Therefore, in + the event that a node becomes the root, **the corresponding handler must start + the DHCP client service and immediately obtain an IP address**. Doing so will + allow other nodes to begin transmitting/receiving packets to/from the external + IP network. However, this step is unnecessary if static IP settings are used. + + +.. ---------------------- Writing a Mesh Application -------------------------- + +.. _mesh-writing-mesh-application: + +Writing an ESP-MESH Application +------------------------------- + +The prerequisites for starting ESP-MESH is to initialize LwIP and Wi-Fi, The +following code snippet demonstrates the necessary prerequisite steps before +ESP-MESH itself can be initialized. + +.. code-block:: c + + tcpip_adapter_init(); + /* + * for mesh + * stop DHCP server on softAP interface by default + * stop DHCP client on station interface by default + */ + ESP_ERROR_CHECK(tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP)); + ESP_ERROR_CHECK(tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA)); + /* do not specify system event callback, use NULL instead. */ + ESP_ERROR_CHECK(esp_event_loop_init(NULL, NULL)); + + /* Wi-Fi initialization */ + wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&config)); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH)); + ESP_ERROR_CHECK(esp_wifi_start()); + +After initializing LwIP and Wi-Fi, the process of getting an ESP-MESH network +up and running can be summarized into the following three steps: + +1. :ref:`mesh-initialize-mesh` +2. :ref:`mesh-configuring-mesh` +3. :ref:`mesh-start-mesh` + +.. _mesh-initialize-mesh: + +Initialize Mesh +^^^^^^^^^^^^^^^ + +The following code snippet demonstrates how to initialize ESP-MESH + +.. code-block:: c + + /* mesh initialization */ + ESP_ERROR_CHECK(esp_mesh_init()); + +.. _mesh-configuring-mesh: + +Configuring an ESP-MESH Network +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. todo - Add note about unified configuration + +ESP-MESH is configured via :cpp:func:`esp_mesh_set_config` which receives its arguments +using the :cpp:type:`mesh_cfg_t` structure. The structure contains the following +parameters used to configure ESP-MESH: + ++------------------+-------------------------------------+ +| Parameter | Description | ++==================+=====================================+ +| Channel | Range from 1 to 14 | ++------------------+-------------------------------------+ +| Event Callback | Callback for Mesh Events, | +| | see :cpp:type:`mesh_event_cb_t` | ++------------------+-------------------------------------+ +| Mesh ID | ID of ESP-MESH Network, | +| | see :cpp:type:`mesh_addr_t` | ++------------------+-------------------------------------+ +| Router | Router Configuration, | +| | see :cpp:type:`mesh_router_t` | ++------------------+-------------------------------------+ +| Mesh AP | Mesh AP Configuration, | +| | see :cpp:type:`mesh_ap_cfg_t` | ++------------------+-------------------------------------+ +| Crypto Functions | Crypto Functions for Mesh IE, | +| | see :cpp:type:`mesh_crypto_funcs_t` | ++------------------+-------------------------------------+ + +The following code snippet demonstrates how to configure ESP-MESH. + +.. code-block:: c + + /* Enable the Mesh IE encryption by default */ + mesh_cfg_t cfg = MESH_INIT_CONFIG_DEFAULT(); + /* mesh ID */ + memcpy((uint8_t *) &cfg.mesh_id, MESH_ID, 6); + /* mesh event callback */ + cfg.event_cb = &mesh_event_handler; + /* channel (must match the router's channel) */ + cfg.channel = CONFIG_MESH_CHANNEL; + /* router */ + cfg.router.ssid_len = strlen(CONFIG_MESH_ROUTER_SSID); + memcpy((uint8_t *) &cfg.router.ssid, CONFIG_MESH_ROUTER_SSID, cfg.router.ssid_len); + memcpy((uint8_t *) &cfg.router.password, CONFIG_MESH_ROUTER_PASSWD, + strlen(CONFIG_MESH_ROUTER_PASSWD)); + /* mesh softAP */ + cfg.mesh_ap.max_connection = CONFIG_MESH_AP_CONNECTIONS; + memcpy((uint8_t *) &cfg.mesh_ap.password, CONFIG_MESH_AP_PASSWD, + strlen(CONFIG_MESH_AP_PASSWD)); + ESP_ERROR_CHECK(esp_mesh_set_config(&cfg)); + +.. _mesh-start-mesh: + +Start Mesh +^^^^^^^^^^ + +The following code snippet demonstrates how to start ESP-MESH. + +.. code-block:: c + + /* mesh start */ + ESP_ERROR_CHECK(esp_mesh_start()); + +After starting ESP-MESH, the application should check for ESP-MESH events to determine +when it has connected to the network. After connecting, the application can start +transmitting and receiving packets over the ESP-MESH network using +:cpp:func:`esp_mesh_send` and :cpp:func:`esp_mesh_recv`. + +.. --------------------- ESP-MESH Application Examples ------------------------ + +.. _mesh-application-examples: Application Examples -------------------- -See :example:`mesh` directory of ESP-IDF examples that contains the following applications. +ESP-IDF contains these ESP-MESH example projects: +:example:`The Internal Communication Example` demonstrates +how to setup a ESP-MESH network and have the root node send a data packet to +every node within the network. + +:example:`The Manual Networking Example` demonstrates +how to use ESP-MESH without the self-organizing features. This example shows how +to program a node to manually scan for a list of potential parent nodes and select +a parent node based on custom criteria. + + +.. ------------------------- ESP-MESH API Reference --------------------------- + +.. _mesh-api-reference: API Reference -------------- diff --git a/docs/en/api-reference/peripherals/can.rst b/docs/en/api-reference/peripherals/can.rst index ece926d88..d6ba1423a 100644 --- a/docs/en/api-reference/peripherals/can.rst +++ b/docs/en/api-reference/peripherals/can.rst @@ -574,6 +574,23 @@ use of the :cpp:func:`can_stop` and :cpp:func:`can_driver_uninstall` functions. return; } +Multiple ID Filter Configuration +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The acceptance mask in :cpp:type:`can_filter_config_t` can be configured such that +two or more IDs will be accepted for a single filter. For a particular filter to +accept multiple IDs, the conflicting bit positions amongst the IDs must be set +in the acceptance mask. The acceptance code can be set to any one of the IDs. + +The following example shows how the calculate the acceptance mask given multiple +IDs:: + + ID1 = 11'b101 1010 0000 + ID2 = 11'b101 1010 0001 + ID3 = 11'b101 1010 0100 + ID4 = 11'b101 1010 1000 + //Acceptance Mask + MASK = 11'b000 0000 1101 Application Examples ^^^^^^^^^^^^^^^^^^^^ @@ -581,19 +598,19 @@ Application Examples **Network Example:** The CAN Network example demonstrates communication between two ESP32s using the CAN driver API. One CAN node acts as a network master initiate and ceasing the transfer of a data from another CAN node acting as a network slave. -The example can be found via :example:`examples/peripheral/can/can_network`. +The example can be found via :example:`peripherals/can/can_network`. **Alert and Recovery Example:** This example demonstrates how to use the CAN driver's alert and bus recovery API. The example purposely introduces errors on the CAN bus to put the CAN controller into the Bus-Off state. An alert is used to detect the Bus-Off state and trigger the bus recovery process. The example can be found -via :example:`examples/peripheral/can/can_alert_and_recovery`. +via :example:`peripherals/can/can_alert_and_recovery`. **Self Test Example:** This example uses the No Acknowledge Mode and Self Reception Request to cause the CAN controller to send and simultaneously receive a series of messages. This example can be used to verify if the connections between the CAN controller and the external transceiver are working correctly. The example can be -found via :example:`examples/peripheral/can/can_self_test`. +found via :example:`peripherals/can/can_self_test`. .. ---------------------------- API Reference ---------------------------------- diff --git a/docs/en/api-reference/system/esp_https_ota.rst b/docs/en/api-reference/system/esp_https_ota.rst index 762de6cf7..72e3c3285 100644 --- a/docs/en/api-reference/system/esp_https_ota.rst +++ b/docs/en/api-reference/system/esp_https_ota.rst @@ -29,6 +29,11 @@ Application Example return ESP_OK; } +Signature Verification +---------------------- + +For additional security, signature of OTA firmware images can be verified. For that, refer :ref:`secure-ota-updates` + API Reference ------------- diff --git a/docs/en/api-reference/system/ota.rst b/docs/en/api-reference/system/ota.rst index 825335473..db0280728 100644 --- a/docs/en/api-reference/system/ota.rst +++ b/docs/en/api-reference/system/ota.rst @@ -32,6 +32,13 @@ The OTA data partition is two flash sectors (0x2000 bytes) in size, to prevent p while it is being written. Sectors are independently erased and written with matching data, and if they disagree a counter field is used to determine which sector was written more recently. +.. _secure-ota-updates: + +Secure OTA Updates Without Secure boot +-------------------------------------- + +The verification of signed OTA updates can be performed even without enabling hardware secure boot. For doing so, refer :ref:`signed-app-verify` + See also -------- diff --git a/docs/en/api-reference/system/power_management.rst b/docs/en/api-reference/system/power_management.rst index 618482441..116233393 100644 --- a/docs/en/api-reference/system/power_management.rst +++ b/docs/en/api-reference/system/power_management.rst @@ -112,7 +112,7 @@ Currently, the following peripheral drivers are aware of DFS and will use ``ESP_ The following drivers will hold ``ESP_PM_APB_FREQ_MAX`` lock while the driver is enabled: -- SPI slave — between calls to :cpp:func:`spi_slave_initialize` and cpp:func:`spi_slave_free`. +- SPI slave — between calls to :cpp:func:`spi_slave_initialize` and :cpp:func:`spi_slave_free`. - Ethernet — between calls to :cpp:func:`esp_eth_enable` and :cpp:func:`esp_eth_disable`. @@ -120,6 +120,8 @@ The following drivers will hold ``ESP_PM_APB_FREQ_MAX`` lock while the driver is - Bluetooth — between calls to :cpp:func:`esp_bt_controller_enable` and :cpp:func:`esp_bt_controller_disable`. +- CAN - between calls to :cpp:func:`can_driver_install` and :cpp:func:`can_driver_uninstall` + The following peripheral drivers are not aware of DFS yet. Applications need to acquire/release locks when necessary: - I2C diff --git a/docs/en/security/secure-boot.rst b/docs/en/security/secure-boot.rst index d03a614d5..713fbfe44 100644 --- a/docs/en/security/secure-boot.rst +++ b/docs/en/security/secure-boot.rst @@ -146,6 +146,8 @@ openssl ecparam -name prime256v1 -genkey -noout -out my_secure_boot_signing_key. Remember that the strength of the secure boot system depends on keeping the signing key private. +.. _remote-sign-image: + Remote Signing of Images ------------------------ @@ -253,10 +255,39 @@ Keyfile is the 32 byte raw secure boot key for the device. To flash this digest esptool.py write_flash 0x0 bootloader-digest.bin - .. _secure-boot-and-flash-encr: Secure Boot & Flash Encryption ------------------------------ If secure boot is used without :doc:`Flash Encryption `, it is possible to launch "time-of-check to time-of-use" attack, where flash contents are swapped after the image is verified and running. Therefore, it is recommended to use both the features together. + +.. _signed-app-verify: + +Signed App Verification Without Hardware Secure Boot +---------------------------------------------------- + +The integrity of apps can be checked even without enabling the hardware secure boot option. This option uses the same app signature scheme as hardware secure +boot, but unlike hardware secure boot it does not prevent the bootloader from being physically updated. This means that the device can be secured +against remote network access, but not physical access. Compared to using hardware Secure Boot this option is much simpler to implement. See :ref:`signed-app-verify-howto` for step by step instructions. + +An app can be verified on update and, optionally, be verified on boot. + +- Verification on update: When enabled, the signature is automatically checked whenever the esp_ota_ops.h APIs are used for OTA updates. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option still adds significant security against network-based attackers by preventing spoofing of OTA updates. + +- Verification on boot: When enabled, the bootloader will be compiled with code to verify that an app is signed before booting it. If hardware secure boot is enabled, this option is always enabled and cannot be disabled. If hardware secure boot is not enabled, this option doesn't add significant security by itself so most users will want to leave it disabled. + +.. _signed-app-verify-howto: + +How To Enable Signed App Verification +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. Run ``make menuconfig`` -> Security features -> Enable "Require signed app images" + +2. "Bootloader verifies app signatures" can be enabled, which verifies app on boot. + +3. By default, "Sign binaries during build" will be enabled on selecting "Require signed app images" option, which will sign binary files as a part of build process. The file named in "Secure boot private signing key" will be used to sign the image. + +4. If you disable "Sign binaries during build" option then you'll have to enter path of a public key file used to verify signed images in "Secure boot public signature verification key". + In this case, private signing key should be generated by following instructions in :ref:`secure-boot-generate-key`; public verification key and signed image should be generated by following instructions in :ref:`remote-sign-image`. + diff --git a/docs/gen-dxd.py b/docs/gen-dxd.py old mode 100644 new mode 100755 index 0737d94f6..f04c0e0c1 --- a/docs/gen-dxd.py +++ b/docs/gen-dxd.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python +# # gen-dxd.py - Generate Doxygen Directives # # This code is in the Public Domain (or CC0 licensed, at your option.) diff --git a/docs/requirements.txt b/docs/requirements.txt index b85fc09a1..dfd6f5c08 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -4,8 +4,9 @@ sphinx==1.6.5 sphinx-rtd-theme breathe==4.7.3 -sphinxcontrib.blockdiag==1.5.3 -sphinxcontrib.seqdiag==0.8.5 -sphinxcontrib.actdiag==0.8.5 -sphinxcontrib.nwdiag==0.9.5 +sphinxcontrib-blockdiag==1.5.3 +sphinxcontrib-seqdiag==0.8.5 +sphinxcontrib-actdiag==0.8.5 +sphinxcontrib-nwdiag==0.9.5 recommonmark +future>=0.16.0 # for ../tools/gen_esp_err_to_name.py diff --git a/docs/zh_CN/api-guides/index.rst b/docs/zh_CN/api-guides/index.rst index d993b44d2..d05b89a55 100644 --- a/docs/zh_CN/api-guides/index.rst +++ b/docs/zh_CN/api-guides/index.rst @@ -25,6 +25,6 @@ API Guides Console Component ROM debug console WiFi Driver - Mesh Stack + ESP-MESH BluFi External SPI-connected RAM diff --git a/examples/bluetooth/a2dp_sink/README.md b/examples/bluetooth/a2dp_sink/README.md index cb45d838c..9a3c5d611 100644 --- a/examples/bluetooth/a2dp_sink/README.md +++ b/examples/bluetooth/a2dp_sink/README.md @@ -5,6 +5,16 @@ Demo of A2DP audio sink role This is the demo of API implementing Advanced Audio Distribution Profile to receive an audio stream. +This example involves the use of Bluetooth legacy profile A2DP for audio stream reception, AVRCP for media information notifications, and I2S for audio stream output interface. + +Applications such as bluetooth speakers can take advantage of this example as a reference of basic functionalities. + +## How to use this example + +### Hardware Required + +To play the sound, there is a need of loudspeaker and possibly an external I2S codec. Otherwise the example will only show a count of audio data packets received silently. Internal DAC can be selected and in this case external I2S codec may not be needed. + For the I2S codec, pick whatever chip or board works for you; this code was written using a PCM5102 chip, but other I2S boards and chips will probably work as well. The default I2S connections are shown below, but these can be changed in menuconfig: | ESP pin | I2S signal | @@ -15,5 +25,51 @@ For the I2S codec, pick whatever chip or board works for you; this code was writ If the internal DAC is selected, analog audio will be available on GPIO25 and GPIO26. The output resolution on these pins will always be limited to 8 bit because of the internal structure of the DACs. +### Configure the project -After the program is started, other bluetooth devices such as smart phones can discover a device named "ESP_SPEAKER". Once a connection is established, audio data can be transmitted. This will be visible in the application log including a count of audio data packets. \ No newline at end of file +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. + +* Set the use of external I2S codec or internal DAC for audio output, and configure the output PINs under A2DP Example Configuration + +* Enable Classic Bluetooth and A2DP under Component config --> Bluetooth --> Bluedroid Enable + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output. + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +## Example Output + +After the program is started, the example starts inquiry scan and page scan, awaiting being discovered and connected. Other bluetooth devices such as smart phones can discover a device named "ESP_SPEAKER". A smartphone or another ESP-IDF example of A2DP source can be used to connect to the local device. + +Once A2DP connection is set up, there will be a notification message with the remote device's bluetooth MAC address like the following: + +``` +I (106427) BT_AV: A2DP connection state: Connected, [64:a2:f9:69:57:a4] +``` + +If a smartphone is used to connect to local device, starting to play music with an APP will result in the transmission of audio stream. The transmitting of audio stream will be visible in the application log including a count of audio data packets, like this: + +``` +I (120627) BT_AV: A2DP audio state: Started +I (122697) BT_AV: Audio packet count 100 +I (124697) BT_AV: Audio packet count 200 +I (126697) BT_AV: Audio packet count 300 +I (128697) BT_AV: Audio packet count 400 + +``` + +Also, the sound will be heard if a loudspeaker is connected and possible external I2S codec is correctly configured. For ESP32 A2DP source example, the sound is noise as the audio source generates the samples with a random sequence. + +## Troubleshooting +* For current stage, the supported audio codec in ESP32 A2DP is SBC. SBC data stream is transmitted to A2DP sink and then decoded into PCM samples as output. The PCM data format is normally of 44.1kHz sampling rate, two-channel 16-bit sample stream. Other decoder configurations in ESP32 A2DP sink is supported but need additional modifications of protocol stack settings. +* As a usage limitation, ESP32 A2DP sink can support at most one connection with remote A2DP source devices. Also, A2DP sink cannot be used together with A2DP source at the same time, but can be used with other profiles such as SPP and HFP. \ No newline at end of file diff --git a/examples/bluetooth/a2dp_sink/main/bt_app_av.c b/examples/bluetooth/a2dp_sink/main/bt_app_av.c index af67c5aa9..d9bbbfbed 100644 --- a/examples/bluetooth/a2dp_sink/main/bt_app_av.c +++ b/examples/bluetooth/a2dp_sink/main/bt_app_av.c @@ -30,10 +30,10 @@ static void bt_av_hdl_a2d_evt(uint16_t event, void *p_param); /* avrc event handler */ static void bt_av_hdl_avrc_evt(uint16_t event, void *p_param); -static uint32_t m_pkt_cnt = 0; -static esp_a2d_audio_state_t m_audio_state = ESP_A2D_AUDIO_STATE_STOPPED; -static const char *m_a2d_conn_state_str[] = {"Disconnected", "Connecting", "Connected", "Disconnecting"}; -static const char *m_a2d_audio_state_str[] = {"Suspended", "Stopped", "Started"}; +static uint32_t s_pkt_cnt = 0; +static esp_a2d_audio_state_t s_audio_state = ESP_A2D_AUDIO_STATE_STOPPED; +static const char *s_a2d_conn_state_str[] = {"Disconnected", "Connecting", "Connected", "Disconnecting"}; +static const char *s_a2d_audio_state_str[] = {"Suspended", "Stopped", "Started"}; /* callback for A2DP sink */ void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param) @@ -55,8 +55,8 @@ void bt_app_a2d_data_cb(const uint8_t *data, uint32_t len) { size_t bytes_written; i2s_write(0, data, len, &bytes_written, portMAX_DELAY); - if (++m_pkt_cnt % 100 == 0) { - ESP_LOGI(BT_AV_TAG, "Audio packet count %u", m_pkt_cnt); + if (++s_pkt_cnt % 100 == 0) { + ESP_LOGI(BT_AV_TAG, "Audio packet count %u", s_pkt_cnt); } } @@ -98,7 +98,7 @@ static void bt_av_hdl_a2d_evt(uint16_t event, void *p_param) a2d = (esp_a2d_cb_param_t *)(p_param); uint8_t *bda = a2d->conn_stat.remote_bda; ESP_LOGI(BT_AV_TAG, "A2DP connection state: %s, [%02x:%02x:%02x:%02x:%02x:%02x]", - m_a2d_conn_state_str[a2d->conn_stat.state], bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); + s_a2d_conn_state_str[a2d->conn_stat.state], bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) { esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); } else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED){ @@ -108,10 +108,10 @@ static void bt_av_hdl_a2d_evt(uint16_t event, void *p_param) } case ESP_A2D_AUDIO_STATE_EVT: { a2d = (esp_a2d_cb_param_t *)(p_param); - ESP_LOGI(BT_AV_TAG, "A2DP audio state: %s", m_a2d_audio_state_str[a2d->audio_stat.state]); - m_audio_state = a2d->audio_stat.state; + ESP_LOGI(BT_AV_TAG, "A2DP audio state: %s", s_a2d_audio_state_str[a2d->audio_stat.state]); + s_audio_state = a2d->audio_stat.state; if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) { - m_pkt_cnt = 0; + s_pkt_cnt = 0; } break; } diff --git a/examples/bluetooth/a2dp_sink/main/bt_app_core.c b/examples/bluetooth/a2dp_sink/main/bt_app_core.c index b04d5c89a..528b34fc5 100644 --- a/examples/bluetooth/a2dp_sink/main/bt_app_core.c +++ b/examples/bluetooth/a2dp_sink/main/bt_app_core.c @@ -21,8 +21,8 @@ static void bt_app_task_handler(void *arg); static bool bt_app_send_msg(bt_app_msg_t *msg); static void bt_app_work_dispatched(bt_app_msg_t *msg); -static xQueueHandle bt_app_task_queue = NULL; -static xTaskHandle bt_app_task_handle = NULL; +static xQueueHandle s_bt_app_task_queue = NULL; +static xTaskHandle s_bt_app_task_handle = NULL; bool bt_app_work_dispatch(bt_app_cb_t p_cback, uint16_t event, void *p_params, int param_len, bt_app_copy_cb_t p_copy_cback) { @@ -57,7 +57,7 @@ static bool bt_app_send_msg(bt_app_msg_t *msg) return false; } - if (xQueueSend(bt_app_task_queue, msg, 10 / portTICK_RATE_MS) != pdTRUE) { + if (xQueueSend(s_bt_app_task_queue, msg, 10 / portTICK_RATE_MS) != pdTRUE) { ESP_LOGE(BT_APP_CORE_TAG, "%s xQueue send failed", __func__); return false; } @@ -75,7 +75,7 @@ static void bt_app_task_handler(void *arg) { bt_app_msg_t msg; for (;;) { - if (pdTRUE == xQueueReceive(bt_app_task_queue, &msg, (portTickType)portMAX_DELAY)) { + if (pdTRUE == xQueueReceive(s_bt_app_task_queue, &msg, (portTickType)portMAX_DELAY)) { ESP_LOGD(BT_APP_CORE_TAG, "%s, sig 0x%x, 0x%x", __func__, msg.sig, msg.event); switch (msg.sig) { case BT_APP_SIG_WORK_DISPATCH: @@ -95,19 +95,19 @@ static void bt_app_task_handler(void *arg) void bt_app_task_start_up(void) { - bt_app_task_queue = xQueueCreate(10, sizeof(bt_app_msg_t)); - xTaskCreate(bt_app_task_handler, "BtAppT", 2048, NULL, configMAX_PRIORITIES - 3, &bt_app_task_handle); + s_bt_app_task_queue = xQueueCreate(10, sizeof(bt_app_msg_t)); + xTaskCreate(bt_app_task_handler, "BtAppT", 2048, NULL, configMAX_PRIORITIES - 3, &s_bt_app_task_handle); return; } void bt_app_task_shut_down(void) { - if (bt_app_task_handle) { - vTaskDelete(bt_app_task_handle); - bt_app_task_handle = NULL; + if (s_bt_app_task_handle) { + vTaskDelete(s_bt_app_task_handle); + s_bt_app_task_handle = NULL; } - if (bt_app_task_queue) { - vQueueDelete(bt_app_task_queue); - bt_app_task_queue = NULL; + if (s_bt_app_task_queue) { + vQueueDelete(s_bt_app_task_queue); + s_bt_app_task_queue = NULL; } } diff --git a/examples/bluetooth/a2dp_source/README.md b/examples/bluetooth/a2dp_source/README.md index 457ee5c40..4e9586ce9 100644 --- a/examples/bluetooth/a2dp_source/README.md +++ b/examples/bluetooth/a2dp_source/README.md @@ -3,16 +3,83 @@ ESP-IDF A2DP-SOURCE demo Demo of A2DP audio source role -This is the demo for user to use ESP_APIs to use Advanced Audio Distribution Profile in transmitting audio stream +This is the demo of using Advanced Audio Distribution Profile APIs to transmit audio stream. Application can take advantage of this example to implement portable audio players or microphones to transmit audio stream to A2DP sink devices. + +## How to use this example + +### Hardware Required + +This example is able to run on any commonly available ESP32 development board. And is supposed to connect to A2DP sink example in ESP-IDF. + +### Configure the project + +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. + +* Enable Classic Bluetooth and A2DP under Component config --> Bluetooth --> Bluedroid Enable + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output. + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +## Example Output + +For the first step, this example performs device discovery to search for a target device(A2DP sink) whose device name is "ESP_SPEAKER" and whose "Rendering" bit of its Service Class field is set in its Class of Device. If a candidate target is found, the local device will initiate connection with it. + +After connection with A2DP sink is established, the example performs the following running loop 1-2-3-4-1: +1. audio transmission starts and lasts for a while +2. audio transmission stops +3. disconnect with target device +4. reconnect to target device + +The example implements an event loop triggered by a periodic "heart beat" timer and events from Bluetooth protocol stack callback functions. + +After the local device discovers the target device and initiates connection, there will be logging message like this: + +``` +I (4090) BT_AV: Found a target device, address 24:0a:c4:02:0e:ee, name ESP_SPEAKER +I (4090) BT_AV: Cancel device discovery ... +I (4100) BT_AV: Device discovery stopped. +I (4100) BT_AV: a2dp connecting to peer: ESP_SPEAKER +``` + +If connection is set up successfully, there will be such message: + +``` +I (5100) BT_AV: a2dp connected +``` + +Start of audio transmission has the following notification message: + +``` +I (10880) BT_AV: a2dp media ready checking ... +... +I (10880) BT_AV: a2dp media ready, starting ... +... +I (11400) BT_AV: a2dp media start successfully. +``` + +Stop of audio transmission, and disconnection with remote device generate the following notification message: + +``` +I (110880) BT_AV: a2dp media stopping... +... +I (110920) BT_AV: a2dp media stopped successfully, disconnecting... +... +I (111040) BT_AV: a2dp disconnected +``` + +## Troubleshooting +* For current stage, the supported audio codec in ESP32 A2DP is SBC. SBC audio stream is encoded from PCM data normally formatted as 44.1kHz sampling rate, two-channel 16-bit sample data. Other SBC configurations can be supported but there is a need for additional modifications to the protocol stack. +* The raw PCM media stream in the example is generated by a sequence of random number, so the sound played on the sink side will be piercing noise. +* As a usage limitation, ESP32 A2DP source can support at most one connection with remote A2DP sink devices. Also, A2DP source cannot be used together with A2DP sink at the same time, but can be used with other profiles such as SPP and HFP. -Options choose step: - 1. make menuconfig. - 2. enter menuconfig "Component config", choose "Bluetooth" - 3. enter menu Bluetooth, choose "Bluedroid Enable" - 4. enter menu Bluedroid Enable, choose "Classic Bluetooth" - 5. select "A2DP" and choose "SOURCE" - -In this example, the bluetooth device implements A2DP source. The A2DP sink device to be connected to can be set up with the example "A2DP sink" in another folder in ESP-IDF example directory. -For the first step, the device performs device discovery to find a target device(A2DP sink) named "ESP_SPEAKER". Then it initiate connection with the target device. -After connection is established, the device then start media transmission. The raw PCM media stream to be encoded and transmited in this example is random sequence therefore continuous noise can be heard if the stream is decoded and played on the sink side. -After a period of time, media stream suspend, disconnection and reconnection procedure will be performed. diff --git a/examples/bluetooth/a2dp_source/main/bt_app_core.c b/examples/bluetooth/a2dp_source/main/bt_app_core.c index b04d5c89a..528b34fc5 100644 --- a/examples/bluetooth/a2dp_source/main/bt_app_core.c +++ b/examples/bluetooth/a2dp_source/main/bt_app_core.c @@ -21,8 +21,8 @@ static void bt_app_task_handler(void *arg); static bool bt_app_send_msg(bt_app_msg_t *msg); static void bt_app_work_dispatched(bt_app_msg_t *msg); -static xQueueHandle bt_app_task_queue = NULL; -static xTaskHandle bt_app_task_handle = NULL; +static xQueueHandle s_bt_app_task_queue = NULL; +static xTaskHandle s_bt_app_task_handle = NULL; bool bt_app_work_dispatch(bt_app_cb_t p_cback, uint16_t event, void *p_params, int param_len, bt_app_copy_cb_t p_copy_cback) { @@ -57,7 +57,7 @@ static bool bt_app_send_msg(bt_app_msg_t *msg) return false; } - if (xQueueSend(bt_app_task_queue, msg, 10 / portTICK_RATE_MS) != pdTRUE) { + if (xQueueSend(s_bt_app_task_queue, msg, 10 / portTICK_RATE_MS) != pdTRUE) { ESP_LOGE(BT_APP_CORE_TAG, "%s xQueue send failed", __func__); return false; } @@ -75,7 +75,7 @@ static void bt_app_task_handler(void *arg) { bt_app_msg_t msg; for (;;) { - if (pdTRUE == xQueueReceive(bt_app_task_queue, &msg, (portTickType)portMAX_DELAY)) { + if (pdTRUE == xQueueReceive(s_bt_app_task_queue, &msg, (portTickType)portMAX_DELAY)) { ESP_LOGD(BT_APP_CORE_TAG, "%s, sig 0x%x, 0x%x", __func__, msg.sig, msg.event); switch (msg.sig) { case BT_APP_SIG_WORK_DISPATCH: @@ -95,19 +95,19 @@ static void bt_app_task_handler(void *arg) void bt_app_task_start_up(void) { - bt_app_task_queue = xQueueCreate(10, sizeof(bt_app_msg_t)); - xTaskCreate(bt_app_task_handler, "BtAppT", 2048, NULL, configMAX_PRIORITIES - 3, &bt_app_task_handle); + s_bt_app_task_queue = xQueueCreate(10, sizeof(bt_app_msg_t)); + xTaskCreate(bt_app_task_handler, "BtAppT", 2048, NULL, configMAX_PRIORITIES - 3, &s_bt_app_task_handle); return; } void bt_app_task_shut_down(void) { - if (bt_app_task_handle) { - vTaskDelete(bt_app_task_handle); - bt_app_task_handle = NULL; + if (s_bt_app_task_handle) { + vTaskDelete(s_bt_app_task_handle); + s_bt_app_task_handle = NULL; } - if (bt_app_task_queue) { - vQueueDelete(bt_app_task_queue); - bt_app_task_queue = NULL; + if (s_bt_app_task_queue) { + vQueueDelete(s_bt_app_task_queue); + s_bt_app_task_queue = NULL; } } diff --git a/examples/bluetooth/a2dp_source/main/main.c b/examples/bluetooth/a2dp_source/main/main.c index 3da55895f..d0e16574c 100644 --- a/examples/bluetooth/a2dp_source/main/main.c +++ b/examples/bluetooth/a2dp_source/main/main.c @@ -74,15 +74,15 @@ static void bt_app_av_state_connecting(uint16_t event, void *param); static void bt_app_av_state_connected(uint16_t event, void *param); static void bt_app_av_state_disconnecting(uint16_t event, void *param); -static esp_bd_addr_t peer_bda = {0}; -static uint8_t peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; -static int m_a2d_state = APP_AV_STATE_IDLE; -static int m_media_state = APP_AV_MEDIA_STATE_IDLE; -static int m_intv_cnt = 0; -static int m_connecting_intv = 0; -static uint32_t m_pkt_cnt = 0; +static esp_bd_addr_t s_peer_bda = {0}; +static uint8_t s_peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; +static int s_a2d_state = APP_AV_STATE_IDLE; +static int s_media_state = APP_AV_MEDIA_STATE_IDLE; +static int s_intv_cnt = 0; +static int s_connecting_intv = 0; +static uint32_t s_pkt_cnt = 0; -TimerHandle_t tmr; +static TimerHandle_t s_tmr; static char *bda2str(esp_bd_addr_t bda, char *str, size_t size) { @@ -210,14 +210,14 @@ static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param) /* search for device named "ESP_SPEAKER" in its extended inqury response */ if (eir) { - get_name_from_eir(eir, peer_bdname, NULL); - if (strcmp((char *)peer_bdname, "ESP_SPEAKER") != 0) { + get_name_from_eir(eir, s_peer_bdname, NULL); + if (strcmp((char *)s_peer_bdname, "ESP_SPEAKER") != 0) { return; } - ESP_LOGI(BT_AV_TAG, "Found a target device, address %s, name %s", bda_str, peer_bdname); - m_a2d_state = APP_AV_STATE_DISCOVERED; - memcpy(peer_bda, param->disc_res.bda, ESP_BD_ADDR_LEN); + ESP_LOGI(BT_AV_TAG, "Found a target device, address %s, name %s", bda_str, s_peer_bdname); + s_a2d_state = APP_AV_STATE_DISCOVERED; + memcpy(s_peer_bda, param->disc_res.bda, ESP_BD_ADDR_LEN); ESP_LOGI(BT_AV_TAG, "Cancel device discovery ..."); esp_bt_gap_cancel_discovery(); } @@ -233,11 +233,11 @@ void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) } case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: { if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED) { - if (m_a2d_state == APP_AV_STATE_DISCOVERED) { - m_a2d_state = APP_AV_STATE_CONNECTING; + if (s_a2d_state == APP_AV_STATE_DISCOVERED) { + s_a2d_state = APP_AV_STATE_CONNECTING; ESP_LOGI(BT_AV_TAG, "Device discovery stopped."); - ESP_LOGI(BT_AV_TAG, "a2dp connecting to peer: %s", peer_bdname); - esp_a2d_source_connect(peer_bda); + ESP_LOGI(BT_AV_TAG, "a2dp connecting to peer: %s", s_peer_bdname); + esp_a2d_source_connect(s_peer_bda); } else { // not discovered, continue to discover ESP_LOGI(BT_AV_TAG, "Device discovery failed, continue to discover..."); @@ -252,7 +252,7 @@ void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) case ESP_BT_GAP_RMT_SRVC_REC_EVT: break; #ifdef CONFIG_BT_SSP_ENABLE - case ESP_BT_GAP_AUTH_CMPL_EVT:{ + case ESP_BT_GAP_AUTH_CMPL_EVT: { if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) { ESP_LOGI(BT_AV_TAG, "authentication success: %s", param->auth_cmpl.device_name); esp_log_buffer_hex(BT_AV_TAG, param->auth_cmpl.bda, ESP_BD_ADDR_LEN); @@ -302,15 +302,15 @@ static void bt_av_hdl_stack_evt(uint16_t event, void *p_param) /* start device discovery */ ESP_LOGI(BT_AV_TAG, "Starting device discovery..."); - m_a2d_state = APP_AV_STATE_DISCOVERING; + s_a2d_state = APP_AV_STATE_DISCOVERING; esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0); /* create and start heart beat timer */ do { int tmr_id = 0; - tmr = xTimerCreate("connTmr", (10000 / portTICK_RATE_MS), + s_tmr = xTimerCreate("connTmr", (10000 / portTICK_RATE_MS), pdTRUE, (void *)tmr_id, a2d_app_heart_beat); - xTimerStart(tmr, portMAX_DELAY); + xTimerStart(s_tmr, portMAX_DELAY); } while (0); break; } @@ -348,8 +348,8 @@ static void a2d_app_heart_beat(void *arg) static void bt_app_av_sm_hdlr(uint16_t event, void *param) { - ESP_LOGI(BT_AV_TAG, "%s state %d, evt 0x%x", __func__, m_a2d_state, event); - switch (m_a2d_state) { + ESP_LOGI(BT_AV_TAG, "%s state %d, evt 0x%x", __func__, s_a2d_state, event); + switch (s_a2d_state) { case APP_AV_STATE_DISCOVERING: case APP_AV_STATE_DISCOVERED: break; @@ -366,7 +366,7 @@ static void bt_app_av_sm_hdlr(uint16_t event, void *param) bt_app_av_state_disconnecting(event, param); break; default: - ESP_LOGE(BT_AV_TAG, "%s invalid state %d", __func__, m_a2d_state); + ESP_LOGE(BT_AV_TAG, "%s invalid state %d", __func__, s_a2d_state); break; } } @@ -380,12 +380,12 @@ static void bt_app_av_state_unconnected(uint16_t event, void *param) case ESP_A2D_MEDIA_CTRL_ACK_EVT: break; case BT_APP_HEART_BEAT_EVT: { - uint8_t *p = peer_bda; + uint8_t *p = s_peer_bda; ESP_LOGI(BT_AV_TAG, "a2dp connecting to peer: %02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2], p[3], p[4], p[5]); - esp_a2d_source_connect(peer_bda); - m_a2d_state = APP_AV_STATE_CONNECTING; - m_connecting_intv = 0; + esp_a2d_source_connect(s_peer_bda); + s_a2d_state = APP_AV_STATE_CONNECTING; + s_connecting_intv = 0; break; } default: @@ -402,11 +402,11 @@ static void bt_app_av_state_connecting(uint16_t event, void *param) a2d = (esp_a2d_cb_param_t *)(param); if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) { ESP_LOGI(BT_AV_TAG, "a2dp connected"); - m_a2d_state = APP_AV_STATE_CONNECTED; - m_media_state = APP_AV_MEDIA_STATE_IDLE; + s_a2d_state = APP_AV_STATE_CONNECTED; + s_media_state = APP_AV_MEDIA_STATE_IDLE; esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_NONE); } else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) { - m_a2d_state = APP_AV_STATE_UNCONNECTED; + s_a2d_state = APP_AV_STATE_UNCONNECTED; } break; } @@ -415,9 +415,9 @@ static void bt_app_av_state_connecting(uint16_t event, void *param) case ESP_A2D_MEDIA_CTRL_ACK_EVT: break; case BT_APP_HEART_BEAT_EVT: - if (++m_connecting_intv >= 2) { - m_a2d_state = APP_AV_STATE_UNCONNECTED; - m_connecting_intv = 0; + if (++s_connecting_intv >= 2) { + s_a2d_state = APP_AV_STATE_UNCONNECTED; + s_connecting_intv = 0; } break; default: @@ -429,7 +429,7 @@ static void bt_app_av_state_connecting(uint16_t event, void *param) static void bt_app_av_media_proc(uint16_t event, void *param) { esp_a2d_cb_param_t *a2d = NULL; - switch (m_media_state) { + switch (s_media_state) { case APP_AV_MEDIA_STATE_IDLE: { if (event == BT_APP_HEART_BEAT_EVT) { ESP_LOGI(BT_AV_TAG, "a2dp media ready checking ..."); @@ -440,7 +440,7 @@ static void bt_app_av_media_proc(uint16_t event, void *param) a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) { ESP_LOGI(BT_AV_TAG, "a2dp media ready, starting ..."); esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START); - m_media_state = APP_AV_MEDIA_STATE_STARTING; + s_media_state = APP_AV_MEDIA_STATE_STARTING; } } break; @@ -451,23 +451,23 @@ static void bt_app_av_media_proc(uint16_t event, void *param) if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_START && a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) { ESP_LOGI(BT_AV_TAG, "a2dp media start successfully."); - m_intv_cnt = 0; - m_media_state = APP_AV_MEDIA_STATE_STARTED; + s_intv_cnt = 0; + s_media_state = APP_AV_MEDIA_STATE_STARTED; } else { // not started succesfully, transfer to idle state ESP_LOGI(BT_AV_TAG, "a2dp media start failed."); - m_media_state = APP_AV_MEDIA_STATE_IDLE; + s_media_state = APP_AV_MEDIA_STATE_IDLE; } } break; } case APP_AV_MEDIA_STATE_STARTED: { if (event == BT_APP_HEART_BEAT_EVT) { - if (++m_intv_cnt >= 10) { + if (++s_intv_cnt >= 10) { ESP_LOGI(BT_AV_TAG, "a2dp media stopping..."); esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP); - m_media_state = APP_AV_MEDIA_STATE_STOPPING; - m_intv_cnt = 0; + s_media_state = APP_AV_MEDIA_STATE_STOPPING; + s_intv_cnt = 0; } } break; @@ -478,9 +478,9 @@ static void bt_app_av_media_proc(uint16_t event, void *param) if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_STOP && a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) { ESP_LOGI(BT_AV_TAG, "a2dp media stopped successfully, disconnecting..."); - m_media_state = APP_AV_MEDIA_STATE_IDLE; - esp_a2d_source_disconnect(peer_bda); - m_a2d_state = APP_AV_STATE_DISCONNECTING; + s_media_state = APP_AV_MEDIA_STATE_IDLE; + esp_a2d_source_disconnect(s_peer_bda); + s_a2d_state = APP_AV_STATE_DISCONNECTING; } else { ESP_LOGI(BT_AV_TAG, "a2dp media stopping..."); esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP); @@ -499,7 +499,7 @@ static void bt_app_av_state_connected(uint16_t event, void *param) a2d = (esp_a2d_cb_param_t *)(param); if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) { ESP_LOGI(BT_AV_TAG, "a2dp disconnected"); - m_a2d_state = APP_AV_STATE_UNCONNECTED; + s_a2d_state = APP_AV_STATE_UNCONNECTED; esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); } break; @@ -507,7 +507,7 @@ static void bt_app_av_state_connected(uint16_t event, void *param) case ESP_A2D_AUDIO_STATE_EVT: { a2d = (esp_a2d_cb_param_t *)(param); if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) { - m_pkt_cnt = 0; + s_pkt_cnt = 0; } break; } @@ -533,7 +533,7 @@ static void bt_app_av_state_disconnecting(uint16_t event, void *param) a2d = (esp_a2d_cb_param_t *)(param); if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) { ESP_LOGI(BT_AV_TAG, "a2dp disconnected"); - m_a2d_state = APP_AV_STATE_UNCONNECTED; + s_a2d_state = APP_AV_STATE_UNCONNECTED; esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); } break; diff --git a/examples/bluetooth/blufi/main/blufi_security.c b/examples/bluetooth/blufi/main/blufi_security.c index c32d3ad49..49ba6c1c6 100644 --- a/examples/bluetooth/blufi/main/blufi_security.c +++ b/examples/bluetooth/blufi/main/blufi_security.c @@ -61,11 +61,7 @@ static struct blufi_security *blufi_sec; static int myrand( void *rng_state, unsigned char *output, size_t len ) { - size_t i; - - for( i = 0; i < len; ++i ) - output[i] = esp_random(); - + esp_fill_random(output, len); return( 0 ); } diff --git a/examples/peripherals/can/can_self_test/main/can_self_test_example_main.c b/examples/peripherals/can/can_self_test/main/can_self_test_example_main.c index 34af55943..a00a46ad8 100644 --- a/examples/peripherals/can/can_self_test/main/can_self_test_example_main.c +++ b/examples/peripherals/can/can_self_test/main/can_self_test_example_main.c @@ -120,7 +120,7 @@ void app_main() xTaskCreatePinnedToCore(can_transmit_task, "CAN_tx", 4096, NULL, TX_TASK_PRIO, NULL, tskNO_AFFINITY); //Install CAN driver - ESP_ERROR_CHECK(can_driver_install(&g_config, & t_config, &f_config)); + ESP_ERROR_CHECK(can_driver_install(&g_config, &t_config, &f_config)); ESP_LOGI(EXAMPLE_TAG, "Driver installed"); //Start control task diff --git a/examples/wifi/espnow/README.md b/examples/wifi/espnow/README.md index 595d51d55..0c3642b43 100644 --- a/examples/wifi/espnow/README.md +++ b/examples/wifi/espnow/README.md @@ -1,30 +1,115 @@ # ESPNOW Example +(See the README.md file in the upper level 'examples' directory for more information about examples.) + This example shows how to use ESPNOW of wifi. Example does the following steps: -1. Start WiFi. +* Start WiFi. +* Initialize ESPNOW. +* Register ESPNOW sending or receiving callback function. +* Add ESPNOW peer information. +* Send and receive ESPNOW data. -2. Initialize ESPNOW. +This example need at least two ESP devices: -3. Register ESPNOW sending or receiving callback function. - -4. Add ESPNOW peer information. - -5. Send and receive ESPNOW data. - -In order to get the MAC address of the other device, firstly send broadcast ESPNOW data to each other with 'state' set as 0. When receiving -broadcast ESPNOW data with 'state' as 0, add the device from which the data comes to the peer list. Then start sending broadcast ESPNOW -data with 'state' set as 1. When receiving broadcast ESPNOW data with 'state' as 1, compare the local magic number with that in the data. -If the local one is bigger than that one, stop sending broadcast ESPNOW data and start sending unicast ESPNOW data. If receive unicast -ESPNOW data, also stop sending broadcast ESPNOW data. That is what happens in this example. It shows how to send/receive broadcast/unicast -ESPNOW data. In practice, if the MAC address of the other device is known, it's not required to send/receive broadcast ESPNOW data first, -just add the device to the peer list and send/receive unicast ESPNOW data. +* In order to get the MAC address of the other device, Device1 firstly send broadcast ESPNOW data with 'state' set as 0. +* When Device2 receiving broadcast ESPNOW data from Device1 with 'state' as 0, adds Device1 into the peer list. + Then start sending broadcast ESPNOW data with 'state' set as 1. +* When Device1 receiving broadcast ESPNOW data with 'state' as 1, compares the local magic number with that in the data. + If the local one is bigger than that one, stop sending broadcast ESPNOW data and starts sending unicast ESPNOW data to Device2. +* If Device2 receives unicast ESPNOW data, also stop sending broadcast ESPNOW data. + +In practice, if the MAC address of the other device is known, it's not required to send/receive broadcast ESPNOW data first, +just add the device into the peer list and send/receive unicast ESPNOW data. There are a lot of "extras" on top of ESPNOW data, such as type, state, sequence number, CRC and magic in this example. These "extras" are not required to use ESPNOW. They are only used to make this example to run correctly. However, it is recommended that users add some "extras" to make ESPNOW data more safe and more reliable. -*Note:* The two devices can be set as either station or softap or station+softap mode. If the receiving device is in station mode only -and it connects to an AP, modem sleep should be disabled. +## How to use example -More info in the code [espnow_example_main.c](./main/espnow_example_main.c). +### Configure the project + +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. +* Set WiFi mode (station or SoftAP) under Example Configuration Options. +* Set ESPNOW primary master key under Example Configuration Options. + This parameter must be set to the same value for sending and recving devices. +* Set ESPNOW local master key under Example Configuration Options. + This parameter must be set to the same value for sending and recving devices. +* Set Channel under Example Configuration Options. + The sending device and the recving device must be on the same channel. +* Set Send count and Send delay under Example Configuration Options. +* Set Send len under Example Configuration Options. + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +Here is the example of ESPNOW receiving device console output. + +``` +I (898) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 +I (898) wifi: mode : sta (30:ae:a4:80:45:68) +I (898) espnow_example: WiFi started +I (898) ESPNOW: espnow [version: 1.0] init +I (5908) espnow_example: Start sending broadcast data +I (6908) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (7908) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (52138) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (52138) espnow_example: Receive 0th broadcast data from: 30:ae:a4:0c:34:ec, len: 200 +I (53158) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (53158) espnow_example: Receive 1th broadcast data from: 30:ae:a4:0c:34:ec, len: 200 +I (54168) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (54168) espnow_example: Receive 2th broadcast data from: 30:ae:a4:0c:34:ec, len: 200 +I (54168) espnow_example: Receive 0th unicast data from: 30:ae:a4:0c:34:ec, len: 200 +I (54678) espnow_example: Receive 1th unicast data from: 30:ae:a4:0c:34:ec, len: 200 +I (55668) espnow_example: Receive 2th unicast data from: 30:ae:a4:0c:34:ec, len: 200 +``` + +Here is the example of ESPNOW sending device console output. + +``` +I (915) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 +I (915) wifi: mode : sta (30:ae:a4:0c:34:ec) +I (915) espnow_example: WiFi started +I (915) ESPNOW: espnow [version: 1.0] init +I (5915) espnow_example: Start sending broadcast data +I (5915) espnow_example: Receive 41th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (5915) espnow_example: Receive 42th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (5925) espnow_example: Receive 44th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (5935) espnow_example: Receive 45th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (6965) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (6965) espnow_example: Receive 46th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (7975) espnow_example: send data to ff:ff:ff:ff:ff:ff +I (7975) espnow_example: Receive 47th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (7975) espnow_example: Start sending unicast data +I (7975) espnow_example: send data to 30:ae:a4:80:45:68 +I (9015) espnow_example: send data to 30:ae:a4:80:45:68 +I (9015) espnow_example: Receive 48th broadcast data from: 30:ae:a4:80:45:68, len: 200 +I (10015) espnow_example: send data to 30:ae:a4:80:45:68 +I (16075) espnow_example: send data to 30:ae:a4:80:45:68 +I (17075) espnow_example: send data to 30:ae:a4:80:45:68 +I (24125) espnow_example: send data to 30:ae:a4:80:45:68 +``` + +## Troubleshooting + +If ESPNOW data can not be received from another device, maybe the two devices are not +on the same channel or the primary key and local key are different. + +In real application, if the receiving device is in station mode only and it connects to an AP, +modem sleep should be disabled. Otherwise, it may fail to revceive ESPNOW data from other devices. diff --git a/examples/wifi/espnow/main/espnow_example.h b/examples/wifi/espnow/main/espnow_example.h index b53e40317..c1881886c 100644 --- a/examples/wifi/espnow/main/espnow_example.h +++ b/examples/wifi/espnow/main/espnow_example.h @@ -21,7 +21,7 @@ #define ESPNOW_QUEUE_SIZE 6 -#define IS_BROADCAST_ADDR(addr) (memcmp(addr, example_broadcast_mac, ESP_NOW_ETH_ALEN) == 0) +#define IS_BROADCAST_ADDR(addr) (memcmp(addr, s_example_broadcast_mac, ESP_NOW_ETH_ALEN) == 0) typedef enum { EXAMPLE_ESPNOW_SEND_CB, diff --git a/examples/wifi/espnow/main/espnow_example_main.c b/examples/wifi/espnow/main/espnow_example_main.c index afb1428c5..78576137a 100644 --- a/examples/wifi/espnow/main/espnow_example_main.c +++ b/examples/wifi/espnow/main/espnow_example_main.c @@ -32,9 +32,9 @@ static const char *TAG = "espnow_example"; -static xQueueHandle example_espnow_queue; +static xQueueHandle s_example_espnow_queue; -static uint8_t example_broadcast_mac[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; +static uint8_t s_example_broadcast_mac[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; static uint16_t s_example_espnow_seq[EXAMPLE_ESPNOW_DATA_MAX] = { 0, 0 }; static void example_espnow_deinit(example_espnow_send_param_t *send_param); @@ -85,7 +85,7 @@ static void example_espnow_send_cb(const uint8_t *mac_addr, esp_now_send_status_ evt.id = EXAMPLE_ESPNOW_SEND_CB; memcpy(send_cb->mac_addr, mac_addr, ESP_NOW_ETH_ALEN); send_cb->status = status; - if (xQueueSend(example_espnow_queue, &evt, portMAX_DELAY) != pdTRUE) { + if (xQueueSend(s_example_espnow_queue, &evt, portMAX_DELAY) != pdTRUE) { ESP_LOGW(TAG, "Send send queue fail"); } } @@ -109,7 +109,7 @@ static void example_espnow_recv_cb(const uint8_t *mac_addr, const uint8_t *data, } memcpy(recv_cb->data, data, len); recv_cb->data_len = len; - if (xQueueSend(example_espnow_queue, &evt, portMAX_DELAY) != pdTRUE) { + if (xQueueSend(s_example_espnow_queue, &evt, portMAX_DELAY) != pdTRUE) { ESP_LOGW(TAG, "Send receive queue fail"); free(recv_cb->data); } @@ -144,7 +144,6 @@ int example_espnow_data_parse(uint8_t *data, uint16_t data_len, uint8_t *state, void example_espnow_data_prepare(example_espnow_send_param_t *send_param) { example_espnow_data_t *buf = (example_espnow_data_t *)send_param->buffer; - int i = 0; assert(send_param->len >= sizeof(example_espnow_data_t)); @@ -153,9 +152,8 @@ void example_espnow_data_prepare(example_espnow_send_param_t *send_param) buf->seq_num = s_example_espnow_seq[buf->type]++; buf->crc = 0; buf->magic = send_param->magic; - for (i = 0; i < send_param->len - sizeof(example_espnow_data_t); i++) { - buf->payload[i] = (uint8_t)esp_random(); - } + /* Fill all remaining bytes after the data with random values */ + esp_fill_random(buf->payload, send_param->len - sizeof(example_espnow_data_t)); buf->crc = crc16_le(UINT16_MAX, (uint8_t const *)buf, send_param->len); } @@ -179,7 +177,7 @@ static void example_espnow_task(void *pvParameter) vTaskDelete(NULL); } - while (xQueueReceive(example_espnow_queue, &evt, portMAX_DELAY) == pdTRUE) { + while (xQueueReceive(s_example_espnow_queue, &evt, portMAX_DELAY) == pdTRUE) { switch (evt.id) { case EXAMPLE_ESPNOW_SEND_CB: { @@ -301,8 +299,8 @@ static esp_err_t example_espnow_init(void) { example_espnow_send_param_t *send_param; - example_espnow_queue = xQueueCreate(ESPNOW_QUEUE_SIZE, sizeof(example_espnow_event_t)); - if (example_espnow_queue == NULL) { + s_example_espnow_queue = xQueueCreate(ESPNOW_QUEUE_SIZE, sizeof(example_espnow_event_t)); + if (s_example_espnow_queue == NULL) { ESP_LOGE(TAG, "Create mutex fail"); return ESP_FAIL; } @@ -319,7 +317,7 @@ static esp_err_t example_espnow_init(void) esp_now_peer_info_t *peer = malloc(sizeof(esp_now_peer_info_t)); if (peer == NULL) { ESP_LOGE(TAG, "Malloc peer information fail"); - vSemaphoreDelete(example_espnow_queue); + vSemaphoreDelete(s_example_espnow_queue); esp_now_deinit(); return ESP_FAIL; } @@ -327,7 +325,7 @@ static esp_err_t example_espnow_init(void) peer->channel = CONFIG_ESPNOW_CHANNEL; peer->ifidx = ESPNOW_WIFI_IF; peer->encrypt = false; - memcpy(peer->peer_addr, example_broadcast_mac, ESP_NOW_ETH_ALEN); + memcpy(peer->peer_addr, s_example_broadcast_mac, ESP_NOW_ETH_ALEN); ESP_ERROR_CHECK( esp_now_add_peer(peer) ); free(peer); @@ -336,7 +334,7 @@ static esp_err_t example_espnow_init(void) memset(send_param, 0, sizeof(example_espnow_send_param_t)); if (send_param == NULL) { ESP_LOGE(TAG, "Malloc send parameter fail"); - vSemaphoreDelete(example_espnow_queue); + vSemaphoreDelete(s_example_espnow_queue); esp_now_deinit(); return ESP_FAIL; } @@ -351,11 +349,11 @@ static esp_err_t example_espnow_init(void) if (send_param->buffer == NULL) { ESP_LOGE(TAG, "Malloc send buffer fail"); free(send_param); - vSemaphoreDelete(example_espnow_queue); + vSemaphoreDelete(s_example_espnow_queue); esp_now_deinit(); return ESP_FAIL; } - memcpy(send_param->dest_mac, example_broadcast_mac, ESP_NOW_ETH_ALEN); + memcpy(send_param->dest_mac, s_example_broadcast_mac, ESP_NOW_ETH_ALEN); example_espnow_data_prepare(send_param); xTaskCreate(example_espnow_task, "example_espnow_task", 2048, send_param, 4, NULL); @@ -367,7 +365,7 @@ static void example_espnow_deinit(example_espnow_send_param_t *send_param) { free(send_param->buffer); free(send_param); - vSemaphoreDelete(example_espnow_queue); + vSemaphoreDelete(s_example_espnow_queue); esp_now_deinit(); } diff --git a/examples/wifi/simple_wifi/CMakeLists.txt b/examples/wifi/getting_started/softAP/CMakeLists.txt similarity index 100% rename from examples/wifi/simple_wifi/CMakeLists.txt rename to examples/wifi/getting_started/softAP/CMakeLists.txt diff --git a/examples/wifi/simple_wifi/Makefile b/examples/wifi/getting_started/softAP/Makefile similarity index 84% rename from examples/wifi/simple_wifi/Makefile rename to examples/wifi/getting_started/softAP/Makefile index b9ced39c0..507c5e060 100644 --- a/examples/wifi/simple_wifi/Makefile +++ b/examples/wifi/getting_started/softAP/Makefile @@ -3,7 +3,7 @@ # project subdirectory. # -PROJECT_NAME := simple_wifi +PROJECT_NAME := wifi_softAP include $(IDF_PATH)/make/project.mk diff --git a/examples/wifi/getting_started/softAP/README.md b/examples/wifi/getting_started/softAP/README.md new file mode 100644 index 000000000..8d831d29b --- /dev/null +++ b/examples/wifi/getting_started/softAP/README.md @@ -0,0 +1,42 @@ +# WiFi softAP example + +(See the README.md file in the upper level 'examples' directory for more information about examples.) + + +## How to use example + +### Configure the project + +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. + +* Set WiFi SSID and WiFi Password and Maximal STA connections under Example Configuration Options. + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +There is the console output for this example: + +``` +I (917) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 +I (917) wifi: mode : softAP (30:ae:a4:80:45:69) +I (917) wifi softAP: wifi_init_softap finished.SSID:myssid password:mypassword +I (26457) wifi: n:1 0, o:1 0, ap:1 1, sta:255 255, prof:1 +I (26457) wifi: station: 70:ef:00:43:96:67 join, AID=1, bg, 20 +I (26467) wifi softAP: station:70:ef:00:43:96:67 join, AID=1 +I (27657) tcpip_adapter: softAP assign IP to station,IP is: 192.168.4.2 +``` diff --git a/examples/wifi/simple_wifi/main/Kconfig.projbuild b/examples/wifi/getting_started/softAP/main/Kconfig.projbuild similarity index 51% rename from examples/wifi/simple_wifi/main/Kconfig.projbuild rename to examples/wifi/getting_started/softAP/main/Kconfig.projbuild index 67bb8677c..1b37eb2fe 100644 --- a/examples/wifi/simple_wifi/main/Kconfig.projbuild +++ b/examples/wifi/getting_started/softAP/main/Kconfig.projbuild @@ -1,22 +1,5 @@ menu "Example Configuration" -choice ESP_WIFI_MODE - prompt "AP or STA" - default ESP_WIFI_IS_STATION - help - Whether the esp32 is softAP or station. - -config ESP_WIFI_IS_SOFTAP - bool "SoftAP" -config ESP_WIFI_IS_STATION - bool "Station" -endchoice - -config ESP_WIFI_MODE_AP - bool - default y if ESP_WIFI_IS_SOFTAP - default n if ESP_WIFI_IS_STATION - config ESP_WIFI_SSID string "WiFi SSID" default "myssid" @@ -30,7 +13,7 @@ config ESP_WIFI_PASSWORD WiFi password (WPA or WPA2) for the example to use. config MAX_STA_CONN - int "Max STA conn" + int "Maximal STA connections" default 4 help Max number of the STA connects to AP. diff --git a/examples/wifi/simple_wifi/main/component.mk b/examples/wifi/getting_started/softAP/main/component.mk similarity index 100% rename from examples/wifi/simple_wifi/main/component.mk rename to examples/wifi/getting_started/softAP/main/component.mk diff --git a/examples/wifi/simple_wifi/main/simple_wifi.c b/examples/wifi/getting_started/softAP/main/softap_example_main.c similarity index 60% rename from examples/wifi/simple_wifi/main/simple_wifi.c rename to examples/wifi/getting_started/softAP/main/softap_example_main.c index 456e880ee..e64871057 100644 --- a/examples/wifi/simple_wifi/main/simple_wifi.c +++ b/examples/wifi/getting_started/softAP/main/softap_example_main.c @@ -1,4 +1,4 @@ -/* Simple WiFi Example +/* WiFi softAP Example This example code is in the Public Domain (or CC0 licensed, at your option.) @@ -19,38 +19,23 @@ #include "lwip/err.h" #include "lwip/sys.h" -/* The examples use simple WiFi configuration that you can set via - 'make menuconfig'. +/* The examples use WiFi configuration that you can set via 'make menuconfig'. If you'd rather not, just change the below entries to strings with the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" */ -#define EXAMPLE_ESP_WIFI_MODE_AP CONFIG_ESP_WIFI_MODE_AP //TRUE:AP FALSE:STA #define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID #define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD #define EXAMPLE_MAX_STA_CONN CONFIG_MAX_STA_CONN /* FreeRTOS event group to signal when we are connected*/ -static EventGroupHandle_t wifi_event_group; +static EventGroupHandle_t s_wifi_event_group; -/* The event group allows multiple bits for each event, - but we only care about one event - are we connected - to the AP with an IP? */ -const int WIFI_CONNECTED_BIT = BIT0; - -static const char *TAG = "simple wifi"; +static const char *TAG = "wifi softAP"; static esp_err_t event_handler(void *ctx, system_event_t *event) { switch(event->event_id) { - case SYSTEM_EVENT_STA_START: - esp_wifi_connect(); - break; - case SYSTEM_EVENT_STA_GOT_IP: - ESP_LOGI(TAG, "got ip:%s", - ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); - xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT); - break; case SYSTEM_EVENT_AP_STACONNECTED: ESP_LOGI(TAG, "station:"MACSTR" join, AID=%d", MAC2STR(event->event_info.sta_connected.mac), @@ -61,10 +46,6 @@ static esp_err_t event_handler(void *ctx, system_event_t *event) MAC2STR(event->event_info.sta_disconnected.mac), event->event_info.sta_disconnected.aid); break; - case SYSTEM_EVENT_STA_DISCONNECTED: - esp_wifi_connect(); - xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT); - break; default: break; } @@ -73,7 +54,7 @@ static esp_err_t event_handler(void *ctx, system_event_t *event) void wifi_init_softap() { - wifi_event_group = xEventGroupCreate(); + s_wifi_event_group = xEventGroupCreate(); tcpip_adapter_init(); ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL)); @@ -101,31 +82,6 @@ void wifi_init_softap() EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); } -void wifi_init_sta() -{ - wifi_event_group = xEventGroupCreate(); - - tcpip_adapter_init(); - ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) ); - - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - ESP_ERROR_CHECK(esp_wifi_init(&cfg)); - wifi_config_t wifi_config = { - .sta = { - .ssid = EXAMPLE_ESP_WIFI_SSID, - .password = EXAMPLE_ESP_WIFI_PASS - }, - }; - - ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); - ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); - ESP_ERROR_CHECK(esp_wifi_start() ); - - ESP_LOGI(TAG, "wifi_init_sta finished."); - ESP_LOGI(TAG, "connect to ap SSID:%s password:%s", - EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); -} - void app_main() { //Initialize NVS @@ -136,12 +92,6 @@ void app_main() } ESP_ERROR_CHECK(ret); -#if EXAMPLE_ESP_WIFI_MODE_AP ESP_LOGI(TAG, "ESP_WIFI_MODE_AP"); wifi_init_softap(); -#else - ESP_LOGI(TAG, "ESP_WIFI_MODE_STA"); - wifi_init_sta(); -#endif /*EXAMPLE_ESP_WIFI_MODE_AP*/ - } diff --git a/examples/wifi/getting_started/station/Makefile b/examples/wifi/getting_started/station/Makefile new file mode 100644 index 000000000..ed014837a --- /dev/null +++ b/examples/wifi/getting_started/station/Makefile @@ -0,0 +1,9 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := wifi_station + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/wifi/getting_started/station/README.md b/examples/wifi/getting_started/station/README.md new file mode 100644 index 000000000..6666da534 --- /dev/null +++ b/examples/wifi/getting_started/station/README.md @@ -0,0 +1,97 @@ +# WiFi station example + +(See the README.md file in the upper level 'examples' directory for more information about examples.) + + +## How to use example + +### Configure the project + +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. + +* Set WiFi SSID and WiFi Password and Maximum retry under Example Configuration Options. + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +There is the console output for station connects to ap successfully: +``` +I (727) wifi station: ESP_WIFI_MODE_STA +I (727) wifi: wifi driver task: 3ffc0c68, prio:23, stack:3584, core=0 +I (727) wifi: wifi firmware version: 19b3110 +I (727) wifi: config NVS flash: enabled +I (727) wifi: config nano formating: disabled +I (737) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (747) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (777) wifi: Init dynamic tx buffer num: 32 +I (777) wifi: Init data frame dynamic rx buffer num: 32 +I (777) wifi: Init management frame dynamic rx buffer num: 32 +I (777) wifi: Init static rx buffer size: 1600 +I (787) wifi: Init static rx buffer num: 10 +I (787) wifi: Init dynamic rx buffer num: 32 +I (907) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 +I (907) wifi: mode : sta (30:ae:a4:80:45:68) +I (907) wifi station: wifi_init_sta finished. +I (907) wifi station: connect to ap SSID:myssid password:mypassword +I (1027) wifi: n:6 0, o:1 0, ap:255 255, sta:6 0, prof:1 +I (2017) wifi: state: init -> auth (b0) +I (2017) wifi: state: auth -> assoc (0) +I (2027) wifi: state: assoc -> run (10) +I (2067) wifi: connected with myssid, channel 6 +I (2067) wifi: pm start, type: 1 + +I (3227) event: sta ip: 172.20.10.7, mask: 255.255.255.240, gw: 172.20.10.1 +I (3227) wifi station: got ip:172.20.10.7 +``` + +There is the console output for station connects to ap failed: +``` +I (728) wifi station: ESP_WIFI_MODE_STA +I (728) wifi: wifi driver task: 3ffc0c68, prio:23, stack:3584, core=0 +I (728) wifi: wifi firmware version: 19b3110 +I (728) wifi: config NVS flash: enabled +I (738) wifi: config nano formating: disabled +I (738) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (748) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE +I (778) wifi: Init dynamic tx buffer num: 32 +I (778) wifi: Init data frame dynamic rx buffer num: 32 +I (778) wifi: Init management frame dynamic rx buffer num: 32 +I (788) wifi: Init static rx buffer size: 1600 +I (788) wifi: Init static rx buffer num: 10 +I (788) wifi: Init dynamic rx buffer num: 32 +I (908) phy: phy_version: 3960, 5211945, Jul 18 2018, 10:40:07, 0, 0 +I (908) wifi: mode : sta (30:ae:a4:80:45:68) +I (908) wifi station: wifi_init_sta finished. +I (918) wifi station: connect to ap SSID:myssid password:mypassword +I (3328) wifi station: retry to connect to the AP +I (3328) wifi station: connect to the AP fail + +I (5738) wifi station: retry to connect to the AP +I (5738) wifi station: connect to the AP fail + +I (8148) wifi station: retry to connect to the AP +I (8148) wifi station: connect to the AP fail + +I (10558) wifi station: retry to connect to the AP +I (10558) wifi station: connect to the AP fail + +I (12968) wifi station: retry to connect to the AP +I (12968) wifi station: connect to the AP fail + +I (15378) wifi station: connect to the AP fail +``` diff --git a/examples/wifi/getting_started/station/main/Kconfig.projbuild b/examples/wifi/getting_started/station/main/Kconfig.projbuild new file mode 100644 index 000000000..0c74a747a --- /dev/null +++ b/examples/wifi/getting_started/station/main/Kconfig.projbuild @@ -0,0 +1,20 @@ +menu "Example Configuration" + +config ESP_WIFI_SSID + string "WiFi SSID" + default "myssid" + help + SSID (network name) for the example to connect to. + +config ESP_WIFI_PASSWORD + string "WiFi Password" + default "mypassword" + help + WiFi password (WPA or WPA2) for the example to use. + +config ESP_MAXIMUM_RETRY + int "Maximum retry" + default 5 + help + Set the Maximum retry to avoid station reconnecting to the AP unlimited when the AP is really inexistent. +endmenu diff --git a/examples/wifi/getting_started/station/main/component.mk b/examples/wifi/getting_started/station/main/component.mk new file mode 100644 index 000000000..61f8990c3 --- /dev/null +++ b/examples/wifi/getting_started/station/main/component.mk @@ -0,0 +1,8 @@ +# +# Main component makefile. +# +# This Makefile can be left empty. By default, it will take the sources in the +# src/ directory, compile them and link them into lib(subdirectory_name).a +# in the build directory. This behaviour is entirely configurable, +# please read the ESP-IDF documents if you need to do this. +# diff --git a/examples/wifi/getting_started/station/main/station_example_main.c b/examples/wifi/getting_started/station/main/station_example_main.c new file mode 100644 index 000000000..71e529732 --- /dev/null +++ b/examples/wifi/getting_started/station/main/station_example_main.c @@ -0,0 +1,108 @@ +/* WiFi station Example + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "esp_event_loop.h" +#include "esp_log.h" +#include "nvs_flash.h" + +#include "lwip/err.h" +#include "lwip/sys.h" + +/* The examples use WiFi configuration that you can set via 'make menuconfig'. + + If you'd rather not, just change the below entries to strings with + the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" +*/ +#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID +#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD +#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY + +/* FreeRTOS event group to signal when we are connected*/ +static EventGroupHandle_t s_wifi_event_group; + +/* The event group allows multiple bits for each event, but we only care about one event + * - are we connected to the AP with an IP? */ +const int WIFI_CONNECTED_BIT = BIT0; + +static const char *TAG = "wifi station"; + +static int s_retry_num = 0; + +static esp_err_t event_handler(void *ctx, system_event_t *event) +{ + switch(event->event_id) { + case SYSTEM_EVENT_STA_START: + esp_wifi_connect(); + break; + case SYSTEM_EVENT_STA_GOT_IP: + ESP_LOGI(TAG, "got ip:%s", + ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip)); + s_retry_num = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + { + if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) { + esp_wifi_connect(); + xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + s_retry_num++; + ESP_LOGI(TAG,"retry to connect to the AP"); + } + ESP_LOGI(TAG,"connect to the AP fail\n"); + break; + } + default: + break; + } + return ESP_OK; +} + +void wifi_init_sta() +{ + s_wifi_event_group = xEventGroupCreate(); + + tcpip_adapter_init(); + ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) ); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + wifi_config_t wifi_config = { + .sta = { + .ssid = EXAMPLE_ESP_WIFI_SSID, + .password = EXAMPLE_ESP_WIFI_PASS + }, + }; + + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); + ESP_ERROR_CHECK(esp_wifi_start() ); + + ESP_LOGI(TAG, "wifi_init_sta finished."); + ESP_LOGI(TAG, "connect to ap SSID:%s password:%s", + EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS); +} + +void app_main() +{ + //Initialize NVS + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK(ret); + + ESP_LOGI(TAG, "ESP_WIFI_MODE_STA"); + wifi_init_sta(); +} diff --git a/examples/wifi/smart_config/README.md b/examples/wifi/smart_config/README.md index 9453edbb6..7f8ee90c7 100644 --- a/examples/wifi/smart_config/README.md +++ b/examples/wifi/smart_config/README.md @@ -1,17 +1,40 @@ # smartconfig Example -This example shows how ESP32 connects to AP with ESPTOUCH. Example does the following steps: +This example shows how ESP32 connects to a target AP with ESPTOUCH. -* Download ESPTOUCH APP from app store. [Android source code](https://github.com/EspressifApp/EsptouchForAndroid) and [iOS source code](https://github.com/EspressifApp/EsptouchForIOS) is available. +## How to use example -* Compile this example and upload it to an ESP32. +### Hardware Required -* Make sure your phone connect to target AP (2.4GHz). +Download ESPTOUCH APP from app store: +[Android source code](https://github.com/EspressifApp/EsptouchForAndroid) +[iOS source code](https://github.com/EspressifApp/EsptouchForIOS) is available. +### Configure the project + +``` +make menuconfig +``` + +* Set serial port under Serial Flasher Options. + +### Build and Flash + +Build the project and flash it to the board, then run monitor tool to view serial output: + +``` +make -j4 flash monitor +``` + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Example output + +* Make sure your phone connect to the target AP (2.4GHz). * Open ESPTOUCH app and input password. There will be success message after few sec. -### Example output - Here is an example of smartconfig console output. ``` I (372) wifi: mode : sta (24:0a:c4:00:44:86) diff --git a/examples/wifi/smart_config/main/smartconfig_main.c b/examples/wifi/smart_config/main/smartconfig_main.c index 3cbf8737d..71e9365e4 100644 --- a/examples/wifi/smart_config/main/smartconfig_main.c +++ b/examples/wifi/smart_config/main/smartconfig_main.c @@ -22,7 +22,7 @@ #include "esp_smartconfig.h" /* FreeRTOS event group to signal when we are connected & ready to make a request */ -static EventGroupHandle_t wifi_event_group; +static EventGroupHandle_t s_wifi_event_group; /* The event group allows multiple bits for each event, but we only care about one event - are we connected @@ -40,11 +40,11 @@ static esp_err_t event_handler(void *ctx, system_event_t *event) xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 4096, NULL, 3, NULL); break; case SYSTEM_EVENT_STA_GOT_IP: - xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); + xEventGroupSetBits(s_wifi_event_group, CONNECTED_BIT); break; case SYSTEM_EVENT_STA_DISCONNECTED: esp_wifi_connect(); - xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); + xEventGroupClearBits(s_wifi_event_group, CONNECTED_BIT); break; default: break; @@ -55,7 +55,7 @@ static esp_err_t event_handler(void *ctx, system_event_t *event) static void initialise_wifi(void) { tcpip_adapter_init(); - wifi_event_group = xEventGroupCreate(); + s_wifi_event_group = xEventGroupCreate(); ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); @@ -93,7 +93,7 @@ static void sc_callback(smartconfig_status_t status, void *pdata) memcpy(phone_ip, (uint8_t* )pdata, 4); ESP_LOGI(TAG, "Phone ip: %d.%d.%d.%d\n", phone_ip[0], phone_ip[1], phone_ip[2], phone_ip[3]); } - xEventGroupSetBits(wifi_event_group, ESPTOUCH_DONE_BIT); + xEventGroupSetBits(s_wifi_event_group, ESPTOUCH_DONE_BIT); break; default: break; @@ -106,7 +106,7 @@ void smartconfig_example_task(void * parm) ESP_ERROR_CHECK( esp_smartconfig_set_type(SC_TYPE_ESPTOUCH) ); ESP_ERROR_CHECK( esp_smartconfig_start(sc_callback) ); while (1) { - uxBits = xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT | ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY); + uxBits = xEventGroupWaitBits(s_wifi_event_group, CONNECTED_BIT | ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY); if(uxBits & CONNECTED_BIT) { ESP_LOGI(TAG, "WiFi Connected to ap"); } diff --git a/make/project.mk b/make/project.mk index f3ceeba1a..364f72970 100644 --- a/make/project.mk +++ b/make/project.mk @@ -13,7 +13,7 @@ .PHONY: build-components menuconfig defconfig all build clean all_binaries check-submodules size size-components size-files size-symbols list-components MAKECMDGOALS ?= all -all: all_binaries check_python_dependencies +all: all_binaries | check_python_dependencies # see below for recipe of 'all' target # # # other components will add dependencies to 'all_binaries'. The @@ -485,16 +485,16 @@ app-clean: $(addprefix component-,$(addsuffix -clean,$(notdir $(COMPONENT_PATHS) $(summary) RM $(APP_ELF) rm -f $(APP_ELF) $(APP_BIN) $(APP_MAP) -size: check_python_dependencies $(APP_ELF) +size: $(APP_ELF) | check_python_dependencies $(PYTHON) $(IDF_PATH)/tools/idf_size.py $(APP_MAP) -size-files: check_python_dependencies $(APP_ELF) +size-files: $(APP_ELF) | check_python_dependencies $(PYTHON) $(IDF_PATH)/tools/idf_size.py --files $(APP_MAP) -size-components: check_python_dependencies $(APP_ELF) +size-components: $(APP_ELF) | check_python_dependencies $(PYTHON) $(IDF_PATH)/tools/idf_size.py --archives $(APP_MAP) -size-symbols: check_python_dependencies $(APP_ELF) +size-symbols: $(APP_ELF) | check_python_dependencies ifndef COMPONENT $(error "ERROR: Please enter the component to look symbols for, e.g. COMPONENT=heap") else diff --git a/tools/check_python_dependencies.py b/tools/check_python_dependencies.py old mode 100644 new mode 100755 index 9c5f8e855..30eaffc02 --- a/tools/check_python_dependencies.py +++ b/tools/check_python_dependencies.py @@ -16,6 +16,7 @@ import os import sys +import argparse try: import pkg_resources except: @@ -24,11 +25,17 @@ except: 'setting up the required packages.') sys.exit(1) -req_file = '{}/requirements.txt'.format(os.getenv("IDF_PATH")) - if __name__ == "__main__": + idf_path = os.getenv("IDF_PATH") + + parser = argparse.ArgumentParser(description='ESP32 Python package dependency checker') + parser.add_argument('--requirements', '-r', + help='Path to the requrements file', + default=idf_path + '/requirements.txt') + args = parser.parse_args() + not_satisfied = [] - with open(req_file) as f: + with open(args.requirements) as f: for line in f: line = line.strip() try: @@ -40,7 +47,7 @@ if __name__ == "__main__": print('The following Python requirements are not satisfied:') for requirement in not_satisfied: print(requirement) - print('Please run "{} -m pip install -r {}" for resolving the issue.'.format(sys.executable, req_file)) + print('Please run "{} -m pip install -r {}" for resolving the issue.'.format(sys.executable, args.requirements)) sys.exit(1) - print('Python requirements are satisfied.') + print('Python requirements from {} are satisfied.'.format(args.requirements)) diff --git a/tools/ci/executable-list.txt b/tools/ci/executable-list.txt index 3579a6e9d..e240013c0 100644 --- a/tools/ci/executable-list.txt +++ b/tools/ci/executable-list.txt @@ -60,4 +60,6 @@ tools/kconfig_new/confserver.py tools/kconfig_new/test/test_confserver.py tools/windows/tool_setup/build_installer.sh tools/test_idf_size/test.sh +tools/check_python_dependencies.py +docs/gen-dxd.py diff --git a/tools/gen_esp_err_to_name.py b/tools/gen_esp_err_to_name.py index b37054152..d623815ec 100755 --- a/tools/gen_esp_err_to_name.py +++ b/tools/gen_esp_err_to_name.py @@ -16,9 +16,20 @@ from __future__ import print_function from __future__ import unicode_literals -from builtins import str -from builtins import range -from builtins import object +import sys +try: + from builtins import str + from builtins import range + from builtins import object +except ImportError: + # This should not happen because the Python packages are checked before invoking this script. However, here is + # some output which should help if we missed something. + print('Import has failed probably because of the missing "future" package. Please install all the packages for ' + 'interpreter {} from the requirements.txt file.'.format(sys.executable)) + # The path to requirements.txt is not provided because this script could be invoked from an IDF project (then the + # requirements.txt from the IDF_PATH should be used) or from the documentation project (then the requirements.txt + # for the documentation directory should be used). + sys.exit(1) from io import open import os import argparse diff --git a/tools/idf_monitor.py b/tools/idf_monitor.py index 79aef4092..f09e934a8 100755 --- a/tools/idf_monitor.py +++ b/tools/idf_monitor.py @@ -739,8 +739,10 @@ if os.name == 'nt': pass def write(self, data): - if type(data) is not bytes: - data = data.encode('latin-1') + if isinstance(data, bytes): + data = bytearray(data) + else: + data = bytearray(data, 'utf-8') for b in data: b = bytes([b]) l = len(self.matched) diff --git a/tools/kconfig/Makefile b/tools/kconfig/Makefile index c8f8ba014..cd0064043 100644 --- a/tools/kconfig/Makefile +++ b/tools/kconfig/Makefile @@ -165,7 +165,7 @@ check-lxdialog := $(SRCDIR)/lxdialog/check-lxdialog.sh # Use recursively expanded variables so we do not call gcc unless # we really need to do so. (Do not call gcc as part of make mrproper) CFLAGS += $(shell $(CONFIG_SHELL) $(check-lxdialog) -ccflags) \ - -DLOCALE -MD + -DLOCALE -MMD %.o: $(SRCDIR)/%.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@