Sfoglia il codice sorgente

Use per-handler GPIO event queue and graceful worker shutdown

SybexXx 3 giorni fa
parent
commit
87f48c593c
1 ha cambiato i file con 128 aggiunte e 75 eliminazioni
  1. 128 75
      code/components/jomjol_controlGPIO/server_GPIO.cpp

+ 128 - 75
code/components/jomjol_controlGPIO/server_GPIO.cpp

@@ -31,7 +31,6 @@
 #include "basic_auth.h"
 
 static const char *TAG = "GPIO";
-QueueHandle_t gpio_queue_handle = NULL;
 
 static uint8_t requiredCapabilitiesForPinMode(gpio_pin_mode_t mode)
 {
@@ -90,34 +89,22 @@ GpioPin::~GpioPin()
     gpio_reset_pin(_gpio);
 }
 
-static void IRAM_ATTR gpio_isr_handler(void* arg)
+static void IRAM_ATTR gpio_isr_handler(void *arg)
 {
-    GpioResult gpioResult;
-    gpioResult.gpio = *(gpio_num_t*) arg;
-    gpioResult.value = gpio_get_level(gpioResult.gpio);
-    BaseType_t ContextSwitchRequest = pdFALSE;
- 
-    xQueueSendToBackFromISR(gpio_queue_handle,(void*)&gpioResult,&ContextSwitchRequest);
-   
-    if(ContextSwitchRequest){
-        taskYIELD();
-    }
-}
-
-static void gpioHandlerTask(void *arg) {
-    ESP_LOGD(TAG,"start interrupt task");
-    while(1){
-        if(uxQueueMessagesWaiting(gpio_queue_handle)){
-            while(uxQueueMessagesWaiting(gpio_queue_handle)){
-                GpioResult gpioResult;
-                xQueueReceive(gpio_queue_handle,(void*)&gpioResult,10);
-                ESP_LOGD(TAG,"gpio: %d state: %d", gpioResult.gpio, gpioResult.value);
-                ((GpioHandler*)arg)->gpioInterrupt(&gpioResult);
-            }  
-        }
+    GpioIsrContext *context = static_cast<GpioIsrContext *>(arg);
+    if (context == NULL || context->eventQueue == NULL) {
+        return;
+    }
 
-        ((GpioHandler*)arg)->taskHandler();
-        vTaskDelay(pdMS_TO_TICKS(1000));
+    GpioResult result = {};
+    result.gpio = context->gpio;
+    result.value = gpio_get_level(context->gpio);
+    result.stopEvent = false;
+
+    BaseType_t higherPriorityTaskWoken = pdFALSE;
+    if (xQueueSendFromISR(context->eventQueue, &result, &higherPriorityTaskWoken) == pdPASS &&
+        higherPriorityTaskWoken == pdTRUE) {
+        portYIELD_FROM_ISR();
     }
 }
 
@@ -132,8 +119,13 @@ void GpioPin::gpioInterrupt(int value) {
     currentState = value;
 }
 
-bool GpioPin::init()
+bool GpioPin::init(QueueHandle_t eventQueue)
 {
+    if (_interruptType != GPIO_INTR_DISABLE && eventQueue == NULL) {
+        ESP_LOGE(TAG, "No event queue available for GPIO%d interrupt", static_cast<int>(_gpio));
+        return false;
+    }
+
     gpio_config_t io_conf = {};
     io_conf.intr_type = _interruptType;
     io_conf.mode = (_mode == GPIO_PIN_MODE_OUTPUT) ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT;
@@ -151,7 +143,9 @@ bool GpioPin::init()
     if (_interruptType != GPIO_INTR_DISABLE) {
         //hook isr handler for specific gpio pin
         ESP_LOGD(TAG, "GpioPin::init add isr handler for GPIO %d", _gpio);
-        const esp_err_t isrResult = gpio_isr_handler_add(_gpio, gpio_isr_handler, (void*)&_gpio);
+        _isrContext.eventQueue = eventQueue;
+        _isrContext.gpio = _gpio;
+        const esp_err_t isrResult = gpio_isr_handler_add(_gpio, gpio_isr_handler, &_isrContext);
         if (isrResult != ESP_OK) {
             ESP_LOGE(TAG, "gpio_isr_handler_add failed for GPIO%d: %s",
                      static_cast<int>(_gpio), esp_err_to_name(isrResult));
@@ -239,12 +233,6 @@ esp_err_t callHandleHttpRequest(httpd_req_t *req)
     return gpioHandler->handleHttpRequest(req);
 }
 
-void taskGpioHandler(void *pvParameter)
-{
-    ESP_LOGD(TAG,"taskGpioHandler");
-    ((GpioHandler*)pvParameter)->init();
-}
-
 GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer) 
 {
     ESP_LOGI(TAG,"start GpioHandler");
@@ -289,49 +277,76 @@ void GpioHandler::init()
         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");
+    // Each handler owns its queue; ISR callbacks never use a process-global queue.
+    _eventQueue = xQueueCreate(16, sizeof(GpioResult));
+    if (_eventQueue == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO event queue");
+        clear();
+        _isEnabled = false;
+        return;
+    }
+
+    _workerStopped = xSemaphoreCreateBinary();
+    if (_workerStopped == NULL) {
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO worker stop semaphore");
+        vQueueDelete(_eventQueue);
+        _eventQueue = NULL;
         clear();
         _isEnabled = false;
         return;
     }
 
-    for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
-        if (!it->second->init()) {
+    bool needsIsr = false;
+    for (std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
+        if (it->second->getInterruptType() != GPIO_INTR_DISABLE) needsIsr = true;
+    }
+    if (needsIsr) {
+        const esp_err_t isrServiceResult = gpio_install_isr_service(ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM);
+        if (isrServiceResult != ESP_OK && isrServiceResult != ESP_ERR_INVALID_STATE) {
+            ESP_LOGE(TAG, "Unable to install GPIO ISR service: %s", esp_err_to_name(isrServiceResult));
+            clear();
+            vSemaphoreDelete(_workerStopped);
+            _workerStopped = NULL;
+            vQueueDelete(_eventQueue);
+            _eventQueue = NULL;
+            _isEnabled = false;
+            return;
+        }
+    }
+
+    for (std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
+        if (!it->second->init(_eventQueue)) {
             LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
                                 "GPIO initialization failed for GPIO" + std::to_string(static_cast<int>(it->first)));
             clear();
-            vQueueDelete(gpio_queue_handle);
-            gpio_queue_handle = NULL;
+            vSemaphoreDelete(_workerStopped);
+            _workerStopped = NULL;
+            vQueueDelete(_eventQueue);
+            _eventQueue = NULL;
             _isEnabled = false;
             return;
         }
     }
 
-#ifdef ENABLE_MQTT
-    std::function<void()> f = std::bind(&GpioHandler::handleMQTTconnect, this);
-    MQTTregisterConnectFunction("gpio-handler", f);
-#endif //ENABLE_MQTT
-
-    const BaseType_t taskResult = xTaskCreate(&gpioHandlerTask, "gpio_int", 3 * 1024,
-                                               (void *)this, tskIDLE_PRIORITY + 4, &xHandleTaskGpio);
+    _isEnabled = true;
+    const BaseType_t taskResult = xTaskCreate(&GpioHandler::taskEntry, "gpio_int", 3 * 1024,
+                                               this, tskIDLE_PRIORITY + 4, &_workerTask);
     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;
+        _workerTask = NULL;
         _isEnabled = false;
+        clear();
+        vSemaphoreDelete(_workerStopped);
+        _workerStopped = NULL;
+        vQueueDelete(_eventQueue);
+        _eventQueue = NULL;
+        LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create GPIO handler task");
         return;
     }
 
-    _isEnabled = true;
+#ifdef ENABLE_MQTT
+    std::function<void()> f = std::bind(&GpioHandler::handleMQTTconnect, this);
+    MQTTregisterConnectFunction("gpio-handler", f);
+#endif
     ESP_LOGI(TAG, "GPIO init completed, is enabled");
 }
 
@@ -357,18 +372,27 @@ void GpioHandler::handleMQTTconnect()
 #endif //ENABLE_MQTT
 
 void GpioHandler::deinit() {
+    _isEnabled = false;
 #ifdef ENABLE_MQTT
     MQTTunregisterConnectFunction("gpio-handler");
-#endif //ENABLE_MQTT
+#endif
 
-    // Stop the worker before deleting its GPIO callback targets or queue.
-    if (xHandleTaskGpio != NULL) {
-        vTaskDelete(xHandleTaskGpio);
-        xHandleTaskGpio = NULL;
+    // Wake the worker and wait until it has stopped using the handler.
+    if (_workerTask != NULL && _eventQueue != NULL) {
+        GpioResult stop = {};
+        stop.stopEvent = true;
+        if (xQueueSend(_eventQueue, &stop, pdMS_TO_TICKS(1000)) != pdPASS) {
+            ESP_LOGW(TAG, "GPIO worker queue full while stopping; waiting for next queue slot");
+            xQueueSend(_eventQueue, &stop, portMAX_DELAY);
+        }
+        if (_workerStopped != NULL) {
+            xSemaphoreTake(_workerStopped, portMAX_DELAY);
+        }
+        _workerTask = 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;
@@ -376,11 +400,45 @@ void GpioHandler::deinit() {
 #endif
     clear();
 
-    if (gpio_queue_handle != NULL) {
-        vQueueDelete(gpio_queue_handle);
-        gpio_queue_handle = NULL;
+    if (_workerStopped != NULL) {
+        vSemaphoreDelete(_workerStopped);
+        _workerStopped = NULL;
     }
-    _isEnabled = false;
+    if (_eventQueue != NULL) {
+        vQueueDelete(_eventQueue);
+        _eventQueue = NULL;
+    }
+}
+
+void GpioHandler::taskEntry(void *arg) {
+    static_cast<GpioHandler *>(arg)->workerLoop();
+}
+
+void GpioHandler::workerLoop() {
+    ESP_LOGD(TAG, "GPIO worker started");
+    bool running = true;
+    TickType_t lastPoll = xTaskGetTickCount();
+
+    while (running) {
+        GpioResult result = {};
+        if (xQueueReceive(_eventQueue, &result, pdMS_TO_TICKS(250)) == pdPASS) {
+            if (result.stopEvent) {
+                running = false;
+            } else {
+                gpioInterrupt(&result);
+            }
+        }
+
+        const TickType_t now = xTaskGetTickCount();
+        if (running && (now - lastPoll) >= pdMS_TO_TICKS(1000)) {
+            taskHandler();
+            lastPoll = now;
+        }
+    }
+
+    ESP_LOGD(TAG, "GPIO worker stopped");
+    if (_workerStopped != NULL) xSemaphoreGive(_workerStopped);
+    vTaskDelete(NULL);
 }
 
 void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
@@ -536,11 +594,6 @@ bool GpioHandler::readConfig()
         }
     }
 
-    if (registerISR) {
-        //install gpio isr service
-        gpio_install_isr_service(ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM);
-    }
-
     if (gpioExtLED > 0)
     {
     //     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Startsequence 06");      // Nremove