Просмотр исходного кода

Merge pull request #4208 from SybexX/develop

Harden PSRAM management and close memory leaks
SybexXx 1 день назад
Родитель
Сommit
a2d4184dc5

+ 84 - 27
code/components/jomjol_controlGPIO/server_GPIO.cpp

@@ -5,6 +5,8 @@
 #include <string.h>
 #include "freertos/FreeRTOS.h"
 #include "freertos/task.h"
+#include "freertos/queue.h"
+#include <new>
 #include "esp_system.h"
 
 #include "esp_log.h"
@@ -33,7 +35,7 @@ QueueHandle_t gpio_queue_handle = NULL;
 GpioPin::GpioPin(gpio_num_t gpio, const char* name, gpio_pin_mode_t mode, gpio_int_type_t interruptType, uint8_t dutyResolution, std::string mqttTopic, bool httpEnable) 
 {
     _gpio = gpio;
-    _name = name; 
+    _name = (name != NULL) ? name : ""; 
     _mode = mode;
     _interruptType = interruptType;    
     _mqttTopic = mqttTopic;
@@ -42,8 +44,13 @@ GpioPin::GpioPin(gpio_num_t gpio, const char* name, gpio_pin_mode_t mode, gpio_i
 GpioPin::~GpioPin()
 {
     ESP_LOGD(TAG,"reset GPIO pin %d", _gpio);
+#ifdef ENABLE_MQTT
+    if (!_mqttTopic.empty()) {
+        MQTTunregisterSubscribeFunction(_mqttTopic);
+    }
+#endif // ENABLE_MQTT
     if (_interruptType != GPIO_INTR_DISABLE) {
-        //hook isr handler for specific gpio pin
+        // Remove the interrupt before releasing this pin's callback target.
         gpio_isr_handler_remove(_gpio);
     }
     gpio_reset_pin(_gpio);
@@ -209,36 +216,48 @@ GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer)
 }
 
 GpioHandler::~GpioHandler()  {
+    deinit();
     if (gpioMap != NULL) {
-        clear();
         delete gpioMap;
+        gpioMap = NULL;
     }
 }
 
 void GpioHandler::init()
 {
-    // TickType_t xDelay = 60000 / portTICK_PERIOD_MS;
-    // ESP_LOGD(TAG, "wait before start %ldms", (long) xDelay);
-    // vTaskDelay( xDelay );
-
     ESP_LOGD(TAG, "*************** Start GPIOHandler_Init *****************");
 
+    // Stop any previous task, queue and pin callbacks before rebuilding them.
+    deinit();
+
     if (gpioMap == NULL) {
-        gpioMap = new std::map<gpio_num_t, GpioPin*>();
-    } else {
-        clear();
+        gpioMap = new (std::nothrow) std::map<gpio_num_t, GpioPin*>();
+        if (gpioMap == NULL) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO map");
+            _isEnabled = false;
+            return;
+        }
     }
-    
-    
+
     ESP_LOGI(TAG, "read GPIO config and init GPIO");
     if (!readConfig()) {
         clear();
         delete gpioMap;
         gpioMap = NULL;
+        _isEnabled = false;
         ESP_LOGI(TAG, "GPIO init completed, handler is disabled");
         return;
     }
 
+    // The ISR can enqueue as soon as a pin interrupt is registered. Create the
+    // queue before initializing any configured GPIO pins.
+    gpio_queue_handle = xQueueCreate(10, sizeof(GpioResult));
+    if (gpio_queue_handle == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO interrupt queue");
+        clear();
+        _isEnabled = false;
+        return;
+    }
 
     for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
         it->second->init();
@@ -249,16 +268,22 @@ void GpioHandler::init()
     MQTTregisterConnectFunction("gpio-handler", f);
 #endif //ENABLE_MQTT
 
-    if (xHandleTaskGpio == NULL) {
-        gpio_queue_handle = xQueueCreate(10,sizeof(GpioResult));
-        BaseType_t  xReturned = xTaskCreate(&gpioHandlerTask, "gpio_int", 3 * 1024, (void *)this, tskIDLE_PRIORITY + 4, &xHandleTaskGpio);
-        if(xReturned == pdPASS ) {
-            ESP_LOGD(TAG, "xHandletaskGpioHandler started");
-        } else {
-            ESP_LOGD(TAG, "xHandletaskGpioHandler not started %d ", (int)xHandleTaskGpio);
-        }
+    const BaseType_t taskResult = xTaskCreate(&gpioHandlerTask, "gpio_int", 3 * 1024,
+                                               (void *)this, tskIDLE_PRIORITY + 4, &xHandleTaskGpio);
+    if (taskResult != pdPASS) {
+        xHandleTaskGpio = NULL;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create GPIO handler task");
+#ifdef ENABLE_MQTT
+        MQTTunregisterConnectFunction("gpio-handler");
+#endif
+        clear();
+        vQueueDelete(gpio_queue_handle);
+        gpio_queue_handle = NULL;
+        _isEnabled = false;
+        return;
     }
 
+    _isEnabled = true;
     ESP_LOGI(TAG, "GPIO init completed, is enabled");
 }
 
@@ -287,11 +312,27 @@ void GpioHandler::deinit() {
 #ifdef ENABLE_MQTT
     MQTTunregisterConnectFunction("gpio-handler");
 #endif //ENABLE_MQTT
-    clear();
+
+    // Stop the worker before deleting its GPIO callback targets or queue.
     if (xHandleTaskGpio != NULL) {
         vTaskDelete(xHandleTaskGpio);
         xHandleTaskGpio = NULL;
     }
+#ifdef __LEDGLOBAL
+    if (leds_global != NULL) {
+        // Wait until RMT has finished using the LED buffers before destroying the driver.
+        leds_global->wait();
+        delete leds_global;
+        leds_global = NULL;
+    }
+#endif
+    clear();
+
+    if (gpio_queue_handle != NULL) {
+        vQueueDelete(gpio_queue_handle);
+        gpio_queue_handle = NULL;
+    }
+    _isEnabled = false;
 }
 
 void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
@@ -365,7 +406,7 @@ bool GpioHandler::readConfig()
             bool httpEnabled = (toLower(splitted[5]) == "true");
             char gpioName[100];
             if (splitted.size() >= 7) {
-                strcpy(gpioName, trim(splitted[6]).c_str());
+                strlcpy(gpioName, trim(splitted[6]).c_str(), sizeof(gpioName));
             } else {
                 sprintf(gpioName, "GPIO%d", gpioNr);
             }
@@ -374,8 +415,20 @@ bool GpioHandler::readConfig()
 #else // ENABLE_MQTT
             std::string mqttTopic = "";
 #endif // ENABLE_MQTT
-            GpioPin* gpioPin = new GpioPin(gpioNr, gpioName, pinMode, intType,dutyResolution, mqttTopic, httpEnabled);
-            (*gpioMap)[gpioNr] = gpioPin;
+            GpioPin* gpioPin = new (std::nothrow) GpioPin(
+                gpioNr, gpioName, pinMode, intType, dutyResolution, mqttTopic, httpEnabled);
+            if (gpioPin == NULL) {
+                LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO pin configuration");
+                return false;
+            }
+            const auto existingPin = gpioMap->find(gpioNr);
+            if (existingPin != gpioMap->end()) {
+                // Duplicate GPIO entries replace the previous uninitialized definition.
+                delete existingPin->second;
+                existingPin->second = gpioPin;
+            } else {
+                gpioMap->emplace(gpioNr, gpioPin);
+            }
 
             if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
             {
@@ -671,10 +724,14 @@ gpio_int_type_t GpioHandler::resolveIntType(std::string input)
 
 static GpioHandler *gpioHandler = NULL;
 
-void gpio_handler_create(httpd_handle_t server) 
+void gpio_handler_create(httpd_handle_t server)
 {
-    if (gpioHandler == NULL)
-        gpioHandler = new GpioHandler(CONFIG_FILE, server);
+    if (gpioHandler == NULL) {
+        gpioHandler = new (std::nothrow) GpioHandler(CONFIG_FILE, server);
+        if (gpioHandler == NULL) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO handler");
+        }
+    }
 }
 
 void gpio_handler_init() 

+ 2 - 1
code/components/jomjol_controlGPIO/server_GPIO.h

@@ -7,6 +7,7 @@
 
 #include <esp_http_server.h>
 #include <map>
+#include <string>
 #include "driver/gpio.h"
 
 #include "SmartLeds.h"
@@ -53,7 +54,7 @@ public:
 
 private:
     gpio_num_t _gpio;
-    const char* _name;
+    std::string _name;
     gpio_pin_mode_t _mode;
     gpio_int_type_t _interruptType;
     std::string _mqttTopic;

+ 36 - 32
code/components/jomjol_controlcamera/ClassControllCamera.cpp

@@ -75,14 +75,6 @@ static bool isSupportedFrameSize(int value)
     {
     case FRAMESIZE_QVGA:
     case FRAMESIZE_VGA:
-    case FRAMESIZE_SVGA:
-    case FRAMESIZE_XGA:
-    case FRAMESIZE_HD:
-    case FRAMESIZE_SXGA:
-    case FRAMESIZE_UXGA:
-    case FRAMESIZE_QXGA:
-    case FRAMESIZE_WQXGA:
-    case FRAMESIZE_QSXGA:
         return true;
     default:
         return false;
@@ -407,7 +399,13 @@ esp_err_t CCamera::ApplySettings(CameraSettings &settings)
     recordError(s->set_raw_gma(s, settings.ImageRawGma));
     recordError(s->set_lenc(s, settings.ImageLenc));
     SetCamSharpness(settings.ImageAutoSharpness, settings.ImageSharpness);
-    recordError(s->set_denoise(s, settings.ImageDenoiseLevel));
+    // The OV2640 driver does not implement denoise control and its set_denoise()
+    // callback always returns -1, even when the requested level is zero. Treat
+    // this unsupported optional control as a no-op instead of aborting camera setup.
+    if (s->id.PID != OV2640_PID)
+    {
+        recordError(s->set_denoise(s, settings.ImageDenoiseLevel));
+    }
 
     const esp_err_t geometryResult = SetQualityZoomSize(settings);
     if (geometryResult != ESP_OK) return geometryResult;
@@ -658,9 +656,14 @@ esp_err_t CCamera::SetZoomSize(const CameraSettings &settings)
     sensor_t *s = esp_camera_sensor_get();
     if (s == NULL) return ESP_FAIL;
 
-    if (!settings.ImageZoomEnabled)
+    // The ESP32 pipeline is deliberately limited to VGA output. Sensor-side
+    // windowing below performs zoom/cropping without creating larger RAM frames.
+    CameraSettings outputSettings = settings;
+    SetImageWidthHeightFromResolution(outputSettings);
+
+    if (!outputSettings.ImageZoomEnabled)
     {
-        return s->set_framesize(s, settings.ImageFrameSize) == 0 ? ESP_OK : ESP_FAIL;
+        return s->set_framesize(s, outputSettings.ImageFrameSize) == 0 ? ESP_OK : ESP_FAIL;
     }
 
     int frameSizeX = 0;
@@ -688,18 +691,18 @@ esp_err_t CCamera::SetZoomSize(const CameraSettings &settings)
         return ESP_ERR_NOT_SUPPORTED;
     }
 
-    const int zoomSize = min(maxZoom, max(0, settings.ImageZoomSize));
+    const int zoomSize = min(maxZoom, max(0, outputSettings.ImageZoomSize));
     const int zoomDelta = maxZoom - zoomSize;
-    int imageWidth = settings.ImageWidth;
-    int imageHeight = settings.ImageHeight;
-    int offsetX = settings.ImageZoomOffsetX;
-    int offsetY = settings.ImageZoomOffsetY;
+    int imageWidth = outputSettings.ImageWidth;
+    int imageHeight = outputSettings.ImageHeight;
+    int offsetX = outputSettings.ImageZoomOffsetX;
+    int offsetY = outputSettings.ImageZoomOffsetY;
 
-    SanitizeZoomParams(settings, zoomDelta, frameSizeX, frameSizeY,
+    SanitizeZoomParams(outputSettings, zoomDelta, frameSizeX, frameSizeY,
                        imageWidth, imageHeight, offsetX, offsetY);
     SetCamWindow(s, frameSizeX, frameSizeY, offsetX, offsetY,
-                 imageWidth, imageHeight, settings.ImageWidth, settings.ImageHeight,
-                 settings.ImageVflip);
+                 imageWidth, imageHeight, outputSettings.ImageWidth, outputSettings.ImageHeight,
+                 outputSettings.ImageVflip);
     return ESP_OK;
 }
 
