ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
hal.cpp
Go to the documentation of this file.
1#ifdef USE_ZEPHYR
2
4#include "esphome/core/hal.h"
5
6#include <zephyr/drivers/watchdog.h>
7#include <zephyr/sys/reboot.h>
8
9#ifdef USE_ZEPHYR_DWT_MICROS
10#include <cmsis_core.h>
11#endif
12
13// Empty zephyr namespace block to satisfy ci-custom's lint_namespace check.
14// HAL functions live in namespace esphome (root) — they are not part of the
15// zephyr component's API.
16namespace esphome::zephyr {} // namespace esphome::zephyr
17
18namespace esphome {
19
20#ifdef CONFIG_WATCHDOG
21static int wdt_channel_id = -1; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
22static const device *const WDT = DEVICE_DT_GET(DT_ALIAS(watchdog0));
23#endif
24
25// yield(), delay(), millis(), millis_64(), delayMicroseconds(), micros() except the cycle-counter one,
26// arch_get_cpu_cycle_count(), arch_get_cpu_freq_hz() inlined in
27// components/zephyr/hal.h.
28
29#ifdef USE_ZEPHYR_DWT_MICROS
30// The kernel clock counts in ticks of about 30 us, and the CPU cycle counter stops while the CPU sleeps.
31// micros() adds the cycles counted since the last call. While the CPU stays busy the result and the kernel clock
32// each trail the true time by less than a tick, so they differ by less than a tick either way. A sleep shorter
33// than a tick can go unnoticed, so the result may trail the true time by up to two ticks until the next resync.
34// The CPU cannot sleep while interrupts are locked, so a lag there comes from before the lock. It and any drift
35// are left for the next unlocked call, which keeps differences inside an InterruptLock exact; InterruptLock makes that
36// call just before it locks, so timestamps taken under the lock line up with later unlocked ones. A counter that has
37// not moved since the last call is not running, and then the kernel clock is used even under a lock.
38
39// One struct so the code loads a single base address.
40static struct {
42 uint32_t last_cycles; // Moves on by whole microseconds only, so the remainder carries over.
43} micros_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
44
45static constexpr uint32_t CYCLES_PER_US = 64; // nRF52 cores always run at 64 MHz.
46// Drift between unlocked calls stays far below this; a larger lead is a lag of over 2^31 us that wrapped. A lag
47// within this of 2^32 us still looks like a lead and holds micros() for at most a second; that is accepted.
48static constexpr int32_t MAX_LEAD_US = 1000000;
49
51 const unsigned int key = irq_lock();
52 const uint32_t cycles = DWT->CYCCNT;
53 const uint32_t elapsed_us = (cycles - micros_state.last_cycles) / CYCLES_PER_US;
54 micros_state.last_cycles += elapsed_us * CYCLES_PER_US;
55 uint32_t value = micros_state.value + elapsed_us;
56
57 const uint32_t kernel_us = k_ticks_to_us_floor32(k_uptime_ticks());
58 // A tick, plus 1 us because kernel_us is rounded down.
59 const int32_t tick_us = k_ticks_to_us_ceil32(1) + 1;
60 const int32_t ahead = static_cast<int32_t>(value - kernel_us);
61 const bool unlocked = arch_irq_unlocked(key);
62 if ((ahead < -tick_us || ahead > MAX_LEAD_US) && (unlocked || elapsed_us == 0)) {
63 // The CPU slept, so the cycle counter fell behind.
64 value = kernel_us;
65 micros_state.last_cycles = cycles;
66 } else if (ahead >= tick_us && ahead <= MAX_LEAD_US && unlocked) {
67 // The CPU clock can run fast against the RTC; cap the drift at one tick, but never below a result already
68 // returned under a lock.
69 const uint32_t cap = kernel_us + tick_us - 1;
70 value = static_cast<int32_t>(cap - micros_state.value) > 0 ? cap : micros_state.value;
71 }
72 micros_state.value = value;
73 irq_unlock(key);
74 return value;
75}
76#endif
77
78void arch_init() {
79 main_loop_thread() = k_current_get();
80#ifdef USE_ZEPHYR_DWT_MICROS
81 CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
82 DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
83#endif
84#ifdef CONFIG_WATCHDOG
85 if (device_is_ready(WDT)) {
86 static wdt_timeout_cfg wdt_config{};
87 wdt_config.flags = WDT_FLAG_RESET_SOC;
88#ifndef USE_BOOTLOADER_MCUBOOT
89 // Adafruit bootloader doesn't feed the WDT while
90 // erasing flash during a firmware update, so a shorter timeout can break the update.
91 wdt_config.window.max = 30000;
92#elif defined(USE_ZIGBEE)
93 // zboss thread uses a lot of CPU cycles during startup
94 wdt_config.window.max = 10000;
95#else
96 wdt_config.window.max = 2000;
97#endif
98 wdt_channel_id = wdt_install_timeout(WDT, &wdt_config);
99 if (wdt_channel_id >= 0) {
100 uint8_t options = 0;
101#ifdef USE_DEBUG
102 options |= WDT_OPT_PAUSE_HALTED_BY_DBG;
103#endif
104#ifdef USE_DEEP_SLEEP
105 options |= WDT_OPT_PAUSE_IN_SLEEP;
106#endif
107 wdt_setup(WDT, options);
108 }
109 }
110#endif
111 // feed watchdog early. Otherwise OTA may rollback.
113}
114
116#ifdef CONFIG_WATCHDOG
117 if (wdt_channel_id >= 0) {
118 wdt_feed(WDT, wdt_channel_id);
119 }
120#endif
121}
122
123void arch_restart() { sys_reboot(SYS_REBOOT_COLD); }
124
125} // namespace esphome
126
127#endif // USE_ZEPHYR
uint8_t options
const char * key
void arch_init()
Definition hal.cpp:44
uint32_t last_cycles
Definition hal.cpp:42
uint32_t value
Definition hal.cpp:41
pthread_t & main_loop_thread()
Definition hal.h:20
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
void arch_feed_wdt()
Definition hal.cpp:115
void arch_restart()
Definition hal.cpp:36
static void uint32_t