Skip to content

Commit 0e21240

Browse files
authored
Use references & flash strings where approperate (#110)
* pass originId as const reference * store strings for serial logging in flash * Use string references where approperate.
1 parent 4e6823c commit 0e21240

16 files changed

+85
-90
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ You may listen for changes to state by registering an update handler callback. I
365365
```cpp
366366
// register an update handler
367367
update_handler_id_t myUpdateHandler = lightStateService.addUpdateHandler(
368-
[&](String originId) {
368+
[&](const String& originId) {
369369
Serial.println("The light's state has been updated");
370370
}
371371
);
@@ -588,7 +588,7 @@ Observe changes to the WiFiSettings:
588588

589589
```cpp
590590
esp8266React.getWiFiSettingsService()->addUpdateHandler(
591-
[&](String originId) {
591+
[&](const String& originId) {
592592
Serial.println("The WiFi Settings were updated!");
593593
}
594594
);

lib/framework/APSettingsService.cpp

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ APSettingsService::APSettingsService(AsyncWebServer* server, FS* fs, SecurityMan
88
AP_SETTINGS_SERVICE_PATH,
99
securityManager),
1010
_fsPersistence(APSettings::serialize, APSettings::deserialize, this, fs, AP_SETTINGS_FILE),
11-
_lastManaged(0),
1211
_dnsServer(nullptr) {
13-
addUpdateHandler([&](String originId) { reconfigureAP(); }, false);
12+
addUpdateHandler([&](const String& originId) { reconfigureAP(); }, false);
1413
}
1514

1615
void APSettingsService::begin() {
@@ -47,11 +46,11 @@ void APSettingsService::manageAP() {
4746
}
4847

4948
void APSettingsService::startAP() {
50-
Serial.println("Starting software access point");
49+
Serial.println(F("Starting software access point"));
5150
WiFi.softAP(_state.ssid.c_str(), _state.password.c_str());
5251
if (!_dnsServer) {
5352
IPAddress apIp = WiFi.softAPIP();
54-
Serial.print("Starting captive portal on ");
53+
Serial.print(F("Starting captive portal on "));
5554
Serial.println(apIp);
5655
_dnsServer = new DNSServer;
5756
_dnsServer->start(DNS_PORT, "*", apIp);
@@ -60,12 +59,12 @@ void APSettingsService::startAP() {
6059

6160
void APSettingsService::stopAP() {
6261
if (_dnsServer) {
63-
Serial.println("Stopping captive portal");
62+
Serial.println(F("Stopping captive portal"));
6463
_dnsServer->stop();
6564
delete _dnsServer;
6665
_dnsServer = nullptr;
6766
}
68-
Serial.println("Stopping software access point");
67+
Serial.println(F("Stopping software access point"));
6968
WiFi.softAPdisconnect(true);
7069
}
7170

lib/framework/FSPersistence.h

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ class FSPersistence {
3232
DynamicJsonDocument jsonDocument = DynamicJsonDocument(MAX_FILE_SIZE);
3333
DeserializationError error = deserializeJson(jsonDocument, settingsFile);
3434
if (error == DeserializationError::Ok && jsonDocument.is<JsonObject>()) {
35-
updateSettings(jsonDocument.as<JsonObject>());
35+
JsonObject jsonObject = jsonDocument.as<JsonObject>();
36+
_statefulService->updateWithoutPropagation(jsonObject, _jsonDeserializer);
3637
settingsFile.close();
3738
return;
3839
}
@@ -74,7 +75,7 @@ class FSPersistence {
7475

7576
void enableUpdateHandler() {
7677
if (!_updateHandlerId) {
77-
_updateHandlerId = _statefulService->addUpdateHandler([&](String originId) { writeToFS(); });
78+
_updateHandlerId = _statefulService->addUpdateHandler([&](const String& originId) { writeToFS(); });
7879
}
7980
}
8081

@@ -86,17 +87,13 @@ class FSPersistence {
8687
char const* _filePath;
8788
update_handler_id_t _updateHandlerId = 0;
8889

89-
// update the settings, but do not call propogate
90-
void updateSettings(JsonObject root) {
91-
_statefulService->updateWithoutPropagation(root, _jsonDeserializer);
92-
}
93-
9490
protected:
9591
// We assume the deserializer supplies sensible defaults if an empty object
9692
// is supplied, this virtual function allows that to be changed.
9793
virtual void applyDefaults() {
9894
DynamicJsonDocument jsonDocument = DynamicJsonDocument(MAX_FILE_SIZE);
99-
updateSettings(jsonDocument.to<JsonObject>());
95+
JsonObject jsonObject = jsonDocument.as<JsonObject>();
96+
_statefulService->updateWithoutPropagation(jsonObject, _jsonDeserializer);
10097
}
10198
};
10299

lib/framework/JsonUtils.h

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@
77

88
class JsonUtils {
99
public:
10-
static void readIP(JsonObject& root, String key, IPAddress& _ip) {
11-
if (!root[key].is<String>() || !_ip.fromString(root[key].as<String>())) {
12-
_ip = INADDR_NONE;
10+
static void readIP(JsonObject& root, const String& key, IPAddress& ip) {
11+
if (!root[key].is<String>() || !ip.fromString(root[key].as<String>())) {
12+
ip = INADDR_NONE;
1313
}
1414
}
15-
static void writeIP(JsonObject& root, String key, IPAddress& _ip) {
16-
if (_ip != INADDR_NONE) {
17-
root[key] = _ip.toString();
15+
static void writeIP(JsonObject& root, const String& key, const IPAddress& ip) {
16+
if (ip != INADDR_NONE) {
17+
root[key] = ip.toString();
1818
}
1919
}
2020
};

lib/framework/MqttPubSub.h

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ class MqttPub : virtual public MqttConnector<T> {
3434
MqttPub(JsonSerializer<T> jsonSerializer,
3535
StatefulService<T>* statefulService,
3636
AsyncMqttClient* mqttClient,
37-
String pubTopic = "") :
37+
const String& pubTopic = "") :
3838
MqttConnector<T>(statefulService, mqttClient), _jsonSerializer(jsonSerializer), _pubTopic(pubTopic) {
39-
MqttConnector<T>::_statefulService->addUpdateHandler([&](String originId) { publish(); }, false);
39+
MqttConnector<T>::_statefulService->addUpdateHandler([&](const String& originId) { publish(); }, false);
4040
}
4141

42-
void setPubTopic(String pubTopic) {
42+
void setPubTopic(const String& pubTopic) {
4343
_pubTopic = pubTopic;
4444
publish();
4545
}
@@ -76,7 +76,7 @@ class MqttSub : virtual public MqttConnector<T> {
7676
MqttSub(JsonDeserializer<T> jsonDeserializer,
7777
StatefulService<T>* statefulService,
7878
AsyncMqttClient* mqttClient,
79-
String subTopic = "") :
79+
const String& subTopic = "") :
8080
MqttConnector<T>(statefulService, mqttClient), _jsonDeserializer(jsonDeserializer), _subTopic(subTopic) {
8181
MqttConnector<T>::_mqttClient->onMessage(std::bind(&MqttSub::onMqttMessage,
8282
this,
@@ -88,7 +88,7 @@ class MqttSub : virtual public MqttConnector<T> {
8888
std::placeholders::_6));
8989
}
9090

91-
void setSubTopic(String subTopic) {
91+
void setSubTopic(const String& subTopic) {
9292
if (!_subTopic.equals(subTopic)) {
9393
// unsubscribe from the existing topic if one was set
9494
if (_subTopic.length() > 0) {
@@ -143,15 +143,15 @@ class MqttPubSub : public MqttPub<T>, public MqttSub<T> {
143143
JsonDeserializer<T> jsonDeserializer,
144144
StatefulService<T>* statefulService,
145145
AsyncMqttClient* mqttClient,
146-
String pubTopic = "",
147-
String subTopic = "") :
146+
const String& pubTopic = "",
147+
const String& subTopic = "") :
148148
MqttConnector<T>(statefulService, mqttClient),
149149
MqttPub<T>(jsonSerializer, statefulService, mqttClient, pubTopic),
150150
MqttSub<T>(jsonDeserializer, statefulService, mqttClient, subTopic) {
151151
}
152152

153153
public:
154-
void configureTopics(String pubTopic, String subTopic) {
154+
void configureTopics(const String& pubTopic, const String& subTopic) {
155155
MqttSub<T>::setSubTopic(subTopic);
156156
MqttPub<T>::setPubTopic(pubTopic);
157157
}

lib/framework/MqttSettingsService.cpp

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ MqttSettingsService::MqttSettingsService(AsyncWebServer* server, FS* fs, Securit
4242
#endif
4343
_mqttClient.onConnect(std::bind(&MqttSettingsService::onMqttConnect, this, std::placeholders::_1));
4444
_mqttClient.onDisconnect(std::bind(&MqttSettingsService::onMqttDisconnect, this, std::placeholders::_1));
45-
addUpdateHandler([&](String originId) { onConfigUpdated(); }, false);
45+
addUpdateHandler([&](const String& originId) { onConfigUpdated(); }, false);
4646
}
4747

4848
MqttSettingsService::~MqttSettingsService() {
@@ -84,13 +84,16 @@ AsyncMqttClient* MqttSettingsService::getMqttClient() {
8484
}
8585

8686
void MqttSettingsService::onMqttConnect(bool sessionPresent) {
87-
Serial.print("Connected to MQTT, ");
88-
Serial.print(sessionPresent ? "with" : "without");
89-
Serial.println(" persistent session");
87+
Serial.print(F("Connected to MQTT, "));
88+
if (sessionPresent) {
89+
Serial.println(F("with persistent session"));
90+
} else {
91+
Serial.println(F("without persistent session"));
92+
}
9093
}
9194

9295
void MqttSettingsService::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
93-
Serial.print("Disconnected from MQTT reason: ");
96+
Serial.print(F("Disconnected from MQTT reason: "));
9497
Serial.println((uint8_t)reason);
9598
_disconnectReason = reason;
9699
_disconnectedAt = millis();
@@ -104,28 +107,28 @@ void MqttSettingsService::onConfigUpdated() {
104107
#ifdef ESP32
105108
void MqttSettingsService::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
106109
if (_state.enabled) {
107-
Serial.println("WiFi connection dropped, starting MQTT client.");
110+
Serial.println(F("WiFi connection dropped, starting MQTT client."));
108111
onConfigUpdated();
109112
}
110113
}
111114

112115
void MqttSettingsService::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
113116
if (_state.enabled) {
114-
Serial.println("WiFi connection dropped, stopping MQTT client.");
117+
Serial.println(F("WiFi connection dropped, stopping MQTT client."));
115118
onConfigUpdated();
116119
}
117120
}
118121
#elif defined(ESP8266)
119122
void MqttSettingsService::onStationModeGotIP(const WiFiEventStationModeGotIP& event) {
120123
if (_state.enabled) {
121-
Serial.println("WiFi connection dropped, starting MQTT client.");
124+
Serial.println(F("WiFi connection dropped, starting MQTT client."));
122125
onConfigUpdated();
123126
}
124127
}
125128

126129
void MqttSettingsService::onStationModeDisconnected(const WiFiEventStationModeDisconnected& event) {
127130
if (_state.enabled) {
128-
Serial.println("WiFi connection dropped, stopping MQTT client.");
131+
Serial.println(F("WiFi connection dropped, stopping MQTT client."));
129132
onConfigUpdated();
130133
}
131134
}
@@ -137,7 +140,7 @@ void MqttSettingsService::configureMqtt() {
137140

138141
// only connect if WiFi is connected and MQTT is enabled
139142
if (_state.enabled && WiFi.isConnected()) {
140-
Serial.println("Connecting to MQTT...");
143+
Serial.println(F("Connecting to MQTT..."));
141144
_mqttClient.setServer(retainCstr(_state.host.c_str(), &_retainedHost), _state.port);
142145
if (_state.username.length() > 0) {
143146
_mqttClient.setCredentials(

lib/framework/NTPSettingsService.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ NTPSettingsService::NTPSettingsService(AsyncWebServer* server, FS* fs, SecurityM
2020
_onStationModeGotIPHandler =
2121
WiFi.onStationModeGotIP(std::bind(&NTPSettingsService::onStationModeGotIP, this, std::placeholders::_1));
2222
#endif
23-
addUpdateHandler([&](String originId) { configureNTP(); }, false);
23+
addUpdateHandler([&](const String& originId) { configureNTP(); }, false);
2424
}
2525

2626
void NTPSettingsService::begin() {
@@ -30,29 +30,29 @@ void NTPSettingsService::begin() {
3030

3131
#ifdef ESP32
3232
void NTPSettingsService::onStationModeGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
33-
Serial.println("Got IP address, starting NTP Synchronization");
33+
Serial.println(F("Got IP address, starting NTP Synchronization"));
3434
configureNTP();
3535
}
3636

3737
void NTPSettingsService::onStationModeDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
38-
Serial.println("WiFi connection dropped, stopping NTP.");
38+
Serial.println(F("WiFi connection dropped, stopping NTP."));
3939
configureNTP();
4040
}
4141
#elif defined(ESP8266)
4242
void NTPSettingsService::onStationModeGotIP(const WiFiEventStationModeGotIP& event) {
43-
Serial.println("Got IP address, starting NTP Synchronization");
43+
Serial.println(F("Got IP address, starting NTP Synchronization"));
4444
configureNTP();
4545
}
4646

4747
void NTPSettingsService::onStationModeDisconnected(const WiFiEventStationModeDisconnected& event) {
48-
Serial.println("WiFi connection dropped, stopping NTP.");
48+
Serial.println(F("WiFi connection dropped, stopping NTP."));
4949
configureNTP();
5050
}
5151
#endif
5252

5353
void NTPSettingsService::configureNTP() {
5454
if (WiFi.isConnected() && _state.enabled) {
55-
Serial.println("Starting NTP...");
55+
Serial.println(F("Starting NTP..."));
5656
#ifdef ESP32
5757
configTzTime(_state.tzFormat.c_str(), _state.server.c_str());
5858
#elif defined(ESP8266)

lib/framework/OTASettingsService.cpp

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ OTASettingsService::OTASettingsService(AsyncWebServer* server, FS* fs, SecurityM
1616
_onStationModeGotIPHandler =
1717
WiFi.onStationModeGotIP(std::bind(&OTASettingsService::onStationModeGotIP, this, std::placeholders::_1));
1818
#endif
19-
addUpdateHandler([&](String originId) { configureArduinoOTA(); }, false);
19+
addUpdateHandler([&](const String& originId) { configureArduinoOTA(); }, false);
2020
}
2121

2222
void OTASettingsService::begin() {
@@ -39,27 +39,27 @@ void OTASettingsService::configureArduinoOTA() {
3939
_arduinoOTA = nullptr;
4040
}
4141
if (_state.enabled) {
42-
Serial.println("Starting OTA Update Service...");
42+
Serial.println(F("Starting OTA Update Service..."));
4343
_arduinoOTA = new ArduinoOTAClass;
4444
_arduinoOTA->setPort(_state.port);
4545
_arduinoOTA->setPassword(_state.password.c_str());
46-
_arduinoOTA->onStart([]() { Serial.println("Starting"); });
47-
_arduinoOTA->onEnd([]() { Serial.println("\nEnd"); });
46+
_arduinoOTA->onStart([]() { Serial.println(F("Starting")); });
47+
_arduinoOTA->onEnd([]() { Serial.println(F("\r\nEnd")); });
4848
_arduinoOTA->onProgress([](unsigned int progress, unsigned int total) {
49-
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
49+
Serial.printf_P(PSTR("Progress: %u%%\r\n"), (progress / (total / 100)));
5050
});
5151
_arduinoOTA->onError([](ota_error_t error) {
5252
Serial.printf("Error[%u]: ", error);
5353
if (error == OTA_AUTH_ERROR)
54-
Serial.println("Auth Failed");
54+
Serial.println(F("Auth Failed"));
5555
else if (error == OTA_BEGIN_ERROR)
56-
Serial.println("Begin Failed");
56+
Serial.println(F("Begin Failed"));
5757
else if (error == OTA_CONNECT_ERROR)
58-
Serial.println("Connect Failed");
58+
Serial.println(F("Connect Failed"));
5959
else if (error == OTA_RECEIVE_ERROR)
60-
Serial.println("Receive Failed");
60+
Serial.println(F("Receive Failed"));
6161
else if (error == OTA_END_ERROR)
62-
Serial.println("End Failed");
62+
Serial.println(F("End Failed"));
6363
});
6464
_arduinoOTA->begin();
6565
}

lib/framework/SecurityManager.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ class SecurityManager {
6565
/*
6666
* Authenticate, returning the user if found
6767
*/
68-
virtual Authentication authenticate(String& username, String& password) = 0;
68+
virtual Authentication authenticate(const String& username, const String& password) = 0;
6969

7070
/*
7171
* Check the request header for the Authorization token

lib/framework/SecuritySettingsService.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ SecuritySettingsService::SecuritySettingsService(AsyncWebServer* server, FS* fs)
88
SECURITY_SETTINGS_PATH,
99
this),
1010
_fsPersistence(SecuritySettings::serialize, SecuritySettings::deserialize, this, fs, SECURITY_SETTINGS_FILE) {
11-
addUpdateHandler([&](String originId) { configureJWTHandler(); }, false);
11+
addUpdateHandler([&](const String& originId) { configureJWTHandler(); }, false);
1212
}
1313

1414
void SecuritySettingsService::begin() {
@@ -51,7 +51,7 @@ Authentication SecuritySettingsService::authenticateJWT(String& jwt) {
5151
return Authentication();
5252
}
5353

54-
Authentication SecuritySettingsService::authenticate(String& username, String& password) {
54+
Authentication SecuritySettingsService::authenticate(const String& username, const String& password) {
5555
for (User _user : _state.users) {
5656
if (_user.username == username && _user.password == password) {
5757
return Authentication(_user);

0 commit comments

Comments
 (0)