ESPHome 2025.7.4
Loading...
Searching...
No Matches
helpers.cpp
Go to the documentation of this file.
2
3#ifdef USE_HOST
4
5#ifndef _WIN32
6#include <net/if.h>
7#include <netinet/in.h>
8#include <sys/ioctl.h>
9#endif
10#include <unistd.h>
11#include <limits>
12#include <random>
13
15#include "esphome/core/log.h"
16
17namespace esphome {
18
19static const char *const TAG = "helpers.host";
20
22 std::random_device dev;
23 std::mt19937 rng(dev());
24 std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max());
25 return dist(rng);
26}
27
28bool random_bytes(uint8_t *data, size_t len) {
29 FILE *fp = fopen("/dev/urandom", "r");
30 if (fp == nullptr) {
31 ESP_LOGW(TAG, "Could not open /dev/urandom, errno=%d", errno);
32 exit(1);
33 }
34 size_t read = fread(data, 1, len, fp);
35 if (read != len) {
36 ESP_LOGW(TAG, "Not enough data from /dev/urandom");
37 exit(1);
38 }
39 fclose(fp);
40 return true;
41}
42
43// Host platform uses std::mutex for proper thread synchronization
44Mutex::Mutex() { handle_ = new std::mutex(); }
45Mutex::~Mutex() { delete static_cast<std::mutex *>(handle_); }
46void Mutex::lock() { static_cast<std::mutex *>(handle_)->lock(); }
47bool Mutex::try_lock() { return static_cast<std::mutex *>(handle_)->try_lock(); }
48void Mutex::unlock() { static_cast<std::mutex *>(handle_)->unlock(); }
49
50void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
51 static const uint8_t esphome_host_mac_address[6] = USE_ESPHOME_HOST_MAC_ADDRESS;
52 memcpy(mac, esphome_host_mac_address, sizeof(esphome_host_mac_address));
53}
54
55} // namespace esphome
56
57#endif // USE_HOST
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:232
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