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

Merge pull request #4211 from SybexX/develop

Improve flow controls and HTTP stability on ESP32-CAM
SybexXx 23 часов назад
Родитель
Сommit
27d34d4bb0

+ 1 - 1
code/components/jomjol_flowcontroll/ClassFlowControll.cpp

@@ -365,7 +365,7 @@ void ClassFlowControll::InitFlow(std::string config)
         // printf("Name: %s\n", cfc->name().c_str());
 	    
         if (cfc) {
-            ESP_LOGE(TAG, "Start ReadParameter (%s)", line.c_str());
+            ESP_LOGI(TAG, "Start ReadParameter (%s)", line.c_str());
             cfc->ReadParameter(pFile, line);
         }
         else {

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

@@ -1031,7 +1031,7 @@ bool ClassFlowPostProcessing::doFlow(string zwtime) {
                     NUMBERS[j]->timeStampLastValue = imagetime;
 
                     string _zw = NUMBERS[j]->name + ": Raw: " + NUMBERS[j]->ReturnRawValue + ", Value: " + NUMBERS[j]->ReturnValue + ", Status: " + NUMBERS[j]->ErrorMessageText;
-                    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _zw);
+                    LogFile.WriteToFile(ESP_LOG_WARN, TAG, _zw);
                     WriteDataLog(j);
                     continue;
                 }
@@ -1068,7 +1068,7 @@ bool ClassFlowPostProcessing::doFlow(string zwtime) {
                     NUMBERS[j]->timeStampLastValue = imagetime;
 
                     string _zw = NUMBERS[j]->name + ": Raw: " + NUMBERS[j]->ReturnRawValue + ", Value: " + NUMBERS[j]->ReturnValue + ", Status: " + NUMBERS[j]->ErrorMessageText;
-                    LogFile.WriteToFile(ESP_LOG_ERROR, TAG, _zw);
+                    LogFile.WriteToFile(ESP_LOG_WARN, TAG, _zw);
                     WriteDataLog(j);
                     continue;
                 }

+ 213 - 11
code/components/jomjol_flowcontroll/MainFlowControl.cpp

@@ -6,6 +6,8 @@
 #include "string.h"
 #include "esp_log.h"
 #include <esp_timer.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
 
 #include <iomanip>
 #include <sstream>
@@ -48,6 +50,110 @@ bool bTaskAutoFlowCreated = false;
 bool bFlowInitialized = false;
 bool flowisrunning = false;
 