@@ -1285,21 +1288,22 @@ void CCamera::SetImageWidthHeightFromResolution(CameraSettings &settings)
 {
     switch (settings.ImageFrameSize)
     {
-    case FRAMESIZE_QVGA:   settings.ImageWidth = 320;  settings.ImageHeight = 240;  break;
-    case FRAMESIZE_VGA:    settings.ImageWidth = 640;  settings.ImageHeight = 480;  break;
-    case FRAMESIZE_SVGA:   settings.ImageWidth = 800;  settings.ImageHeight = 600;  break;
-    case FRAMESIZE_XGA:    settings.ImageWidth = 1024; settings.ImageHeight = 768;  break;
-    case FRAMESIZE_HD:     settings.ImageWidth = 1280; settings.ImageHeight = 720;  break;
-    case FRAMESIZE_SXGA:   settings.ImageWidth = 1280; settings.ImageHeight = 1024; break;
-    case FRAMESIZE_UXGA:   settings.ImageWidth = 1600; settings.ImageHeight = 1200; break;
-    case FRAMESIZE_QXGA:   settings.ImageWidth = 2048; settings.ImageHeight = 1536; break;
-    case FRAMESIZE_WQXGA:  settings.ImageWidth = 2560; settings.ImageHeight = 1600; break;
-    case FRAMESIZE_QSXGA: settings.ImageWidth = 2560; settings.ImageHeight = 1920; break;
+    case FRAMESIZE_QVGA:
+        settings.ImageWidth = 320;
+        settings.ImageHeight = 240;
+        break;
+    case FRAMESIZE_VGA:
+        settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
+        settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
+        break;
     default:
-        ESP_LOGW(TAG, "Unsupported frame size %d; falling back to VGA", static_cast<int>(settings.ImageFrameSize));
+        // Higher resolutions overload the ESP32 image-processing pipeline.
+        // Zoom is implemented by sensor-side windowing, while the output stays VGA.
+        ESP_LOGW(TAG, "Frame size %d exceeds the supported VGA limit; forcing VGA",
+                 static_cast<int>(settings.ImageFrameSize));
         settings.ImageFrameSize = FRAMESIZE_VGA;
-        settings.ImageWidth = 640;
-        settings.ImageHeight = 480;
+        settings.ImageWidth = CAMERA_MAX_FRAME_WIDTH;
+        settings.ImageHeight = CAMERA_MAX_FRAME_HEIGHT;
         break;
     }
 }

+ 8 - 6
code/components/jomjol_fileserver_ota/md5.cpp

