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

Add safe pause and one-shot flow controls

SybexXx 1 день назад
Родитель
Сommit
aeb28dac14
1 измененных файлов с 213 добавлено и 11 удалено
  1. 213 11
      code/components/jomjol_flowcontroll/MainFlowControl.cpp

+ 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";