From 2be5e88549f3ee1e3466e88702860fb5b78349f2 Mon Sep 17 00:00:00 2001 From: Xu Si Yu Date: Wed, 21 May 2025 19:30:19 +0800 Subject: [PATCH] feat(openthread): add a function to exit openthread main loop safely --- components/openthread/include/esp_openthread.h | 11 ++++++++++- components/openthread/src/esp_openthread.cpp | 15 ++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/components/openthread/include/esp_openthread.h b/components/openthread/include/esp_openthread.h index 9e5f39a59b..a3f0528f93 100644 --- a/components/openthread/include/esp_openthread.h +++ b/components/openthread/include/esp_openthread.h @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2021-2025 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -79,6 +79,15 @@ esp_err_t esp_openthread_deinit(void); */ otInstance *esp_openthread_get_instance(void); +/** + * @brief Signals the OpenThread main loop to exit. + * + * @return + * - ESP_OK on success + * - ESP_FAIL on failures + * + */ +esp_err_t esp_openthread_mainloop_exit(void); #ifdef __cplusplus } // end of extern "C" diff --git a/components/openthread/src/esp_openthread.cpp b/components/openthread/src/esp_openthread.cpp index 73018e2d3f..d816cd121d 100644 --- a/components/openthread/src/esp_openthread.cpp +++ b/components/openthread/src/esp_openthread.cpp @@ -26,6 +26,8 @@ #include "openthread/dataset_ftd.h" #endif +static bool s_ot_mainloop_running = false; + static int hex_digit_to_int(char hex) { if ('A' <= hex && hex <= 'F') { @@ -158,13 +160,24 @@ esp_err_t esp_openthread_auto_start(otOperationalDatasetTlvs *datasetTlvs) return ESP_OK; } +static void mainloop_safe_exit(void *ctx) +{ + s_ot_mainloop_running = false; +} + +esp_err_t esp_openthread_mainloop_exit(void) +{ + return esp_openthread_task_queue_post(mainloop_safe_exit, NULL); +} + esp_err_t esp_openthread_launch_mainloop(void) { esp_openthread_mainloop_context_t mainloop; otInstance *instance = esp_openthread_get_instance(); esp_err_t error = ESP_OK; + s_ot_mainloop_running = true; - while (true) { + while (s_ot_mainloop_running) { FD_ZERO(&mainloop.read_fds); FD_ZERO(&mainloop.write_fds); FD_ZERO(&mainloop.error_fds);