@@ -200,19 +200,21 @@ void md5Step(uint32_t *buffer, uint32_t *input){
 
 
 void md5File(FILE *file, uint8_t *result){
-    void *input_buffer = malloc(1024);
+    if (file == NULL || result == NULL) {
+        return;
+    }
+
+    // Fixed-size stack buffer avoids a heap allocation for a tiny streaming workspace.
+    uint8_t input_buffer[1024];
     size_t input_size = 0;
 
     MD5Context ctx;
     md5Init(&ctx);
 
-    while((input_size = fread(input_buffer, 1, 1024, file)) > 0){
-        md5Update(&ctx, (uint8_t *)input_buffer, input_size);
+    while((input_size = fread(input_buffer, 1, sizeof(input_buffer), file)) > 0){
+        md5Update(&ctx, input_buffer, input_size);
     }
 
     md5Finalize(&ctx);
-
-    free(input_buffer);
-
     memcpy(result, ctx.digest, 16);
 }

+ 15 - 13
code/components/jomjol_fileserver_ota/server_file.cpp

@@ -1004,26 +1004,28 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
 {
     static struct file_server_data *server_data = NULL;
 
-    /* Validate file storage base path */
-    if (!base_path)
+    if (server == NULL)
     {
-        //    if (!base_path || strcmp(base_path, "/spiffs") != 0) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server base_path not set");
-        //        return ESP_ERR_INVALID_ARG;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server handle is not available");
+        return;
     }
 
-    if (server_data)
+    /* Validate file storage base path */
+    if (base_path == NULL || base_path[0] == '\0')
     {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server already started");
-        //        return ESP_ERR_INVALID_STATE;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File server base_path not set");
+        return;
     }
 
-    /* Allocate memory for server data */
-    server_data = (file_server_data *)calloc(1, sizeof(struct file_server_data));
-    if (!server_data)
+    /* Reuse the same context on server restarts instead of overwriting and leaking it. */
+    if (server_data == NULL)
     {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate memory for server data");
-        //        return ESP_ERR_NO_MEM;
+        server_data = (file_server_data *)calloc(1, sizeof(struct file_server_data));
+        if (server_data == NULL)
+        {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate memory for server data");
+            return;
+        }
     }
     strlcpy(server_data->base_path, base_path,
             sizeof(server_data->base_path));

+ 9 - 8
code/components/jomjol_fileserver_ota/server_help.cpp

@@ -108,17 +108,18 @@ esp_err_t send_file(httpd_req_t *req, std::string filename)
         chunksize = fread(chunk, 1, SERVER_HELPER_SCRATCH_BUFSIZE, fd);
 
         /* Send the buffer contents as HTTP response chunk */
-        if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK)
+        const esp_err_t sendResult = httpd_resp_send_chunk(req, chunk, chunksize);
+        if (sendResult != ESP_OK)
         {
             fclose(fd);
-            ESP_LOGE(TAG, "File sending failed!");
-
-            /* Abort sending file */
-            httpd_resp_sendstr_chunk(req, NULL);
-
-            /* Respond with 500 Internal Server Error */
-            httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
 
+            // The response headers/body may already have been sent. A failed
+            // chunk send usually means the peer closed/reset the connection;
+            // trying to send a final chunk or a second HTTP 500 response on
+            // that socket only creates secondary errors and cannot reach the
+            // client.
+            ESP_LOGW(TAG, "File transfer interrupted for %s (send error %d)",
+                     filename.c_str(), static_cast<int>(sendResult));
             return ESP_FAIL;
         }
 

+ 12 - 7
code/components/jomjol_flowcontroll/ClassFlowControll.cpp

@@ -304,10 +304,14 @@ ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
         flowpostprocessing = (ClassFlowPostProcessing*) cfc;
     }
 
+    const std::string normalizedType = toUpper(_type);
+    const bool disabledSection = !_type.empty() && (_type[0] == ';');
+
     if (cfc) {
         FlowControll.push_back(cfc);
-    } else if (_type != "[AUTOTIMER]" && _type != "[DATALOGGING]" &&
-               _type != "[DEBUG]" && _type != "[SYSTEM]") {
+    } else if (!disabledSection &&
+               normalizedType != "[AUTOTIMER]" && normalizedType != "[DATALOGGING]" &&
+               normalizedType != "[DEBUG]" && normalizedType != "[SYSTEM]") {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate flow component " + _type);
     }
 
@@ -365,11 +369,12 @@ void ClassFlowControll::InitFlow(std::string config)
             cfc->ReadParameter(pFile, line);
         }
         else {
-            line = "";
-		
-            if (fgets(zw, 1024, pFile) && !feof(pFile)) {
-                ESP_LOGD(TAG, "Read: %s", zw);
-                line = std::string(zw);
+            // This controller only instantiates flow steps. Other or disabled
+            // config sections (for example GPIO and commented-out integrations)
+            // are handled elsewhere or intentionally inactive. Skip their whole
+            // paragraph instead of treating each key/value line as a flow name.
+            if (!this->GetNextParagraph(pFile, line)) {
+                line.clear();
             }
         }
     }

+ 169 - 87
code/components/jomjol_flowcontroll/ClassFlowPostProcessing.cpp

@@ -4,6 +4,10 @@
 
 #include <iomanip>
 #include <sstream>
+#include <new>
+#include <memory>
+#include <cerrno>
+#include <cstdlib>
 
 #include <time.h>
 
@@ -150,102 +154,127 @@ bool ClassFlowPostProcessing::SetPreValue(double _newvalue, string _numbers, boo
 
 bool ClassFlowPostProcessing::LoadPreValue(void) {
     std::vector<string> splitted;
-    FILE* pFile;
-    char zw[1024];
+    char zw[1024] = {};
     string zwtime, zwvalue, name;
-    bool _done = false;
 
     UpdatePreValueINI = false;       // Conversion to the new format
 
-    pFile = fopen(FilePreValue.c_str(), "r");
-	
-    if (pFile == NULL) {
+    // Close the descriptor on every return path, including empty or malformed files.
+    std::unique_ptr<FILE, int(*)(FILE*)> pFile(fopen(FilePreValue.c_str(), "r"), fclose);
+    if (!pFile) {
         return false;
     }
 
-    // Makes sure that an empty file is treated as such.
-    zw[0] = '\0';
-
-    fgets(zw, 1024, pFile);
+    if (fgets(zw, sizeof(zw), pFile.get()) == NULL) {
+        return false;
+    }
     ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
     zwtime = trim(std::string(zw));
-	
-    if (zwtime.length() == 0) {
+    if (zwtime.empty()) {
         return false;
     }
 
     splitted = HelperZerlegeZeile(zwtime, "\t");
-	
-    //  Conversion to the new format
+
+    // Conversion to the current tab-separated format: name, timestamp, value.
     if (splitted.size() > 1) {
-        while ((splitted.size() > 1) && !_done) {
+        while (true) {
+            if (splitted.size() < 3) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue entry: expected name, timestamp and value");
+                return false;
+            }
+
             name = trim(splitted[0]);
             zwtime = trim(splitted[1]);
             zwvalue = trim(splitted[2]);
+            if (name.empty() || !isStringNumeric(zwvalue)) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue entry for '" + name + "'");
+                return false;
+            }
+            char* valueEnd = NULL;
+            errno = 0;
+            const double parsedValue = strtod(zwvalue.c_str(), &valueEnd);
+            if (valueEnd == zwvalue.c_str() || *valueEnd != '\0' || errno == ERANGE) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid numeric PreValue for '" + name + "'");
+                return false;
+            }
+
+            int yy = 0, month = 0, dd = 0, hh = 0, mm = 0, ss = 0;
+            struct tm whenStart = {};
+            if (sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT,
+                       &yy, &month, &dd, &hh, &mm, &ss) != 6) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid PreValue timestamp for '" + name + "'");
+                return false;
+            }
+            whenStart.tm_year = yy - 1900;
+            whenStart.tm_mon = month - 1;
+            whenStart.tm_mday = dd;
+            whenStart.tm_hour = hh;
+            whenStart.tm_min = mm;
+            whenStart.tm_sec = ss;
+            whenStart.tm_isdst = -1;
+            const time_t parsedTime = mktime(&whenStart);
+            if (parsedTime == static_cast<time_t>(-1)) {
+                LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to parse PreValue timestamp for '" + name + "'");
+                return false;
+            }
 
             for (int j = 0; j < NUMBERS.size(); ++j) {
                 if (NUMBERS[j]->name == name) {
-                    NUMBERS[j]->PreValue = stod(zwvalue.c_str());
-                    NUMBERS[j]->ReturnPreValue = RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma + 1);      // To be on the safe side, 1 digit more, as Exgtended Resolution may be on (will only be set during the first run).
+                    NUMBERS[j]->PreValue = parsedValue;
+                    NUMBERS[j]->ReturnPreValue = RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma + 1);
+                    NUMBERS[j]->timeStampLastPreValue = parsedTime;
 
                     time_t tStart;
-                    int yy, month, dd, hh, mm, ss;
-                    struct tm whenStart;
-
-                    sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT, &yy, &month, &dd, &hh, &mm, &ss);
-                    whenStart.tm_year = yy - 1900;
-                    whenStart.tm_mon = month - 1;
-                    whenStart.tm_mday = dd;
-                    whenStart.tm_hour = hh;
-                    whenStart.tm_min = mm;
-                    whenStart.tm_sec = ss;
-                    whenStart.tm_isdst = -1;
-
-                    NUMBERS[j]->timeStampLastPreValue = mktime(&whenStart);
-
                     time(&tStart);
-                    localtime(&tStart);
-                    double difference = difftime(tStart, NUMBERS[j]->timeStampLastPreValue);
-                    difference /= 60;
-			
-                    if (difference > PreValueAgeStartup) {
-                        NUMBERS[j]->PreValueOkay = false;
-                    }
-                    else {
-                        NUMBERS[j]->PreValueOkay = true;
-                    }
+                    const double difference = difftime(tStart, parsedTime) / 60.0;
+                    NUMBERS[j]->PreValueOkay = (difference <= PreValueAgeStartup);
                 }
             }
 
