ESPHome 2026.3.0
Loading...
Searching...
No Matches
helpers.cpp
Go to the documentation of this file.
3
4#ifdef USE_RP2040
5
6#include "esphome/core/hal.h"
7
8#if defined(USE_WIFI)
9#include <WiFi.h>
10#include <pico/cyw43_arch.h> // For cyw43_arch_lwip_begin/end (LwIPLock)
11#endif
12#include <hardware/structs/rosc.h>
13#include <hardware/sync.h>
14
15namespace esphome {
16
18 uint32_t result = 0;
19 for (uint8_t i = 0; i < 32; i++) {
20 result <<= 1;
21 result |= rosc_hw->randombit;
22 }
23 return result;
24}
25
26bool random_bytes(uint8_t *data, size_t len) {
27 while (len-- != 0) {
28 uint8_t result = 0;
29 for (uint8_t i = 0; i < 8; i++) {
30 result <<= 1;
31 result |= rosc_hw->randombit;
32 }
33 *data++ = result;
34 }
35 return true;
36}
37
38// RP2040 doesn't have mutexes, but that shouldn't be an issue as it's single-core and non-preemptive OS.
39Mutex::Mutex() {}
41void Mutex::lock() {}
42bool Mutex::try_lock() { return true; }
43void Mutex::unlock() {}
44
45IRAM_ATTR InterruptLock::InterruptLock() { state_ = save_and_disable_interrupts(); }
46IRAM_ATTR InterruptLock::~InterruptLock() { restore_interrupts(state_); }
47
48// On RP2040 (Pico W), arduino-pico sets PICO_CYW43_ARCH_THREADSAFE_BACKGROUND=1.
49// This means lwip callbacks run from a low-priority user IRQ context, not the
50// main loop (see low_priority_irq_handler() in pico-sdk
51// async_context_threadsafe_background.c). cyw43_arch_lwip_begin/end acquires the
52// async_context recursive mutex to prevent IRQ callbacks from firing during
53// critical sections. See esphome#10681.
54//
55// When CYW43 is not available (non-WiFi RP2040 boards), this is a no-op since
56// there's no network stack and no lwip callbacks to race with.
57#if defined(USE_WIFI)
58LwIPLock::LwIPLock() { cyw43_arch_lwip_begin(); }
59LwIPLock::~LwIPLock() { cyw43_arch_lwip_end(); }
60#else
63#endif
64
65void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
66#ifdef USE_WIFI
67 WiFi.macAddress(mac);
68#endif
69}
70
71} // namespace esphome
72
73#endif // USE_RP2040
void unlock()
Definition helpers.cpp:27
bool try_lock()
Definition helpers.cpp:26
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
bool random_bytes(uint8_t *data, size_t len)
Generate len number of random bytes.
Definition helpers.cpp:18
std::string size_t len
Definition helpers.h:892
uint32_t random_uint32()
Return a random 32-bit unsigned integer.
Definition helpers.cpp:17
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:73
static void uint32_t