+// Flow control state is shared by the HTTP server task and the flow task (different cores).
+static portMUX_TYPE flowControlMux = portMUX_INITIALIZER_UNLOCKED;
+static bool flowPauseRequested = false;
+static bool flowPaused = false;
+static bool flowManualRunRequested = false;
+
+static bool IsFlowRunning()
+{
+    bool running;
+    portENTER_CRITICAL(&flowControlMux);
+    running = flowisrunning;
+    portEXIT_CRITICAL(&flowControlMux);
+    return running;
+}
+
+static void SetFlowRunning(bool running)
+{
+    portENTER_CRITICAL(&flowControlMux);
+    flowisrunning = running;
+    portEXIT_CRITICAL(&flowControlMux);
+}
+
+static bool IsFlowPauseRequested()
+{
+    bool requested;
+    portENTER_CRITICAL(&flowControlMux);
+    requested = flowPauseRequested;
+    portEXIT_CRITICAL(&flowControlMux);
+    return requested;
+}
+
+static bool IsFlowPaused()
+{
+    bool paused;
+    portENTER_CRITICAL(&flowControlMux);
+    paused = flowPaused;
+    portEXIT_CRITICAL(&flowControlMux);
+    return paused;
+}
+
+static void RequestFlowPause()
+{
+    portENTER_CRITICAL(&flowControlMux);
+    flowPauseRequested = true;
+    portEXIT_CRITICAL(&flowControlMux);
+}
+
+static void RequestFlowResume()
+{
+    portENTER_CRITICAL(&flowControlMux);
+    flowPauseRequested = false;
+    flowPaused = false;
+    flowManualRunRequested = false;
+    portEXIT_CRITICAL(&flowControlMux);
+}
+
+static bool QueueManualRunWhilePaused()
+{
+    bool queued = false;
+    portENTER_CRITICAL(&flowControlMux);
+    if (flowPauseRequested && !flowisrunning)
+    {
+        flowManualRunRequested = true;
+        queued = true;
+    }
+    portEXIT_CRITICAL(&flowControlMux);
+    return queued;
+}
+
+// Called only by task_autodoFlow at the start of each scheduling iteration.
+// A queued manual run is allowed through once, but the automatic pause remains set.
+static bool UpdateFlowPauseStateForTask()
+{
+    bool shouldPause = false;
+    portENTER_CRITICAL(&flowControlMux);
+    if (flowPauseRequested && flowManualRunRequested && !flowisrunning)
+    {
+        flowManualRunRequested = false;
+        flowPaused = false;
+    }
+    else if (flowPauseRequested)
+    {
+        flowPaused = true;
+        shouldPause = true;
+    }
+    else
+    {
+        flowPaused = false;
+        flowManualRunRequested = false;
+    }
+    portEXIT_CRITICAL(&flowControlMux);
+    return shouldPause;
+}
+
+static void ResetFlowControlState()
+{
+    portENTER_CRITICAL(&flowControlMux);
+    flowPauseRequested = false;
+    flowPaused = false;
+    flowManualRunRequested = false;
+    flowisrunning = false;
+    portEXIT_CRITICAL(&flowControlMux);
+}
+
 long auto_interval = 0;
 bool autostartIsEnabled = false;
 