-            if (!fgets(zw, 1024, pFile)) {
-                _done = true;
-            }
-            else {
-                ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
-                splitted = HelperZerlegeZeile(trim(std::string(zw)), "\t");
-		    
-                if (splitted.size() > 1) {
-                    name = trim(splitted[0]);
-                    zwtime = trim(splitted[1]);
-                    zwvalue = trim(splitted[2]);
+            std::string nextLine;
+            bool haveNextLine = false;
+            while (fgets(zw, sizeof(zw), pFile.get()) != NULL) {
+                nextLine = trim(std::string(zw));
+                if (!nextLine.empty()) {
+                    haveNextLine = true;
+                    break;
                 }
             }
+            if (!haveNextLine) {
+                break;
+            }
+
+            ESP_LOGD(TAG, "Read line Prevalue.ini: %s", zw);
+            splitted = HelperZerlegeZeile(nextLine, "\t");
         }
-        fclose(pFile);
-    }   
+    }
     else {
-        // Old Format
-        fgets(zw, 1024, pFile);
-        fclose(pFile);
+        // Old format stores the timestamp in the first line and the value in the second.
+        if (NUMBERS.empty() || fgets(zw, sizeof(zw), pFile.get()) == NULL) {
+            return false;
+        }
         ESP_LOGD(TAG, "%s", zw);
         zwvalue = trim(std::string(zw));
-        NUMBERS[0]->PreValue = stod(zwvalue.c_str());
-
-        time_t tStart;
-        int yy, month, dd, hh, mm, ss;
-        struct tm whenStart;
+        if (!isStringNumeric(zwvalue)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid legacy PreValue number");
+            return false;
+        }
+        char* valueEnd = NULL;
+        errno = 0;
+        const double parsedValue = strtod(zwvalue.c_str(), &valueEnd);
+        if (valueEnd == zwvalue.c_str() || *valueEnd != '\0' || errno == ERANGE) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid numeric legacy PreValue");
+            return false;
+        }
 
-        sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT, &yy, &month, &dd, &hh, &mm, &ss);
+        int yy = 0, month = 0, dd = 0, hh = 0, mm = 0, ss = 0;
+        struct tm whenStart = {};
+        if (sscanf(zwtime.c_str(), PREVALUE_TIME_FORMAT_INPUT,
+                   &yy, &month, &dd, &hh, &mm, &ss) != 6) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Invalid legacy PreValue timestamp");
+            return false;
+        }
         whenStart.tm_year = yy - 1900;
         whenStart.tm_mon = month - 1;
         whenStart.tm_mday = dd;
@@ -254,19 +283,21 @@ bool ClassFlowPostProcessing::LoadPreValue(void) {
         whenStart.tm_sec = ss;
         whenStart.tm_isdst = -1;
 
-        ESP_LOGD(TAG, "TIME: %d, %d, %d, %d, %d, %d", whenStart.tm_year, whenStart.tm_mon, whenStart.tm_wday, whenStart.tm_hour, whenStart.tm_min, whenStart.tm_sec);
-
-        NUMBERS[0]->timeStampLastPreValue = mktime(&whenStart);
+        const time_t parsedTime = mktime(&whenStart);
+        if (parsedTime == static_cast<time_t>(-1)) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to parse legacy PreValue timestamp");
+            return false;
+        }
 
+        time_t tStart;
         time(&tStart);
-        localtime(&tStart);
-        double difference = difftime(tStart, NUMBERS[0]->timeStampLastPreValue);
-        difference /= 60;
-			
+        const double difference = difftime(tStart, parsedTime) / 60.0;
         if (difference > PreValueAgeStartup) {
             return false;
         }
 
+        NUMBERS[0]->PreValue = parsedValue;
+        NUMBERS[0]->timeStampLastPreValue = parsedTime;
         NUMBERS[0]->Value = NUMBERS[0]->PreValue;
         NUMBERS[0]->ReturnValue = to_string(NUMBERS[0]->Value);
 
@@ -274,15 +305,16 @@ bool ClassFlowPostProcessing::LoadPreValue(void) {
             NUMBERS[0]->ReturnValue = RundeOutput(NUMBERS[0]->Value, NUMBERS[0]->Nachkomma);
         }
 
-        UpdatePreValueINI = true;       // Conversion to the new format
+        // Close the input before rewriting the file in the current format.
+        pFile.reset();
+        UpdatePreValueINI = true;
         SavePreValue();
-    } 
+    }
 
     return true;
 }
 
 void ClassFlowPostProcessing::SavePreValue() {
-    FILE* pFile;
     string _zw;
 
     // PreValues unchanged --> File does not have to be rewritten
@@ -290,27 +322,43 @@ void ClassFlowPostProcessing::SavePreValue() {
         return;
     }
 
-    pFile = fopen(FilePreValue.c_str(), "w");
+    FILE* rawFile = fopen(FilePreValue.c_str(), "w");
+    if (rawFile == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: unable to open " + FilePreValue);
+        return;
+    }
+    std::unique_ptr<FILE, int(*)(FILE*)> pFile(rawFile, fclose);
+    bool writeOkay = true;
 
     for (int j = 0; j < NUMBERS.size(); ++j) {
-        char buffer[80];
+        char buffer[80] = {};
         struct tm* timeinfo = localtime(&NUMBERS[j]->timeStampLastPreValue);
-        strftime(buffer, 80, PREVALUE_TIME_FORMAT_OUTPUT, timeinfo);
+        if (timeinfo == NULL || strftime(buffer, sizeof(buffer), PREVALUE_TIME_FORMAT_OUTPUT, timeinfo) == 0) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: unable to format timestamp");
+            writeOkay = false;
+            break;
+        }
         NUMBERS[j]->timeStamp = std::string(buffer);
         NUMBERS[j]->timeStampTimeUTC = NUMBERS[j]->timeStampLastPreValue;
-        // ESP_LOGD(TAG, "SaverPreValue %d, Value: %f, Nachkomma %d", j, NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma);
 
-        _zw = NUMBERS[j]->name + "\t" + NUMBERS[j]->timeStamp + "\t" + RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma) + "\n";
+        _zw = NUMBERS[j]->name + "\t" + NUMBERS[j]->timeStamp + "\t" +
+              RundeOutput(NUMBERS[j]->PreValue, NUMBERS[j]->Nachkomma) + "\n";
         ESP_LOGD(TAG, "Write PreValue line: %s", _zw.c_str());
