Pārlūkot izejas kodu

Keep GPIO map lock out of HTTP and MQTT work

SybexXx 1 dienu atpakaļ
vecāks
revīzija
7f9c8bd70c
1 mainītis faili ar 125 papildinājumiem un 148 dzēšanām
  1. 125 148
      code/components/jomjol_controlGPIO/server_GPIO.cpp

+ 125 - 148
code/components/jomjol_controlGPIO/server_GPIO.cpp

@@ -214,20 +214,20 @@ bool GpioPin::getValue(std::string* errorText)
     return gpio_get_level(_gpio) == 1;
     return gpio_get_level(_gpio) == 1;
 }
 }
 
 
-void GpioPin::setValue(bool value, gpio_set_source setSource, std::string* errorText)
+void GpioPin::setValue(bool value, gpio_set_source setSource, std::string* errorText, bool publishMqtt)
 {
 {
     ESP_LOGD(TAG, "GpioPin::setValue %d", value);
     ESP_LOGD(TAG, "GpioPin::setValue %d", value);
 
 
     if ((_mode != GPIO_PIN_MODE_OUTPUT) && (_mode != GPIO_PIN_MODE_OUTPUT_PWM) && (_mode != GPIO_PIN_MODE_BUILT_IN_FLASH_LED)) {
     if ((_mode != GPIO_PIN_MODE_OUTPUT) && (_mode != GPIO_PIN_MODE_OUTPUT_PWM) && (_mode != GPIO_PIN_MODE_BUILT_IN_FLASH_LED)) {
-        (*errorText) = "GPIO is not in output mode";
+        if (errorText != NULL) *errorText = "GPIO is not in output mode";
     } else {
     } else {
         gpio_set_level(_gpio, value);
         gpio_set_level(_gpio, value);
 
 
 #ifdef ENABLE_MQTT
 #ifdef ENABLE_MQTT
-        if ((_mqttTopic.compare("") != 0) && (setSource != GPIO_SET_SOURCE_MQTT)) {
+        if (publishMqtt && !_mqttTopic.empty() && setSource != GPIO_SET_SOURCE_MQTT) {
             MQTTPublish(_mqttTopic, value ? "true" : "false", 1);
             MQTTPublish(_mqttTopic, value ? "true" : "false", 1);
         }
         }
-#endif //ENABLE_MQTT
+#endif // ENABLE_MQTT
     }
     }
 }
 }
 
 
@@ -742,10 +742,10 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
 {
 {
     ESP_LOGD(TAG, "handleHttpRequest");
     ESP_LOGD(TAG, "handleHttpRequest");
 
 
-    char _query[200];
-    if (httpd_req_get_url_query_str(req, _query, sizeof(_query)) == ESP_OK) {
+    char query[200] = {};
+    if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK) {
         char capabilitiesRequest[8] = {};
         char capabilitiesRequest[8] = {};
-        if (httpd_query_key_value(_query, "capabilities", capabilitiesRequest,
+        if (httpd_query_key_value(query, "capabilities", capabilitiesRequest,
                                   sizeof(capabilitiesRequest)) == ESP_OK &&
                                   sizeof(capabilitiesRequest)) == ESP_OK &&
             strcmp(capabilitiesRequest, "1") == 0) {
             strcmp(capabilitiesRequest, "1") == 0) {
             const GpioBoardProfile *profile = gpioGetBoardProfile();
             const GpioBoardProfile *profile = gpioGetBoardProfile();
@@ -755,193 +755,170 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
                 return ESP_OK;
                 return ESP_OK;
             }
             }
 
 
-            std::string response = "{\"profile\":\"";
+            std::string response = "{\\"profile\\":\\"";
             response += profile->name;
             response += profile->name;
-            response += "\",\"maxChannels\":";
+            response += "\\",\\"maxChannels\\":";
             response += std::to_string(profile->maxUserChannels);
             response += std::to_string(profile->maxUserChannels);
-            response += ",\"pins\":[";
+            response += ",\\"pins\\":[";
             for (size_t i = 0; i < profile->userPinCount; ++i) {
             for (size_t i = 0; i < profile->userPinCount; ++i) {
                 if (i > 0U) response += ",";
                 if (i > 0U) response += ",";
-                response += "{\"gpio\":";
+                response += "{\\"gpio\\":";
                 response += std::to_string(static_cast<int>(profile->userPins[i].gpio));
                 response += std::to_string(static_cast<int>(profile->userPins[i].gpio));
-                response += ",\"capabilities\":";
+                response += ",\\"capabilities\\":";
                 response += std::to_string(profile->userPins[i].capabilities);
                 response += std::to_string(profile->userPins[i].capabilities);
                 response += "}";
                 response += "}";
             }
             }
             response += "]}";
             response += "]}";
             httpd_resp_set_type(req, "application/json");
             httpd_resp_set_type(req, "application/json");
             httpd_resp_set_hdr(req, "Cache-Control", "no-store");
             httpd_resp_set_hdr(req, "Cache-Control", "no-store");
-            httpd_resp_send(req, response.c_str(), response.length());
-            return ESP_OK;
+            return httpd_resp_send(req, response.c_str(), response.length());
         }
         }
     }
     }
 
 
