diff --git a/components/esp_libc/CMakeLists.txt b/components/esp_libc/CMakeLists.txt index 479347b6f71..84920715ad7 100644 --- a/components/esp_libc/CMakeLists.txt +++ b/components/esp_libc/CMakeLists.txt @@ -26,6 +26,7 @@ set(srcs "src/termios.c" "src/stdatomic.c" "src/time.c" + "src/timespec_get.c" "src/timekeeping.c" "src/sysconf.c" "src/realpath.c" diff --git a/components/esp_libc/platform_include/time.h b/components/esp_libc/platform_include/time.h index b79b5f36ff5..c7e2398c126 100644 --- a/components/esp_libc/platform_include/time.h +++ b/components/esp_libc/platform_include/time.h @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD + * SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ @@ -22,6 +22,10 @@ extern "C" { #define CLOCK_BOOTTIME (clockid_t)4 #endif +#ifndef TIME_UTC +#define TIME_UTC 1 +#endif + int clock_settime(clockid_t clock_id, const struct timespec *tp); int clock_gettime(clockid_t clock_id, struct timespec *tp); int clock_getres(clockid_t clock_id, struct timespec *res); diff --git a/components/esp_libc/src/timespec_get.c b/components/esp_libc/src/timespec_get.c new file mode 100644 index 00000000000..81d3d5c5abc --- /dev/null +++ b/components/esp_libc/src/timespec_get.c @@ -0,0 +1,15 @@ +/* + * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include + +int timespec_get(struct timespec *ts, int base) +{ + if (base != TIME_UTC || clock_gettime(CLOCK_REALTIME, ts) < 0) { + return 0; + } + return base; +} diff --git a/components/esp_libc/test_apps/newlib/main/test_time.c b/components/esp_libc/test_apps/newlib/main/test_time.c index 1a4d5d21a38..5051ed2a6ef 100644 --- a/components/esp_libc/test_apps/newlib/main/test_time.c +++ b/components/esp_libc/test_apps/newlib/main/test_time.c @@ -548,6 +548,17 @@ TEST_CASE("test posix_timers clock_... functions", "[newlib]") test_posix_timers_clock(); } +TEST_CASE("timespec_get returns UTC time", "[newlib]") +{ + struct timespec ts = {0}; + + TEST_ASSERT_EQUAL_INT(TIME_UTC, timespec_get(&ts, TIME_UTC)); + TEST_ASSERT_GREATER_OR_EQUAL_INT64(0, ts.tv_sec); + TEST_ASSERT_GREATER_OR_EQUAL_INT32(0, ts.tv_nsec); + TEST_ASSERT_LESS_THAN_INT32(1000000000L, ts.tv_nsec); + TEST_ASSERT_EQUAL_INT(0, timespec_get(&ts, -1)); +} + #define TEST_USE_CPU_CYCLES 1 #if TEST_USE_CPU_CYCLES && CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE #include "esp_cpu.h"