// Host build: esp_timer (the linux target ships only its header). One FreeRTOS task per timer. #include #include #include #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" struct esp_timer { esp_timer_cb_t cb; void *arg; volatile int64_t due_us; // 0 = stopped volatile int64_t period_us; SemaphoreHandle_t wake; }; int64_t esp_timer_get_time(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000; } static void timer_task(void *arg) { struct esp_timer *t = arg; for (;;) { int64_t due = t->due_us; if (!due) { xSemaphoreTake(t->wake, portMAX_DELAY); continue; } int64_t wait = due - esp_timer_get_time(); if (wait > 0) { TickType_t ticks = (TickType_t)((wait + 999) / 1000 / portTICK_PERIOD_MS); if (xSemaphoreTake(t->wake, ticks ? ticks : 1) == pdTRUE) { continue; // restarted or stopped: look again } if (t->due_us != due || esp_timer_get_time() < due) { continue; } } t->due_us = t->period_us ? due + t->period_us : 0; t->cb(t->arg); } } esp_err_t esp_timer_create(const esp_timer_create_args_t *args, esp_timer_handle_t *out) { struct esp_timer *t = calloc(1, sizeof(*t)); if (!t) { return ESP_ERR_NO_MEM; } t->cb = args->callback; t->arg = args->arg; t->wake = xSemaphoreCreateBinary(); xTaskCreate(timer_task, args->name ? args->name : "esp_timer", 16384, t, 22, NULL); *out = t; return ESP_OK; } static esp_err_t arm(esp_timer_handle_t t, uint64_t us, uint64_t period) { t->period_us = period; t->due_us = esp_timer_get_time() + (int64_t)us; if (!t->due_us) { t->due_us = 1; } xSemaphoreGive(t->wake); return ESP_OK; } esp_err_t esp_timer_start_once(esp_timer_handle_t t, uint64_t timeout_us) { return arm(t, timeout_us, 0); } esp_err_t esp_timer_start_periodic(esp_timer_handle_t t, uint64_t period) { return arm(t, period, period); } esp_err_t esp_timer_stop(esp_timer_handle_t t) { bool was = t->due_us != 0; t->due_us = 0; xSemaphoreGive(t->wake); return was ? ESP_OK : ESP_ERR_INVALID_STATE; } bool esp_timer_is_active(esp_timer_handle_t t) { return t->due_us != 0; }