-    std::lock_guard<std::recursive_mutex> lock(_mapMutex);
-
-    if (gpioMap == NULL) {
-        httpd_resp_sendstr(req, "GPIO handler not initialized");
+    char gpioText[30] = {};
+    char statusText[30] = {};
+    if (httpd_req_get_url_query_str(req, query, sizeof(query)) != ESP_OK) {
+        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
+                            "Error in call. Use /GPIO?GPIO=12&Status=high");
         return ESP_OK;
         return ESP_OK;
     }
     }
 
 
-#ifdef DEBUG_DETAIL_ON 
-    LogFile.WriteHeapInfo("handler_switch_GPIO - Start");    
-#endif
-
-    LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_switch_GPIO");
-    char _valueGPIO[30];    
-    char _valueStatus[30];    
-    std::string gpio, status;
-
-    if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK) {
-        ESP_LOGD(TAG, "Query: %s", _query);
-        
-        if (httpd_query_key_value(_query, "GPIO", _valueGPIO, 30) == ESP_OK)
-        {
-            ESP_LOGD(TAG, "GPIO is found %s", _valueGPIO); 
-            gpio = std::string(_valueGPIO);
-        } else {
-            std::string resp_str = "GPIO No is not defined";
-            httpd_resp_send(req, resp_str.c_str(), resp_str.length());    
-            return ESP_OK;
-        }
-        if (httpd_query_key_value(_query, "Status", _valueStatus, 30) == ESP_OK)
-        {
-            ESP_LOGD(TAG, "Status is found %s", _valueStatus); 
-            status = std::string(_valueStatus);
-        }
-    } else {
-        const char* resp_str = "Error in call. Use /GPIO?GPIO=12&Status=high";
-        httpd_resp_send(req, resp_str, strlen(resp_str));    
+    if (httpd_query_key_value(query, "GPIO", gpioText, sizeof(gpioText)) != ESP_OK) {
+        httpd_resp_sendstr(req, "GPIO No is not defined");
         return ESP_OK;
         return ESP_OK;
     }
     }
 
 
-    status = toUpper(status);
-    if ((status != "HIGH") && (status != "LOW") && (status != "TRUE") && (status != "FALSE") && (status != "0") && (status != "1") && (status != ""))
-    {
-        std::string zw = "Status not valid: " + status;
-        httpd_resp_sendstr_chunk(req, zw.c_str());
-        httpd_resp_sendstr_chunk(req, NULL);          
-        return ESP_OK;    
+    std::string status;
+    if (httpd_query_key_value(query, "Status", statusText, sizeof(statusText)) == ESP_OK) {
+        status = toUpper(std::string(statusText));
     }
     }
 
 
+    if (status != "HIGH" && status != "LOW" && status != "TRUE" &&
+        status != "FALSE" && status != "0" && status != "1" && !status.empty()) {
+        const std::string message = "Status not valid: " + status;
+        httpd_resp_sendstr(req, message.c_str());
+        return ESP_OK;
+    }
+
+    const std::string gpio = gpioText;
     if (gpio.empty()) {
     if (gpio.empty()) {
         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing");
         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing");
         return ESP_OK;
         return ESP_OK;
     }
     }
-    for (size_t i = 0; i < gpio.length(); ++i) {
-        if (gpio[i] < '0' || gpio[i] > '9') {
-            httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number must be numeric");
+    for (char ch : gpio) {
+        if (ch < '0' || ch > '9') {
+            httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
+                                "GPIO number must be numeric");
             return ESP_OK;
             return ESP_OK;
         }
         }
     }
     }
 
 
