🪄 Formats StatefulService

This commit is contained in:
Rune Harlyk
2024-07-09 20:01:11 +02:00
committed by Rune Harlyk
parent ba41f520b0
commit 227cbd536f
2 changed files with 36 additions and 46 deletions
+14 -23
View File
@@ -14,54 +14,45 @@
#include <SettingValue.h> #include <SettingValue.h>
namespace SettingValue namespace SettingValue {
{ const String PLATFORM = "esp32";
const String PLATFORM = "esp32";
/** /**
* Returns a new string after replacing each instance of the pattern with a value generated by calling the provided * Returns a new string after replacing each instance of the pattern with a value generated by calling the provided
* callback. * callback.
*/ */
String replaceEach(String value, String pattern, String (*generateReplacement)()) String replaceEach(String value, String pattern, String (*generateReplacement)()) {
{ while (true) {
while (true)
{
int index = value.indexOf(pattern); int index = value.indexOf(pattern);
if (index == -1) if (index == -1) {
{
break; break;
} }
value = value.substring(0, index) + generateReplacement() + value.substring(index + pattern.length()); value = value.substring(0, index) + generateReplacement() + value.substring(index + pattern.length());
} }
return value; return value;
} }
/** /**
* Generates a random number, encoded as a hex string. * Generates a random number, encoded as a hex string.
*/ */
String getRandom() String getRandom() { return String(random(2147483647), HEX); }
{
return String(random(2147483647), HEX);
}
/** /**
* Uses the station's MAC address to create a unique id for each device. * Uses the station's MAC address to create a unique id for each device.
*/ */
String getUniqueId() String getUniqueId() {
{
uint8_t mac[6]; uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA); esp_read_mac(mac, ESP_MAC_WIFI_STA);
char macStr[13] = {0}; char macStr[13] = {0};
sprintf(macStr, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); sprintf(macStr, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return String(macStr); return String(macStr);
} }
String format(String value) String format(String value) {
{
value = replaceEach(value, "#{random}", getRandom); value = replaceEach(value, "#{random}", getRandom);
value.replace("#{unique_id}", getUniqueId()); value.replace("#{unique_id}", getUniqueId());
value.replace("#{platform}", PLATFORM); value.replace("#{platform}", PLATFORM);
return value; return value;
} }
}; // end namespace SettingValue }; // end namespace SettingValue
+2 -3
View File
@@ -17,9 +17,8 @@
#include <Arduino.h> #include <Arduino.h>
namespace SettingValue namespace SettingValue {
{ String format(String value);
String format(String value);
}; };
#endif // end SettingValue #endif // end SettingValue