Refactor JWTHelper base64 URL encoding to modify output in-place and improve memory efficiency. Enhance MQTTBridge cleanup process to prevent memory leaks by properly deleting queued packets and timezone objects.

This commit is contained in:
agessaman committed 2026-01-02 13:36:41 -08:00
1 parent 3851a84bbf
commit 1219668fb1
2 files changed
+35 -14

No files matched your search

+14 -14
View File
@@ -172,22 +172,22 @@ size_t JWTHelper::base64UrlEncode(const uint8_t* input, size_t inputLen, char* o
Serial.printf("JWTHelper: mbedtls_base64_encode result: %s (outlen: %d)\n", output, (int)outlen);
// Convert to base64 URL format (replace + with -, / with _, remove padding =)
String encoded(output);
encoded.replace('+', '-');
encoded.replace('/', '_');
encoded.replace("=", "");
// Copy back to output buffer
size_t len = encoded.length();
if (len >= outputSize) {
Serial.printf("JWTHelper: base64UrlEncode output too large: %d >= %d\n", (int)len, (int)outputSize);
return 0;
// Convert to base64 URL format in-place (replace + with -, / with _, remove padding =)
for (size_t i = 0; i < outlen; i++) {
if (output[i] == '+') {
output[i] = '-';
} else if (output[i] == '/') {
output[i] = '_';
}
}
strcpy(output, encoded.c_str());
Serial.printf("JWTHelper: base64UrlEncode completed, outputLen: %d\n", (int)len);
return len;
// Remove padding '=' characters
while (outlen > 0 && output[outlen-1] == '=') {
outlen--;
}
output[outlen] = '\0';
Serial.printf("JWTHelper: base64UrlEncode completed, outputLen: %d\n", (int)outlen);
return outlen;
}
size_t JWTHelper::createHeader(char* output, size_t outputSize) {
+21
View File
@@ -228,11 +228,26 @@ void MQTTBridge::end() {
_analyzer_eu_client = nullptr;
}
// Clean up queued packets to prevent memory leaks
for (int i = 0; i < _queue_count; i++) {
int index = (_queue_head + i) % MAX_QUEUE_SIZE;
if (_packet_queue[index].packet) {
_mgr->free(_packet_queue[index].packet);
_packet_queue[index].packet = nullptr;
}
}
// Clear packet queue
_queue_count = 0;
_queue_head = 0;
_queue_tail = 0;
// Clean up timezone object to prevent memory leak
if (_timezone) {
delete _timezone;
_timezone = nullptr;
}
// Clean up resources
if (_mqtt_client) {
delete _mqtt_client;
@@ -1045,6 +1060,12 @@ void MQTTBridge::syncTimeWithNTP() {
// Set timezone from string (with DST support)
MQTT_DEBUG_PRINTLN("Setting timezone: %s", _prefs->timezone_string);
// Clean up old timezone object to prevent memory leak
if (_timezone) {
delete _timezone;
_timezone = nullptr;
}
// Create timezone object based on timezone string
Timezone* tz = createTimezoneFromString(_prefs->timezone_string);
if (tz) {