-    const int gpionum = atoi(gpio.c_str());
-    gpio_num_t gpio_num = static_cast<gpio_num_t>(gpionum);
-    if (gpioBoardFindUserPin(gpio_num) == NULL)
-    {
-        std::string zw = "GPIO" + std::to_string(gpionum) + " is not available in this board profile";
-            httpd_resp_sendstr_chunk(req, zw.c_str());
-            httpd_resp_sendstr_chunk(req, NULL);          
-            return ESP_OK;
+    const int gpioNumber = atoi(gpio.c_str());
+    const gpio_num_t gpioNum = static_cast<gpio_num_t>(gpioNumber);
+    if (gpioBoardFindUserPin(gpioNum) == NULL) {
+        const std::string message = "GPIO" + std::to_string(gpioNumber) +
+                                    " is not available in this board profile";
+        httpd_resp_sendstr(req, message.c_str());
+        return ESP_OK;
     }
     }
 
 
-    if (gpioMap->count(gpio_num) == 0) {
-        char resp_str [30];
-        sprintf(resp_str, "GPIO%d is not registred", gpio_num);
-        httpd_resp_send(req, resp_str, strlen(resp_str));  
-        return ESP_OK;     
-    }
+    std::string response;
+    std::string mqttTopic;
+    bool publishMqtt = false;
+    int responseStatus = 200;
 
 
-    if (!(*gpioMap)[gpio_num]->isHttpEnabled()) {
-        httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "HTTP access is disabled for this GPIO");
-        return ESP_OK;
-    }
-    
-    if (status == "") 
+    // Protect only the map lookup and the immediate GPIO operation. Never keep
+    // this mutex while sending an HTTP response or publishing to the MQTT client:
+    // camera flash transitions also need the map and must not wait on network I/O.
     {
     {
-        std::string resp_str = "";
-        status = (*gpioMap)[gpio_num]->getValue(&resp_str) ? "HIGH" : "LOW";
-        if (resp_str == "") {
-            resp_str = status;
+        std::lock_guard<std::recursive_mutex> lock(_mapMutex);
+
+        if (gpioMap == NULL) {
+            response = "GPIO handler not initialized";
+        } else {
+            const auto pin = gpioMap->find(gpioNum);
+            if (pin == gpioMap->end()) {
+                response = "GPIO" + std::to_string(gpioNumber) + " is not registred";
+            } else if (!pin->second->isHttpEnabled()) {
+                response = "HTTP access is disabled for this GPIO";
+                responseStatus = 403;
+            } else if (status.empty()) {
+                std::string errorText;
+                const bool high = pin->second->getValue(&errorText);
+                response = errorText.empty() ? (high ? "HIGH" : "LOW") : errorText;
+            } else {
+                std::string errorText;
+                const bool high = status == "HIGH" || status == "TRUE" || status == "1";
+                pin->second->setValue(high, GPIO_SET_SOURCE_HTTP, &errorText, false);
+                if (errorText.empty()) {
+                    response = "GPIO" + std::to_string(gpioNumber) +
+                               " switched to " + status;
+#ifdef ENABLE_MQTT
+                    mqttTopic = pin->second->getMqttTopic();
+                    publishMqtt = !mqttTopic.empty();
+#endif
+                } else {
+                    response = errorText;
+                }
+            }
         }
         }
-        httpd_resp_sendstr_chunk(req, resp_str.c_str());
-        httpd_resp_sendstr_chunk(req, NULL);
     }
     }
-    else
-    {
-        std::string resp_str = "";
-        (*gpioMap)[gpio_num]->setValue((status == "HIGH") || (status == "TRUE") || (status == "1"), GPIO_SET_SOURCE_HTTP, &resp_str);
-        if (resp_str == "") {
-            resp_str = "GPIO" + std::to_string(gpionum) + " switched to " + status;
-        }
-        httpd_resp_sendstr_chunk(req, resp_str.c_str());
-        httpd_resp_sendstr_chunk(req, NULL);
+
+#ifdef ENABLE_MQTT
+    if (publishMqtt) {
+        MQTTPublish(mqttTopic, (status == "HIGH" || status == "TRUE" || status == "1")
+                                   ? "true" : "false", 1);
     }
     }