-			
-        if (pFile) {
-            fputs(_zw.c_str(), pFile);
+
+        if (fputs(_zw.c_str(), pFile.get()) < 0) {
+            writeOkay = false;
+            break;
         }
     }
 
-    UpdatePreValueINI = false;
-
-    fclose(pFile);
+    if (fclose(pFile.release()) != 0) {
+        writeOkay = false;
+    }
+    if (writeOkay) {
+        UpdatePreValueINI = false;
+    } else {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "SavePreValue: failed while writing " + FilePreValue);
+    }
 }
 
 ClassFlowPostProcessing::ClassFlowPostProcessing(std::vector<ClassFlow*>* lfc, ClassFlowCNNGeneral *_analog, ClassFlowCNNGeneral *_digit) {
@@ -593,7 +641,14 @@ bool ClassFlowPostProcessing::ReadParameter(FILE* pfile, string& aktparamgraph)
         return false;
     }
 
-    InitNUMBERS();
+    if (!InitNUMBERS()) {
+        disabled = true;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Post-processing initialization failed; disabling this step and skipping its configuration");
+        // InitFlow() advances using aktparamgraph. Consume this entire section so a failed
+        // allocation cannot leave the parser on [PostProcessing] and recreate the flow forever.
+        while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) {}
+        return true;
+    }
 
     while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) {
         splitted = ZerlegeZeile(aktparamgraph);
@@ -661,7 +716,20 @@ bool ClassFlowPostProcessing::ReadParameter(FILE* pfile, string& aktparamgraph)
     return true;
 }
 
-void ClassFlowPostProcessing::InitNUMBERS() {
+ClassFlowPostProcessing::~ClassFlowPostProcessing() {
+    for (NumberPost* number : NUMBERS) {
+        delete number;
+    }
+    NUMBERS.clear();
+}
+
+bool ClassFlowPostProcessing::InitNUMBERS() {
+    // The configuration can be reloaded; release any previous per-number state first.
+    for (NumberPost* number : NUMBERS) {
+        delete number;
+    }
+    NUMBERS.clear();
+
     int anzDIGIT = 0;
     int anzANALOG = 0;
     std::vector<std::string> name_numbers;
@@ -677,9 +745,21 @@ void ClassFlowPostProcessing::InitNUMBERS() {
     }
 
     ESP_LOGD(TAG, "Anzahl NUMBERS: %d - DIGITS: %d, ANALOG: %d", name_numbers.size(), anzDIGIT, anzANALOG);
+    if (name_numbers.empty()) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "No digit or analog numbers are available for post-processing");
+        return false;
+    }
 
     for (int _num = 0; _num < name_numbers.size(); ++_num) {
-        NumberPost *_number = new NumberPost;
+        NumberPost *_number = new (std::nothrow) NumberPost;
+        if (_number == NULL) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate post-processing state for number " + name_numbers[_num]);
+            for (NumberPost* number : NUMBERS) {
+                delete number;
+            }
+            NUMBERS.clear();
+            return false;
+        }
 
         _number->name = name_numbers[_num];
         
