DeterministicESPAsyncWebServer v6.27.1
Zero-allocation, bounded-execution async HTTP server for ESP32
Loading...
Searching...
No Matches
device_id.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file device_id.cpp
6 * @brief Stable MAC-derived device UUID - implementation. See device_id.h.
7 */
8
9#include "device_id.h"
11
12#if DETWS_ENABLE_DEVICE_ID
13
15
16#ifdef ARDUINO
17#include <esp_mac.h> // esp_read_mac()
18#endif
19
20namespace
21{
22// RFC 4122 DNS namespace UUID (6ba7b810-9dad-11d1-80b4-00c04fd430c8).
23const uint8_t NS_DNS[16] = {0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1,
24 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8};
25} // namespace
26
27void detws_uuid_from_mac(const uint8_t mac[6], char out[DETWS_UUID_STR_LEN])
28{
29 // UUIDv5 name = lowercase MAC hex (12 chars, no separators).
30 uint8_t input[16 + 12];
31 for (int i = 0; i < 16; i++)
32 input[i] = NS_DNS[i];
33 for (int i = 0; i < 6; i++)
34 {
35 input[16 + i * 2] = (uint8_t)det_hex_digit((uint8_t)(mac[i] >> 4));
36 input[16 + i * 2 + 1] = (uint8_t)det_hex_digit((uint8_t)(mac[i] & 0x0F));
37 }
38
39 uint8_t h[SHA1_DIGEST_LEN];
40 sha1(input, sizeof(input), h);
41 h[6] = (uint8_t)((h[6] & 0x0F) | 0x50); // version 5
42 h[8] = (uint8_t)((h[8] & 0x3F) | 0x80); // RFC 4122 variant
43
44 // Format as 8-4-4-4-12 (16 bytes -> 32 hex + 4 dashes).
45 static const int groups[5] = {4, 2, 2, 2, 6};
46 int hi = 0;
47 int oi = 0;
48 for (int g = 0; g < 5; g++)
49 {
50 if (g)
51 out[oi++] = '-';
52 for (int b = 0; b < groups[g]; b++)
53 {
54 out[oi++] = det_hex_digit((uint8_t)(h[hi] >> 4));
55 out[oi++] = det_hex_digit((uint8_t)(h[hi] & 0x0F));
56 hi++;
57 }
58 }
59 out[oi] = '\0';
60}
61
62#ifdef ARDUINO
63void detws_device_uuid(char out[DETWS_UUID_STR_LEN])
64{
65 uint8_t mac[6] = {0};
66 esp_read_mac(mac, ESP_MAC_WIFI_STA); // stable factory MAC
67 detws_uuid_from_mac(mac, out);
68}
69#endif
70
71#endif // DETWS_ENABLE_DEVICE_ID
Stable device UUID derived from the chip MAC (DETWS_ENABLE_DEVICE_ID).
Tiny no-stdlib hex encode / decode / nibble helpers (one shared copy).
char det_hex_digit(int nibble, bool upper=false)
Nibble 0..15 -> hex char (lowercase, or uppercase when upper).
Definition hex.h:24
void sha1(const uint8_t *data, size_t len, uint8_t digest[SHA1_DIGEST_LEN])
Compute a SHA-1 digest over an arbitrary byte buffer.
Definition sha1.cpp:24
Software SHA-1 implementation - no platform dependencies.
#define SHA1_DIGEST_LEN
SHA-1 digest length in bytes.
Definition sha1.h:22