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