@@ -739,6 +819,7 @@ void ClassFlowPostProcessing::InitNUMBERS() {
     for (int i = 0; i < NUMBERS.size(); ++i) {
         ESP_LOGD(TAG, "Number %s, Anz DIG: %d, Anz ANA %d", NUMBERS[i]->name.c_str(), NUMBERS[i]->AnzahlDigit, NUMBERS[i]->AnzahlAnalog);
     }
+    return true;
 }
 
 string ClassFlowPostProcessing::ShiftDecimal(string in, int _decShift) {
@@ -786,6 +867,7 @@ string ClassFlowPostProcessing::ShiftDecimal(string in, int _decShift) {
 }
 
 bool ClassFlowPostProcessing::doFlow(string zwtime) {
+    if (disabled) return true;
     std::lock_guard<std::mutex> lock(preValueMutex);
     string zwvalue;
     time_t imagetime = flowTakeImage->getTimeImageTaken();

+ 2 - 2
code/components/jomjol_flowcontroll/ClassFlowPostProcessing.h

@@ -35,7 +35,7 @@ protected:
     string ErsetzteN(string, double _prevalue);
     double checkDigitConsistency(double input, int _decilamshift, bool _isanalog, double _preValue);
 
-    void InitNUMBERS();
+    bool InitNUMBERS();
 	
     void handleDecimalSeparator(string _decsep, string _value);
     void handleMaxRateValue(string _decsep, string _value);
@@ -55,7 +55,7 @@ public:
     std::vector<NumberPost*> NUMBERS;
 
     ClassFlowPostProcessing(std::vector<ClassFlow*>* lfc, ClassFlowCNNGeneral *_analog, ClassFlowCNNGeneral *_digit);
-    virtual ~ClassFlowPostProcessing(){};
+    virtual ~ClassFlowPostProcessing();
     bool ReadParameter(FILE* pfile, string& aktparamgraph);
     bool doFlow(string time);
     string getReadout(int _number);

+ 122 - 16
code/components/jomjol_helper/psram.cpp

@@ -23,16 +23,25 @@ struct alignas(16) StbiSharedBlockHeader {
 static_assert(sizeof(StbiSharedBlockHeader) == STBI_ALIGNMENT, "STBI shared allocation header must preserve alignment");
 static portMUX_TYPE sharedMemoryMux = portMUX_INITIALIZER_UNLOCKED;
 static uint8_t* sharedRegion = nullptr;
+static uint8_t* sharedRegionAllocation = nullptr;
 static size_t allocatedBytesForSTBI = 0;
 static SharedMemoryUser sharedMemoryUser = SharedMemoryUser::None;
 static bool tensorArenaClaimed = false;
 static bool modelMemoryClaimed = false;
 
-static bool getSharedRegionSize(size_t* size) {
+static bool getAlignedTensorArenaSize(size_t* size) {
     if (size == nullptr) return false;
     const size_t arenaSize = static_cast<size_t>(TENSOR_ARENA_SIZE);
+    if (arenaSize == 0 || arenaSize > SIZE_MAX - (STBI_ALIGNMENT - 1)) return false;
+    *size = (arenaSize + STBI_ALIGNMENT - 1) & ~(STBI_ALIGNMENT - 1);
+    return true;
+}
+static bool getSharedRegionSize(size_t* size) {
+    if (size == nullptr) return false;
+    size_t arenaSize = 0;
+    if (!getAlignedTensorArenaSize(&arenaSize)) return false;
     const size_t modelSize = static_cast<size_t>(MAX_MODEL_SIZE);
-    if (arenaSize == 0 || modelSize == 0 || arenaSize > SIZE_MAX - modelSize) return false;
+    if (modelSize == 0 || arenaSize > SIZE_MAX - modelSize) return false;
     *size = arenaSize + modelSize;
     return true;
 }
@@ -46,8 +55,11 @@ static const char* sharedMemoryUserName(SharedMemoryUser user) {
 }
 static bool isInsideSharedRegionLocked(const void* ptr, size_t regionSize) {
     if (ptr == nullptr || sharedRegion == nullptr) return false;
+    if (sharedRegionAllocation == nullptr) return false;
+    const uintptr_t allocationBegin = reinterpret_cast<uintptr_t>(sharedRegionAllocation);
     const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
     const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
+    if (begin < allocationBegin || begin - allocationBegin >= STBI_ALIGNMENT) return false;
     return address >= begin && (address - begin) < regionSize;
 }
 static bool alignStbiOffset(size_t value, size_t* aligned) {
@@ -67,16 +79,37 @@ bool reserve_psram_shared_region(void) {
     const bool alreadyReserved = (sharedRegion != nullptr);
     portEXIT_CRITICAL(&sharedMemoryMux);
     if (alreadyReserved) return true;
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + std::to_string(regionSize) + " bytes)...");
-    uint8_t* candidate = static_cast<uint8_t*>(malloc_psram_heap("Shared PSRAM region", regionSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
-    if (candidate == nullptr) {
+    if (regionSize > SIZE_MAX - (STBI_ALIGNMENT - 1)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared PSRAM region size overflows alignment padding");
+        return false;
+    }
+    const size_t allocationSize = regionSize + STBI_ALIGNMENT - 1;
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + std::to_string(regionSize) + " usable bytes)...");
+    uint8_t* candidateAllocation = static_cast<uint8_t*>(malloc_psram_heap(
+        "Shared PSRAM region", allocationSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    if (candidateAllocation == nullptr) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate shared PSRAM region!");
         return false;
     }
+    const uintptr_t rawAddress = reinterpret_cast<uintptr_t>(candidateAllocation);
+    if (rawAddress > UINTPTR_MAX - (STBI_ALIGNMENT - 1)) {
+        free_psram_heap("Invalid shared PSRAM region", candidateAllocation);
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared PSRAM region address overflows alignment");
+        return false;
+    }
+    const uintptr_t alignedAddress = (rawAddress + STBI_ALIGNMENT - 1) &
+                                     ~static_cast<uintptr_t>(STBI_ALIGNMENT - 1);
+    uint8_t* candidate = reinterpret_cast<uint8_t*>(alignedAddress);
     portENTER_CRITICAL(&sharedMemoryMux);
-    if (sharedRegion == nullptr) { sharedRegion = candidate; candidate = nullptr; }
+    if (sharedRegion == nullptr) {
+        sharedRegion = candidate;
+        sharedRegionAllocation = candidateAllocation;
+        candidateAllocation = nullptr;
+    }
     portEXIT_CRITICAL(&sharedMemoryMux);
-    if (candidate != nullptr) free_psram_heap("Unused duplicate shared PSRAM region", candidate);
+    if (candidateAllocation != nullptr) {
+        free_psram_heap("Unused duplicate shared PSRAM region", candidateAllocation);
+    }
     return true;
 }
 
@@ -166,9 +199,16 @@ void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize) {
     if (sharedPointer) {
         const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
         const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
-        if ((address - begin) >= sizeof(StbiSharedBlockHeader)) {
-            const StbiSharedBlockHeader* header = reinterpret_cast<const StbiSharedBlockHeader*>(static_cast<const uint8_t*>(ptr) - sizeof(StbiSharedBlockHeader));
-            if (header->magic == STBI_SHARED_BLOCK_MAGIC) { oldSize = header->size; validSharedHeader = true; }
+        const size_t userOffset = static_cast<size_t>(address - begin);
+        if (userOffset >= sizeof(StbiSharedBlockHeader) &&
+            (userOffset & (STBI_ALIGNMENT - 1)) == 0) {
+            const StbiSharedBlockHeader* header = reinterpret_cast<const StbiSharedBlockHeader*>(
+                static_cast<const uint8_t*>(ptr) - sizeof(StbiSharedBlockHeader));
+            if (header->magic == STBI_SHARED_BLOCK_MAGIC &&
+                header->size > 0 && header->size <= regionSize - userOffset) {
+                oldSize = header->size;
+                validSharedHeader = true;
+            }
         }
     }
     portEXIT_CRITICAL(&sharedMemoryMux);
@@ -197,9 +237,14 @@ void psram_free_shared_stbi_memory(void *ptr) {
  * Memory used in Aligning Step
  *******************************************************************/
 void *psram_reserve_shared_tmp_image_memory(void) {
+    return psram_reserve_shared_tmp_image_memory(static_cast<size_t>(IMAGE_SIZE));
+}
+
+void *psram_reserve_shared_tmp_image_memory(size_t requiredSize) {
     size_t regionSize = 0;
-    if (!getSharedRegionSize(&regionSize) || static_cast<size_t>(IMAGE_SIZE) > regionSize) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region");
+    if (requiredSize == 0 || !getSharedRegionSize(&regionSize) || requiredSize > regionSize) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region (" +
+            std::to_string(requiredSize) + " bytes requested)");
         return nullptr;
     }
     SharedMemoryUser currentUser;
@@ -212,11 +257,12 @@ void *psram_reserve_shared_tmp_image_memory(void) {
     }
     portEXIT_CRITICAL(&sharedMemoryMux);
     if (result == nullptr) {
-        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM unavailable for tmpImage (owner: " +
+        LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared PSRAM unavailable for tmpImage (" +
+            std::to_string(requiredSize) + " bytes requested; owner: " +
             std::string(sharedMemoryUserName(currentUser)) + ")");
         return nullptr;
     }
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(IMAGE_SIZE) + " bytes, use shared memory in PSRAM)...");
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(requiredSize) + " bytes, shared PSRAM)...");
     return result;
 }
 
@@ -254,12 +300,18 @@ void *psram_get_shared_tensor_arena_memory(void) {
 void *psram_get_shared_model_memory(void) {
     bool unavailable = false, duplicateClaim = false;
     void* result = nullptr;
+    size_t modelOffset = 0;
+    if (!getAlignedTensorArenaSize(&modelOffset)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid Tensor Arena size for model placement");
+        return nullptr;
+    }
     SharedMemoryUser currentUser;
     portENTER_CRITICAL(&sharedMemoryMux);
     currentUser = sharedMemoryUser;
-    if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
+    if (sharedRegion == nullptr || !tensorArenaClaimed ||
+        sharedMemoryUser != SharedMemoryUser::Digitization) unavailable = true;
     else if (modelMemoryClaimed) duplicateClaim = true;
-    else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + static_cast<size_t>(TENSOR_ARENA_SIZE); }
+    else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + modelOffset; }
     portEXIT_CRITICAL(&sharedMemoryMux);
     if (result == nullptr) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Model shared memory was claimed more than once" :
@@ -324,3 +376,57 @@ void free_psram_heap(std::string name, void *ptr) {
     LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
     heap_caps_free(ptr);
 }
+
+/*******************************************************************
+ * Internal SRAM heap wrappers
+ *******************************************************************/
+void *malloc_internal_heap(std::string name, size_t size, uint32_t caps) {
+    if (size == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal allocation for '" + name + "'");
+        return nullptr;
+    }
+    const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
+    void* ptr = heap_caps_malloc(size, internalCaps);
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
+    return ptr;
+}
+
+void *realloc_internal_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
+    if (size == 0) {
+        if (ptr != nullptr) {
+            LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
+            heap_caps_free(ptr);
+        }
+        return nullptr;
+    }
+    if (ptr == nullptr) return malloc_internal_heap(name, size, caps);
+    const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
+    void* resized = heap_caps_realloc(ptr, size, internalCaps);
+    if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
+    return resized;
+}
+
+void *calloc_internal_heap(std::string name, size_t n, size_t size, uint32_t caps) {
+    if (size != 0 && n > SIZE_MAX / size) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Internal calloc size overflow for '" + name + "'");
+        return nullptr;
+    }
+    if (n == 0 || size == 0) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal calloc for '" + name + "'");
+        return nullptr;
+    }
+    const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
+    void* ptr = heap_caps_calloc(n, size, internalCaps);
+    const size_t totalSize = n * size;
+    if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
+    else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
+    return ptr;
+}
+
+void free_internal_heap(std::string name, void *ptr) {
+    if (ptr == nullptr) return;
+    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
+    heap_caps_free(ptr);
+}

+ 5 - 0
code/components/jomjol_helper/psram.h

@@ -12,6 +12,7 @@ void *psram_reserve_shared_stbi_memory(size_t size);
 void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize);
 void psram_free_shared_stbi_memory(void *ptr);
 void *psram_reserve_shared_tmp_image_memory(void);
+void *psram_reserve_shared_tmp_image_memory(size_t requiredSize);
 void psram_free_shared_temp_image_memory(void);
 void *psram_get_shared_tensor_arena_memory(void);
 void *psram_get_shared_model_memory(void);
@@ -20,4 +21,8 @@ void *malloc_psram_heap(std::string name, size_t size, uint32_t caps);
 void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps);
 void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps);
 void free_psram_heap(std::string name, void *ptr);
+void *malloc_internal_heap(std::string name, size_t size, uint32_t caps = MALLOC_CAP_8BIT);
+void *realloc_internal_heap(std::string name, void *ptr, size_t size, uint32_t caps = MALLOC_CAP_8BIT);
+void *calloc_internal_heap(std::string name, size_t n, size_t size, uint32_t caps = MALLOC_CAP_8BIT);
+void free_internal_heap(std::string name, void *ptr);
 #endif // PSRAM_h

+ 29 - 4
code/components/jomjol_image_proc/CImageBasis.cpp

@@ -242,18 +242,18 @@ esp_err_t CImageBasis::SendJPGtoHTTP(httpd_req_t *_req, const int quality)
     if (_req == nullptr || !ImageOkay()) return ESP_FAIL;
     SendJPGHTTP send;
     send.req = _req; send.res = ESP_OK; send.size = 0;
-    send.buf = static_cast<char*>(malloc_psram_heap("JPEG HTTP stream buffer", HTTP_BUFFER_SENT, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
+    send.buf = static_cast<char*>(malloc_internal_heap("JPEG HTTP stream buffer", HTTP_BUFFER_SENT, MALLOC_CAP_8BIT));
     if (send.buf == nullptr) return ESP_ERR_NO_MEM;
     uint8_t* image = RGBImageLock();
     if (image == nullptr) {
-        free_psram_heap("JPEG HTTP stream buffer", send.buf);
+        free_internal_heap("JPEG HTTP stream buffer", send.buf);
         return ESP_FAIL;
     }
     const int encoded = stbi_write_jpg_to_func(writejpgtohttphelp, &send, width, height, channels, image, quality);
     if (!encoded && send.res == ESP_OK) send.res = ESP_FAIL;
     flushJPGHTTPBuffer(&send);
     RGBImageRelease();
-    free_psram_heap("JPEG HTTP stream buffer", send.buf);
+    free_internal_heap("JPEG HTTP stream buffer", send.buf);
     return send.res;
 }
 
@@ -513,6 +513,19 @@ bool CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
         return false;
     }
 
+    // tmpImage is used for camera frames. Inspect dimensions before decoding so
+    // an unexpected high-resolution JPEG cannot allocate a large temporary buffer.
+    if (name == "tmpImage") {
+        int inputWidth = 0, inputHeight = 0, inputChannels = 0;
+        if (!stbi_info_from_memory(_buffer, len, &inputWidth, &inputHeight, &inputChannels) ||
+            inputWidth <= 0 || inputHeight <= 0 ||
+            inputWidth > CAMERA_MAX_FRAME_WIDTH || inputHeight > CAMERA_MAX_FRAME_HEIGHT) {
+            LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
+                "LoadFromMemory: tmpImage JPEG exceeds the VGA limit or has invalid dimensions");
+            return false;
+        }
+    }
+
     int newWidth = 0, newHeight = 0, sourceChannels = 0;
     uint8_t* decoded = stbi_load_from_memory(_buffer, len, &newWidth, &newHeight,
                                               &sourceChannels, STBI_rgb);
