-
Notifications
You must be signed in to change notification settings - Fork 148
/
SettingValue.cpp
55 lines (48 loc) · 1.33 KB
/
SettingValue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <SettingValue.h>
namespace SettingValue {
#ifdef ESP32
const String PLATFORM = "esp32";
#elif defined(ESP8266)
const String PLATFORM = "esp8266";
#endif
/**
* Returns a new string after replacing each instance of the pattern with a value generated by calling the provided
* callback.
*/
String replaceEach(String value, String pattern, String (*generateReplacement)()) {
while (true) {
int index = value.indexOf(pattern);
if (index == -1) {
break;
}
value = value.substring(0, index) + generateReplacement() + value.substring(index + pattern.length());
}
return value;
}
/**
* Generates a random number, encoded as a hex string.
*/
String getRandom() {
return String(random(2147483647), HEX);
}
/**
* Uses the station's MAC address to create a unique id for each device.
*/
String getUniqueId() {
uint8_t mac[6];
#ifdef ESP32
esp_read_mac(mac, ESP_MAC_WIFI_STA);
#elif defined(ESP8266)
wifi_get_macaddr(STATION_IF, mac);
#endif
char macStr[13] = {0};
sprintf(macStr, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr);
}
String format(String value) {
value = replaceEach(value, "#{random}", getRandom);
value.replace("#{unique_id}", getUniqueId());
value.replace("#{platform}", PLATFORM);
return value;
}
}; // end namespace SettingValue