-          
-    return ESP_OK;    
-};
+#endif
 
 
-void GpioHandler::flashLightEnable(bool value) 
+    if (responseStatus == 403) {
+        httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, response.c_str());
+    } else {
+        httpd_resp_sendstr(req, response.c_str());
+    }
+    return ESP_OK;
+}
+
+void GpioHandler::flashLightEnable(bool value)
 {
 {
-    std::lock_guard<std::recursive_mutex> lock(_mapMutex);
     ESP_LOGD(TAG, "GpioHandler::flashLightEnable %s", value ? "true" : "false");
     ESP_LOGD(TAG, "GpioHandler::flashLightEnable %s", value ? "true" : "false");
 
 
-    if (gpioMap != NULL) {
-        for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) 
-        {
-            if (it->second->getMode() == GPIO_PIN_MODE_BUILT_IN_FLASH_LED) //|| (it->second->getMode() == GPIO_PIN_MODE_EXTERNAL_FLASH_PWM) || (it->second->getMode() == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X))
-            {
-                std::string resp_str = "";
-                it->second->setValue(value, GPIO_SET_SOURCE_INTERNAL, &resp_str);
-
-                if (resp_str == "") {
-                    ESP_LOGD(TAG, "Flash light pin GPIO %d switched to %s", (int)it->first, (value ? "on" : "off"));
-                } else {
-                    ESP_LOGE(TAG, "Can't set flash light pin GPIO %d.  Error: %s", (int)it->first, resp_str.c_str());
-                }
-            } else 
-                {
-                    if (it->second->getMode() == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
-                    {
-#ifdef __LEDGLOBAL
-                        if (leds_global == NULL) {
-                            ESP_LOGI(TAG, "init SmartLed: LEDNumber=%d, GPIO=%d", LEDNumbers, (int)it->second->getGPIO());
-                            leds_global = new SmartLed( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
-                        } else {
-                            // wait until we can update: https://github.com/RoboticsBrno/SmartLeds/issues/10#issuecomment-386921623
-                            leds_global->wait();
-                        }
-#else
-                        SmartLed leds( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
-#endif
-  
-                        if (value)
-                        {
-                            for (int i = 0; i < LEDNumbers; ++i)
-#ifdef __LEDGLOBAL
-                                (*leds_global)[i] = LEDColor;
-#else
-                                leds[i] = LEDColor;
-#endif
-                        }
-                        else
-                        {
-                            for (int i = 0; i < LEDNumbers; ++i)
-#ifdef __LEDGLOBAL
-                                (*leds_global)[i] = Rgb{0, 0, 0};
-#else
-                                leds[i] = Rgb{0, 0, 0};
+    std::vector<std::string> mqttTopics;
+    {
+        std::lock_guard<std::recursive_mutex> lock(_mapMutex);
+        if (gpioMap != NULL) {
+            for (std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin();
+                 it != gpioMap->end(); ++it) {
+                if (it->second->getMode() == GPIO_PIN_MODE_BUILT_IN_FLASH_LED) {
+                    std::string errorText;
+                    // Do the GPIO write under the map lock, but defer the network
+                    // publication until after unlocking. The camera task calls this
+                    // synchronously at image-capture and flow-step transitions.
+                    it->second->setValue(value, GPIO_SET_SOURCE_INTERNAL,
+                                         &errorText, false);
+                    if (errorText.empty()) {
+                        ESP_LOGD(TAG, "Flash light pin GPIO %d switched %s",
+                                 static_cast<int>(it->first), value ? "on" : "off");
+#ifdef ENABLE_MQTT
+                        const std::string &topic = it->second->getMqttTopic();
+                        if (!topic.empty()) mqttTopics.push_back(topic);
 #endif
 #endif
-                        }
-#ifdef __LEDGLOBAL
-                        leds_global->show(); 
-#else
-                        leds.show(); 
-#endif 
+                    } else {
+                        ESP_LOGE(TAG, "Can't set flash light pin GPIO %d. Error: %s",
+                                 static_cast<int>(it->first), errorText.c_str());
                     }
                     }
                 }
                 }
+                // External addressable LED modes are not exposed by the currently
+                // supported classic ESP32 board profiles.
+            }
         }
         }
     }
     }
+
+#ifdef ENABLE_MQTT
+    for (const std::string &topic : mqttTopics) {
+        MQTTPublish(topic, value ? "true" : "false", 1);
+    }
+#endif
 }
 }
 
 
 gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input) 
 gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input)