@@ -604,6 +617,16 @@ CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CImageBasis-Copyfrom: invalid source dimensions");
         return;
     }
+    if (name == "tmpImage" &&
+        (_copyfrom->width > CAMERA_MAX_FRAME_WIDTH ||
+         _copyfrom->height > CAMERA_MAX_FRAME_HEIGHT ||
+         _copyfrom->channels != 3)) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
+            "CImageBasis-Copyfrom: tmpImage must be RGB and must not exceed the VGA limit (" +
+            std::to_string(_copyfrom->width) + "x" + std::to_string(_copyfrom->height) +
+            ", channels: " + std::to_string(_copyfrom->channels) + ")");
+        return;
+    }
     width = _copyfrom->width;
     height = _copyfrom->height;
     channels = _copyfrom->channels;
@@ -620,7 +643,9 @@ CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
     }
 
     if (name == "tmpImage") {
-        rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory());
+        // tmpImage is an in-place VGA workspace. Do not silently add a second,
+        // larger PSRAM allocation when the shared workspace cannot be leased.
+        rgb_image = static_cast<uint8_t*>(psram_reserve_shared_tmp_image_memory(imageSize));
         ownsSharedTempImageLease = (rgb_image != NULL);
         memsize = (rgb_image != NULL) ? static_cast<int>(imageSize) : 0;
     } else {

+ 102 - 43
code/components/jomjol_mqtt/interface_mqtt.cpp

@@ -11,6 +11,9 @@
 #include "MainFlowControl.h"
 #include "cJSON.h"
 #include "../../include/defines.h"
+#include <mutex>
+#include <new>
+#include <utility>
 
 #if DEBUG_DETAIL_ON
 #include "esp_timer.h"
@@ -18,8 +21,10 @@
 
 static const char *TAG = "MQTT IF";
 
-std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;  
+std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
 std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
+static std::mutex connectFunctionMutex;
+static std::mutex subscribeFunctionMutex;
 
 int failedOnRound = -1;
 int MQTTReconnectCnt = 0;
@@ -136,13 +141,18 @@ static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
             ESP_LOGD(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
             ESP_LOGD(TAG, "DATA=%.*s", event->data_len, event->data);
             topic.assign(event->topic, event->topic_len);
-            if (subscribeFunktionMap != NULL) {
-                if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
-                    ESP_LOGD(TAG, "call subcribe function for topic %s", topic.c_str());
-                    (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
+            {
+                // Keep callback targets alive until invocation finishes. Unregister waits for this lock.
+                std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
+                if (subscribeFunktionMap != NULL) {
+                    const auto handler = subscribeFunktionMap->find(topic);
+                    if (handler != subscribeFunktionMap->end()) {
+                        ESP_LOGD(TAG, "call subcribe function for topic %s", topic.c_str());
+                        handler->second(topic, event->data, event->data_len);
+                    }
+                } else {
+                    ESP_LOGW(TAG, "no handler available\r\n");
                 }
-            } else {
-                ESP_LOGW(TAG, "no handler available\r\n");
             }
             break;
         
@@ -345,6 +355,9 @@ int MQTT_Init() {
         if (ret != ESP_OK)
         {
             LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
+            esp_mqtt_client_destroy(client);
+            client = NULL;
+            mqtt_connected = false;
             mqtt_initialized = false;
             return -1;
         }
@@ -356,6 +369,9 @@ int MQTT_Init() {
         if (ret != ESP_OK)
         {
             LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
+            esp_mqtt_client_destroy(client);
+            client = NULL;
+            mqtt_connected = false;
             mqtt_initialized = false;
             return -1;
         }
@@ -412,28 +428,33 @@ bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
     //ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
     //example: {"numbersname": "main", "value": 12345.1234567}
 
-    if (_data_len > 0) {    // Check if data length > 0
-        cJSON *jsonData = cJSON_Parse(_data);
+    if (_data != NULL && _data_len > 0) {
+        // MQTT event payloads are length-delimited and are not guaranteed to be NUL-terminated.
+        cJSON *jsonData = cJSON_ParseWithLength(_data, static_cast<size_t>(_data_len));
+        if (jsonData == NULL) {
+            LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: invalid JSON payload");
+            return ESP_FAIL;
+        }
+
         cJSON *numbersname = cJSON_GetObjectItemCaseSensitive(jsonData, "numbersname");
         cJSON *value = cJSON_GetObjectItemCaseSensitive(jsonData, "value");
-
-        if (cJSON_IsString(numbersname) && (numbersname->valuestring != NULL)) {    // Check if numbersname is valid
-            if (cJSON_IsNumber(value)) {   // Check if value is a number
-                LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) + 
-                                                                                         ", value: " + std::to_string(value->valuedouble));
-                if (flowctrl.UpdatePrevalue(std::to_string(value->valuedouble), std::string(numbersname->valuestring), true)) {
-                    cJSON_Delete(jsonData);
-                    return ESP_OK;
-                }
-            }
-            else {
+        bool updateOkay = false;
+
+        if (cJSON_IsString(numbersname) && numbersname->valuestring != NULL) {
+            if (cJSON_IsNumber(value)) {
+                LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) +
+                                                         ", value: " + std::to_string(value->valuedouble));
+                updateOkay = flowctrl.UpdatePrevalue(std::to_string(value->valuedouble),
+                                                     std::string(numbersname->valuestring), true);
+            } else {
                 LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: value not a valid number (\"value\": 12345.12345)");
             }
-        }
-        else {
+        } else {
             LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: numbersname not a valid string (\"numbersname\": \"main\")");
         }
+
         cJSON_Delete(jsonData);
+        return updateOkay;
     }
     else {
         LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: handler called, but no data received");
@@ -446,10 +467,14 @@ void MQTTconnected(){
     if (mqtt_connected) {
         LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
         
-        if (connectFunktionMap != NULL) {
-            for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
-                it->second();
-                ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
+        {
+            // Callback owners cannot be destroyed until a connect callback has returned.
+            std::lock_guard<std::mutex> lock(connectFunctionMutex);
+            if (connectFunktionMap != NULL) {
+                for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
+                    it->second();
+                    ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
+                }
             }
         }
 
@@ -462,10 +487,13 @@ void MQTTconnected(){
         std::function<bool(std::string topic, char* data, int data_len)> subHandler2 = mqtt_handler_set_prevalue;     
         MQTTregisterSubscribeFunction(maintopic + "/ctrl/set_prevalue", subHandler2);      // subcribe to maintopic/ctrl/set_prevalue
 
-       if (subscribeFunktionMap != NULL) {
-            for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
-                int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
-                LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe successful");
+       {
+            std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
+            if (subscribeFunktionMap != NULL && client != NULL) {
+                for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
+                    const int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
+                    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe requested, msg_id=" + std::to_string(msg_id));
+                }
             }
         }
 
@@ -477,47 +505,78 @@ void MQTTconnected(){
 }
 
 void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
-    ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
+    ESP_LOGD(TAG, "MQTTregisterConnectFunction %s\r\n", name.c_str());
+    std::lock_guard<std::mutex> lock(connectFunctionMutex);
     if (connectFunktionMap == NULL) {
-        connectFunktionMap = new std::map<std::string, std::function<void()>>();
+        connectFunktionMap = new (std::nothrow) std::map<std::string, std::function<void()>>();
+        if (connectFunktionMap == NULL) {
+            ESP_LOGE(TAG, "Unable to allocate MQTT connect callback map");
+            return;
+        }
     }
 
-    if ((*connectFunktionMap)[name] != NULL) {
-        ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
+    if (connectFunktionMap->find(name) != connectFunktionMap->end()) {
+        ESP_LOGW(TAG, "connect function %s already registered", name.c_str());
         return;
     }
 
-    (*connectFunktionMap)[name] = func;
-
+    connectFunktionMap->emplace(name, std::move(func));
     if (mqtt_connected) {
-        func();
+        connectFunktionMap->find(name)->second();
     }
 }
 
 void MQTTunregisterConnectFunction(std::string name){
-    ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
-    if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
+    ESP_LOGD(TAG, "unregisterConnectFunction %s\r\n", name.c_str());
+    std::lock_guard<std::mutex> lock(connectFunctionMutex);
+    if (connectFunktionMap != NULL) {
         connectFunktionMap->erase(name);
+        if (connectFunktionMap->empty()) {
+            delete connectFunktionMap;
+            connectFunktionMap = NULL;
+        }
     }
 }
 
 void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
     ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
+    std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
     if (subscribeFunktionMap == NULL) {
-        subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
+        subscribeFunktionMap = new (std::nothrow) std::map<std::string, std::function<bool(std::string, char*, int)>>();
+        if (subscribeFunktionMap == NULL) {
+            ESP_LOGE(TAG, "Unable to allocate MQTT subscription callback map");
+            return;
+        }
     }
 
-    if ((*subscribeFunktionMap)[topic] != NULL) {
+    if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
         ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
         return;
     }
+    subscribeFunktionMap->emplace(topic, std::move(func));
+}
+
+void MQTTunregisterSubscribeFunction(std::string topic) {
+    std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
+    if (subscribeFunktionMap == NULL) return;
+    const auto handler = subscribeFunktionMap->find(topic);
+    if (handler == subscribeFunktionMap->end()) return;
 
-    (*subscribeFunktionMap)[topic] = func;
+    if (mqtt_connected && client != NULL) {
+        const int msg_id = esp_mqtt_client_unsubscribe(client, topic.c_str());
+        ESP_LOGD(TAG, "topic %s unsubscribe requested, msg_id=%d", topic.c_str(), msg_id);
+    }
+    subscribeFunktionMap->erase(handler);
+    if (subscribeFunktionMap->empty()) {
+        delete subscribeFunktionMap;
+        subscribeFunktionMap = NULL;
+    }
 }
 
 void MQTTdestroySubscribeFunction(){
+    std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
     if (subscribeFunktionMap != NULL) {
-        if (mqtt_connected) {
+        if (mqtt_connected && client != NULL) {
             for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
                 int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
                 ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);

+ 1 - 0
code/components/jomjol_mqtt/interface_mqtt.h

@@ -24,6 +24,7 @@ bool getMQTTisConnected();
 void MQTTregisterConnectFunction(std::string name, std::function<void()> func);
 void MQTTunregisterConnectFunction(std::string name);
 void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func);
+void MQTTunregisterSubscribeFunction(std::string topic);
 void MQTTdestroySubscribeFunction();
 void MQTTconnected();
 

+ 0 - 12
code/components/jomjol_mqtt/mqtt_outbox.c

@@ -134,18 +134,6 @@ esp_err_t outbox_delete_item(outbox_handle_t outbox, outbox_item_handle_t item_t
     return ESP_FAIL;
 }
 
-uint8_t *outbox_item_get_data(outbox_item_handle_t item,  size_t *len, uint16_t *msg_id, int *msg_type, int *qos)
-{
-    if (item) {
-        *len = item->len;
-        *msg_id = item->msg_id;
-        *msg_type = item->msg_type;
-        *qos = item->msg_qos;
-        return (uint8_t *)item->buffer;
-    }
-    return NULL;
-}
-
 esp_err_t outbox_delete(outbox_handle_t outbox, int msg_id, int msg_type)
 {
     if (outbox == NULL) { return ESP_FAIL; }

+ 3 - 1
code/include/defines.h

@@ -194,7 +194,9 @@
 /////////////////////////////////////////////
 #define MAX_MODEL_SIZE            (unsigned int)(1.3 * 1024 * 1024) // Space for the currently largest model (1.1 MB) + some spare
 #define TENSOR_ARENA_SIZE         800 * 1024 // Space for the Tensor Arena, (819200 Bytes)
-#define IMAGE_SIZE                640 * 480 * 3 // Space for a extracted image (921600 Bytes)
+#define CAMERA_MAX_FRAME_WIDTH    640
+#define CAMERA_MAX_FRAME_HEIGHT   480
+#define IMAGE_SIZE                (CAMERA_MAX_FRAME_WIDTH * CAMERA_MAX_FRAME_HEIGHT * 3) // VGA RGB buffer (921600 Bytes)
 /////////////////////////////////////////////
 ////      Conditionnal definitions       ////
 /////////////////////////////////////////////