ESPHome 2026.5.0b1
Loading...
Searching...
No Matches
hal.cpp
Go to the documentation of this file.
1#ifdef USE_HOST
2
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6#include "core.h"
7
8#include <time.h>
9#include <unistd.h>
10#include <cerrno>
11#include <cstdlib>
12#include <cstring>
13
14// Empty host 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// host component's API.
17namespace esphome::host {} // namespace esphome::host
18
19namespace esphome {
20
21// yield(), arch_init(), arch_feed_wdt(), arch_get_cpu_freq_hz() inlined in
22// components/host/hal.h.
23
24uint32_t IRAM_ATTR HOT millis() {
25 struct timespec spec;
26 clock_gettime(CLOCK_MONOTONIC, &spec);
27 return static_cast<uint32_t>(spec.tv_sec * 1000ULL + spec.tv_nsec / 1000000);
28}
29uint64_t millis_64() {
30 struct timespec spec;
31 clock_gettime(CLOCK_MONOTONIC, &spec);
32 return static_cast<uint64_t>(spec.tv_sec) * 1000ULL + static_cast<uint64_t>(spec.tv_nsec) / 1000000ULL;
33}
34void HOT delay(uint32_t ms) {
35 struct timespec ts;
36 ts.tv_sec = ms / 1000;
37 ts.tv_nsec = (ms % 1000) * 1000000;
38 int res;
39 do {
40 res = nanosleep(&ts, &ts);
41 } while (res != 0 && errno == EINTR);
42}
43uint32_t IRAM_ATTR HOT micros() {
44 struct timespec spec;
45 clock_gettime(CLOCK_MONOTONIC, &spec);
46 return static_cast<uint32_t>(spec.tv_sec * 1000000ULL + spec.tv_nsec / 1000);
47}
48void IRAM_ATTR HOT delayMicroseconds(uint32_t us) {
49 struct timespec ts;
50 ts.tv_sec = us / 1000000U;
51 ts.tv_nsec = (us % 1000000U) * 1000U;
52 int res;
53 do {
54 res = nanosleep(&ts, &ts);
55 } while (res != 0 && errno == EINTR);
56}
57void arch_restart() {
58 // Host OTA: if a re-exec is armed, swap binaries instead of exiting.
59 if (const char *target = host::get_reexec_path()) {
60 char **argv = host::get_argv();
61 if (argv != nullptr) {
62 execv(target, argv);
63 // execv only returns on failure.
64 ESP_LOGE("host", "execv('%s') failed: %s", target, std::strerror(errno));
65 exit(1);
66 }
67 }
68 exit(0);
69}
70
72 struct timespec spec;
73 clock_gettime(CLOCK_MONOTONIC, &spec);
74 time_t seconds = spec.tv_sec;
75 uint32_t ns = static_cast<uint32_t>(spec.tv_nsec);
76 return static_cast<uint32_t>(seconds) * 1000000000U + ns;
77}
78
79} // namespace esphome
80
81#endif // USE_HOST
const char * get_reexec_path()
Armed re-exec path, or nullptr.
Definition core.cpp:71
char ** get_argv()
argv captured by main(); stable for process lifetime.
Definition core.cpp:59
uint32_t arch_get_cpu_cycle_count()
Definition hal.cpp:71
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
uint64_t millis_64()
Definition hal.cpp:29
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
void HOT delay(uint32_t ms)
Definition hal.cpp:82
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
void arch_restart()
Definition hal.cpp:39
static void uint32_t