ESPHome 2026.9.1
Loading...
Searching...
No Matches
hal.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
4#include "esphome/core/hal.h"
5
6#include <esp_clk_tree.h>
7#include <esp_ota_ops.h>
8#include <esp_system.h>
9#include <esp_task_wdt.h>
10#include <esp_timer.h>
11#include <freertos/FreeRTOS.h>
12#include <freertos/task.h>
13
14// Empty esp32 namespace block to satisfy ci-custom's lint_namespace check.
15// HAL functions live in namespace esphome (root) — they are not part of the
16// esp32 component's API.
17namespace esphome::esp32 {} // namespace esphome::esp32
18
19namespace esphome {
20
21// Use xTaskGetTickCount() when tick rate is 1 kHz (ESPHome's default via sdkconfig),
22// falling back to esp_timer for non-standard rates. IRAM_ATTR is required because
23// Wiegand and ZyAura call millis() from IRAM_ATTR ISR handlers on ESP32.
24// xTaskGetTickCountFromISR() is used in ISR context to satisfy the FreeRTOS API contract.
25uint32_t IRAM_ATTR HOT millis() {
26#if CONFIG_FREERTOS_HZ == 1000
27 if (xPortInIsrContext()) [[unlikely]] {
28 return xTaskGetTickCountFromISR();
29 }
30 return xTaskGetTickCount();
31#else
32 return micros_to_millis(static_cast<uint64_t>(esp_timer_get_time()));
33#endif
34}
35
37 esp_restart();
38 // restart() doesn't always end execution
39 while (true) { // NOLINT(clang-diagnostic-unreachable-code)
40 yield();
41 }
42}
43
44void arch_init() {
45 // Enable the task watchdog only on the loop task (from which we're currently running)
46 esp_task_wdt_add(nullptr);
47
48 // Handle OTA rollback: mark partition valid immediately unless USE_OTA_ROLLBACK is enabled,
49 // in which case safe_mode will mark it valid after confirming successful boot.
50#ifndef USE_OTA_ROLLBACK
51 esp_ota_mark_app_valid_cancel_rollback();
52#endif
53}
54
56 uint32_t freq = 0;
57 esp_clk_tree_src_get_freq_hz(SOC_MOD_CLK_CPU, ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED, &freq);
58 return freq;
59}
60
61} // namespace esphome
62
63#endif // USE_ESP32
void yield(void)
void arch_init()
Definition hal.cpp:44
uint32_t arch_get_cpu_freq_hz()
Definition hal.cpp:55
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
void arch_restart()
Definition hal.cpp:36
int64_t esp_timer_get_time(void)
static void uint32_t