@@ -141,9 +247,9 @@ bool doflow(void)
 {
     std::string zw_time = getCurrentTimeString(LOGFILE_TIME_FORMAT);
     ESP_LOGD(TAG, "doflow - start %s", zw_time.c_str());
-    flowisrunning = true;
+    SetFlowRunning(true);
     flowctrl.doFlow(zw_time);
-    flowisrunning = false;
+    SetFlowRunning(false);
 
 #ifdef DEBUG_DETAIL_ON
     ESP_LOGD(TAG, "doflow - end %s", zw_time.c_str());
@@ -263,12 +369,27 @@ esp_err_t handler_flow_start(httpd_req_t *req)
 
     httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
 
-    if (autostartIsEnabled)
+    if (autostartIsEnabled && bTaskAutoFlowCreated && bFlowInitialized)
     {
-        xTaskAbortDelay(xHandletask_autodoFlow); // Delay will be aborted if task is in blocked (waiting) state. If task is already running, no action
-        LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by REST API /flow_start");
-        const char *resp_str = "The flow is going to be started immediately or is already running";
-        httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+        if (IsFlowRunning())
+        {
+            const char *resp_str = "A flow round is already running";
+            httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+        }
+        else if (IsFlowPauseRequested())
+        {
+            QueueManualRunWhilePaused();
+            if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
+            const char *resp_str = "One manual round is triggered; the automatic flow will remain paused afterwards";
+            httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+        }
+        else
+        {
+            if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
+            LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by REST API /flow_start");
+            const char *resp_str = "The flow is going to be started immediately";
+            httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+        }
     }
     else
     {
@@ -283,6 +404,53 @@ esp_err_t handler_flow_start(httpd_req_t *req)
     return ESP_OK;
 }
 
+esp_err_t handler_flow_pause(httpd_req_t *req)
+{
+    httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
+
+    if (!autostartIsEnabled || !bTaskAutoFlowCreated || !bFlowInitialized)
+    {
+        httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow is not active and cannot be paused");
+        return ESP_FAIL;
+    }
+
+    if (IsFlowPaused())
+    {
+        const char *resp_str = "Flow is already paused";
+        httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+        return ESP_OK;
+    }
+
+    RequestFlowPause();
+    if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
+
+    const char *resp_str = IsFlowRunning()
+        ? "Pause requested. The current round will finish before the flow pauses"
+        : "Pause requested. No further automatic round will start";
+    httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Flow pause requested through Web-UI");
+    return ESP_OK;
+}
+
+esp_err_t handler_flow_resume(httpd_req_t *req)
+{
+    httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
+
+    if (!autostartIsEnabled || !bTaskAutoFlowCreated || !bFlowInitialized)
+    {
+        httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Flow is not active and cannot be resumed");
+        return ESP_FAIL;
+    }
+
+    RequestFlowResume();
+    if (xHandletask_autodoFlow != NULL) xTaskAbortDelay(xHandletask_autodoFlow);
+
+    const char *resp_str = "Automatic flow resumed. The next round starts immediately";
+    httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
+    LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Automatic flow resumed through Web-UI");
+    return ESP_OK;
+}
+
 #ifdef ENABLE_MQTT
 esp_err_t MQTTCtrlFlowStart(std::string _topic)
 {
@@ -294,7 +462,15 @@ esp_err_t MQTTCtrlFlowStart(std::string _topic)
 
     if (autostartIsEnabled)
     {
-        xTaskAbortDelay(xHandletask_autodoFlow); // Delay will be aborted if task is in blocked (waiting) state. If task is already running, no action
+        if (IsFlowPauseRequested())
+        {
+            if (!IsFlowRunning() && QueueManualRunWhilePaused() && xHandletask_autodoFlow != NULL)
+                xTaskAbortDelay(xHandletask_autodoFlow);
+        }
+        else if (xHandletask_autodoFlow != NULL)
+        {
+            xTaskAbortDelay(xHandletask_autodoFlow); // Start immediately if the flow task is in its interval delay.
+        }
         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Flow start triggered by MQTT topic " + _topic);
     }
     else
@@ -776,7 +952,7 @@ esp_err_t handler_editflow(httpd_req_t *req)
 
         std::string out2 = out.substr(0, out.length() - 4) + "_org.jpg";
 
-        if ((flowctrl.SetupModeActive || (flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
+        if ((flowctrl.SetupModeActive || IsFlowPaused() || (flowctrl.getActStatus() == std::string("Flow finished"))) && psram_init_shared_memory_for_take_image_step())
         {
             LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Taking image for Alignment Mark Update...");
 
@@ -1556,6 +1732,17 @@ void task_autodoFlow(void *pvParameter)
 
     while (autostartIsEnabled)
     {
+        if (UpdateFlowPauseStateForTask())
+        {
+            if (flowctrl.getActStatus() != "Flow paused")
+            {
+                flowctrl.setActStatus("Flow paused");
+                LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Flow paused; waiting for resume or one manual round");
+            }
+            vTaskDelay(pdMS_TO_TICKS(250));
+            continue;
+        }
+
         LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "----------------------------------------------------------------"); // Clear separation between runs
         time_t roundStartTime = getUpTime();
 
@@ -1564,7 +1751,7 @@ void task_autodoFlow(void *pvParameter)
 
         fr_start = esp_timer_get_time();
 
-        if (flowisrunning)
+        if (IsFlowRunning())
         {
 #ifdef DEBUG_DETAIL_ON
             ESP_LOGD(TAG, "Autoflow: doFlow is already running!");
@@ -1575,7 +1762,6 @@ void task_autodoFlow(void *pvParameter)
 #ifdef DEBUG_DETAIL_ON
             ESP_LOGD(TAG, "Autoflow: doFlow is started");
 #endif
-            flowisrunning = true;
             doflow();
 #ifdef DEBUG_DETAIL_ON
             ESP_LOGD(TAG, "Remove older log files");
@@ -1612,6 +1798,11 @@ void task_autodoFlow(void *pvParameter)
 
         fr_delta_ms = (esp_timer_get_time() - fr_start) / 1000;
 
+        if (IsFlowPauseRequested())
+        {
+            continue; // Finish the current round, then enter the paused state at the top of the loop.
+        }
+
         if (auto_interval > fr_delta_ms)
         {
             const TickType_t xDelay = (auto_interval - fr_delta_ms) / portTICK_PERIOD_MS;
@@ -1635,6 +1826,7 @@ void task_autodoFlow(void *pvParameter)
 void InitializeFlowTask(void)
 {
     BaseType_t xReturned;
+    ResetFlowControlState();
 
     ESP_LOGD(TAG, "getESPHeapInfo: %s", getESPHeapInfo().c_str());
 
@@ -1678,6 +1870,16 @@ void register_server_main_flow_task_uri(httpd_handle_t server)
     camuri.user_ctx = (void *)"Flow Start";
     httpd_register_uri_handler(server, &camuri);
 
+    camuri.uri = "/flow_pause";
+    camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_flow_pause);
+    camuri.user_ctx = (void *)"Flow Pause";
+    httpd_register_uri_handler(server, &camuri);
+
+    camuri.uri = "/flow_resume";
+    camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_flow_resume);
+    camuri.user_ctx = (void *)"Flow Resume";
+    httpd_register_uri_handler(server, &camuri);
+
     camuri.uri = "/statusflow.html";
     camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_statusflow);
     camuri.user_ctx = (void *)"Light Off";

+ 2 - 2
code/main/server_main.cpp

@@ -462,8 +462,8 @@ httpd_handle_t start_webserver(void)
     config.core_id = 1; // previously -> 2023-01-02: 0, 2022-12-11: tskNO_AFFINITY;
     config.server_port = 80;
     config.ctrl_port = 32768;
-    config.max_open_sockets = 7; // Tested: allow more simultaneous Web-UI connections
-    config.max_uri_handlers = 41; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
+    config.max_open_sockets = 5; // Conservative HTTP client limit; lwIP socket pool configured separately
+    config.max_uri_handlers = 43; // Make sure this fits all URI handlers. Memory usage in bytes: 6*max_uri_handlers
     config.max_resp_headers = 8;                        
     config.backlog_conn = 5;                        
     config.lru_purge_enable = true; // this cuts old connections if new ones are needed.               

+ 3 - 0
code/sdkconfig.defaults

@@ -110,6 +110,9 @@ CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
 CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024
 CONFIG_HTTPD_PURGE_BUF_LEN=16
 
+# Keep the lwIP socket pool within the ESP32 stability limit observed in testing
+CONFIG_LWIP_MAX_SOCKETS=12
+
 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=16
 CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM=16
 

+ 4 - 4
sd-card/html/edit_alignment.html

@@ -285,7 +285,7 @@
 
             async function task() {
                 while (true) {
-                    if (durchlaufe > 10) {
+                    if (durchlaufe > 30) {
                         document.getElementById("overlay").style.display = "none";
                         firework.launch('Enhancing Image Contrast aborted, timeout!', 'danger', 5000);
                         return;
@@ -316,7 +316,7 @@
                         }
                         catch (error){}
 
-                        document.getElementById("overlaytext").innerHTML = "Device is busy, waiting until the Digitization Round got completed (this can take several minutes)...<br><br>Current step: " + xhttp.responseText;
+                        document.getElementById("overlaytext").innerHTML = "Device is busy, waiting for the current round to finish and the flow to pause...<br><br>Current step: " + xhttp.responseText;
                         console.log("Device is busy, waiting 5s then checking again...");
                         await sleep(5000);
                     }
@@ -478,7 +478,7 @@
 
             async function task() {
                 while (true) {
-                    if (durchlaufe > 10) {
+                    if (durchlaufe > 30) {
                         document.getElementById("overlay").style.display = "none";
                         firework.launch('Updating marker aborted, timeout!', 'danger', 5000);
                         return;
@@ -517,7 +517,7 @@
                         }
                         catch (error){}
 
-                        document.getElementById("overlaytext").innerHTML = "Device is busy, waiting until the Digitization Round got completed (this can take several minutes)...<br><br>Current step: " + xhttp.responseText;
+                        document.getElementById("overlaytext").innerHTML = "Device is busy, waiting for the current round to finish and the flow to pause...<br><br>Current step: " + xhttp.responseText;
                         console.log("Device is busy, waiting 5s then checking again...");
                         await sleep(5000);
                     }

+ 27 - 23
sd-card/html/index.html

@@ -158,10 +158,12 @@
             <li><a href="https://jomjol.github.io/AI-on-the-edge-device-docs/" target="_blank">Help</a></li>
         </ul>
     </li>
-    <li id="ManualControl" style="display:none;"><a>Manual Control <i class="arrow down"></i></a> <!-- Workaround: Hide menu if no entry is available -->
+    <li id="ManualControl"><a>Manual Control <i class="arrow down"></i></a>
         <ul class="submenu" style="width: 300px">
-            <li><a href="#" onclick="flow_start()">Start Round</a></li>
-            <li id="HASendDiscovery" style="width: 300px" style="display:none;"><a href="#" onclick="HA_send_discovery()">Resend Homeassistant Discovery</a></li>
+            <li><a href="#" onclick="flow_pause()">Pause after current round</a></li>
+            <li><a href="#" onclick="flow_resume()">Resume automatic flow</a></li>
+            <li><a href="#" onclick="flow_start()">Start one round now</a></li>
+            <li id="HASendDiscovery" style="width: 300px; display:none;"><a href="#" onclick="HA_send_discovery()">Resend Homeassistant Discovery</a></li>
         </ul>
     </li>
   </ul>
@@ -206,26 +208,29 @@
     document.getElementById('maincontent').src = getCookie("page");
 
     
+    function call_flow_control(endpoint) {
+        var xhttp = new XMLHttpRequest();
+        xhttp.onreadystatechange = function() {
+            if (this.readyState == 4) {
+                var okay = this.status >= 200 && this.status < 300;
+                firework.launch(xhttp.responseText || (okay ? "Flow command accepted" : "Flow command failed"),
+                                okay ? "success" : "danger", 5000);
+            }
+        };
+        xhttp.open("GET", getDomainname() + endpoint, true);
+        xhttp.send();
+    }
+
     function flow_start() {
-    var url = getDomainname() + '/flow_start'; 
-		var xhttp = new XMLHttpRequest();
-		xhttp.onreadystatechange = function() {
-			if (this.readyState == 4 && this.status == 200) {
-                firework.launch(xhttp.responseText, 'success', 5000);
-			    /*if (xhttp.responseText.substring(0,3) == "001") {
-					firework.launch('Flow start triggered', 'success', 5000);
-                    window.location.reload();
-				}
-				else if (xhttp.responseText.substring(0,3) == "002") {
-					firework.launch('Flow start scheduled. Start after round is completed', 'success', 5000);
-				}
-				else if (xhttp.responseText.substring(0,3) == "099") {
-					firework.launch('Flow start triggered, but start not possible (no flow task available)', 'danger', 5000);
-                }*/
-			}
-		}
-		xhttp.open("GET", url, true);
-		xhttp.send();
+        call_flow_control('/flow_start');
+    }
+
+    function flow_pause() {
+        call_flow_control('/flow_pause');
+    }
+
+    function flow_resume() {
+        call_flow_control('/flow_resume');
     }
     
 
@@ -236,7 +241,6 @@
         param = getConfigParameters();
 		
 		if (category["MQTT"]["enabled"] && param["MQTT"]["HomeassistantDiscovery"].value1 == "true") {
-            document.getElementById("ManualControl").style.display="";
             document.getElementById("HASendDiscovery").style.display="";
         }
 	}