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

Restore GPIO handler and correct profile JSON escaping

SybexXx 2 дней назад
Родитель
Сommit
ec7c27ce64
1 измененных файлов с 142 добавлено и 142 удалено
  1. 142 142
      code/components/jomjol_controlGPIO/server_GPIO.cpp

+ 142 - 142
code/components/jomjol_controlGPIO/server_GPIO.cpp

@@ -17,7 +17,7 @@
 #include "../../include/defines.h"
 
 #include "server_GPIO.h"
-                response += "{\"gpio\":";
+#include "board_gpio_profile.h"
 
 #include "ClassLogFile.h"
 #include "configFile.h"
@@ -32,9 +32,9 @@
 
 static const char *TAG = "GPIO";
 
-                response += "{\"gpio\":";
+static bool parseUserGpioKey(const std::string &key, gpio_num_t *gpio)
 {
-                response += "{\"gpio\":";
+    if (gpio == NULL || key.size() < 3U || key.size() > 4U ||
         key.compare(0, 2, "IO") != 0) {
         return false;
     }
@@ -53,7 +53,7 @@ static const char *TAG = "GPIO";
         return false;
     }
 
-                response += "{\"gpio\":";
+    *gpio = static_cast<gpio_num_t>(value);
     return true;
 }
 
@@ -67,14 +67,14 @@ static bool isSupportedInterruptName(const std::string &name)
            name == "high-level-trigger";
 }
 
-                response += "{\"gpio\":";
+static bool isInputPinMode(gpio_pin_mode_t mode)
 {
     return mode == GPIO_PIN_MODE_INPUT ||
            mode == GPIO_PIN_MODE_INPUT_PULLUP ||
            mode == GPIO_PIN_MODE_INPUT_PULLDOWN;
 }
 
-                response += "{\"gpio\":";
+static uint8_t requiredCapabilitiesForPinMode(gpio_pin_mode_t mode)
 {
     switch (mode) {
         case GPIO_PIN_MODE_INPUT: return GPIO_PIN_CAP_INPUT;
@@ -88,8 +88,8 @@ static bool isSupportedInterruptName(const std::string &name)
     }
 }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+static bool isAllowedUserPinConfiguration(gpio_num_t gpio, gpio_pin_mode_t mode,
+                                          gpio_int_type_t interruptType,
                                           std::string *reason)
 {
     uint8_t required = requiredCapabilitiesForPinMode(mode);
@@ -98,16 +98,16 @@ static bool isSupportedInterruptName(const std::string &name)
         return false;
     }
     if (interruptType != GPIO_INTR_DISABLE) required |= GPIO_PIN_CAP_INTERRUPT;
-                response += "{\"gpio\":";
+    if (!gpioBoardPinSupports(gpio, required)) {
         if (reason != NULL) *reason = "GPIO is not whitelisted for this board or requested mode";
         return false;
     }
     return true;
 }
 
-                response += "{\"gpio\":";
+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) 
 {
-                response += "{\"gpio\":";
+    _gpio = gpio;
     _name = (name != NULL) ? name : ""; 
     _mode = mode;
     _interruptType = interruptType;    
@@ -117,7 +117,7 @@ static bool isSupportedInterruptName(const std::string &name)
 
 GpioPin::~GpioPin()
 {
-                response += "{\"gpio\":";
+    ESP_LOGD(TAG,"reset GPIO pin %d", _gpio);
 #ifdef ENABLE_MQTT
     if (!_mqttTopic.empty()) {
         MQTTunregisterSubscribeFunction(_mqttTopic);
@@ -125,13 +125,13 @@ GpioPin::~GpioPin()
 #endif // ENABLE_MQTT
     if (_isrRegistered) {
         // Remove only an ISR that was successfully installed for this pin.
-                response += "{\"gpio\":";
+        gpio_isr_handler_remove(_gpio);
         _isrRegistered = false;
     }
-                response += "{\"gpio\":";
+    gpio_reset_pin(_gpio);
 }
 
-                response += "{\"gpio\":";
+static void IRAM_ATTR gpio_isr_handler(void *arg)
 {
     GpioIsrContext *context = static_cast<GpioIsrContext *>(arg);
     if (context == NULL || context->eventQueue == NULL) {
@@ -139,7 +139,7 @@ GpioPin::~GpioPin()
     }
 
     GpioResult result = {};
-                response += "{\"gpio\":";
+    result.gpio = context->gpio;
     // Read the pin level in task context; keep the IRAM ISR minimal.
     result.value = 0;
     result.stopEvent = false;
@@ -151,10 +151,10 @@ GpioPin::~GpioPin()
     }
 }
 
-                response += "{\"gpio\":";
+void GpioPin::gpioInterrupt(int value) {
 #ifdef ENABLE_MQTT
     if (!_mqttTopic.empty()) {
-                response += "{\"gpio\":";
+        ESP_LOGD(TAG, "gpioInterrupt %s %d", _mqttTopic.c_str(), value);
         MQTTPublish(_mqttTopic, value ? "true" : "false", 1);
     }
 #endif // ENABLE_MQTT
@@ -164,33 +164,33 @@ GpioPin::~GpioPin()
 bool GpioPin::init(QueueHandle_t eventQueue)
 {
     if (_interruptType != GPIO_INTR_DISABLE && eventQueue == NULL) {
-                response += "{\"gpio\":";
+        ESP_LOGE(TAG, "No event queue available for GPIO%d interrupt", static_cast<int>(_gpio));
         return false;
     }
 
-                response += "{\"gpio\":";
+    gpio_config_t io_conf = {};
     io_conf.intr_type = _interruptType;
     io_conf.mode = (_mode == GPIO_PIN_MODE_OUTPUT) ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT;
-                response += "{\"gpio\":";
+    io_conf.pin_bit_mask = (1ULL << static_cast<unsigned int>(_gpio));
     io_conf.pull_down_en = (_mode == GPIO_PIN_MODE_INPUT_PULLDOWN) ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
     io_conf.pull_up_en = (_mode == GPIO_PIN_MODE_INPUT_PULLUP) ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
 
-                response += "{\"gpio\":";
+    const esp_err_t configResult = gpio_config(&io_conf);
     if (configResult != ESP_OK) {
-                response += "{\"gpio\":";
+        ESP_LOGE(TAG, "gpio_config failed for GPIO%d: %s", static_cast<int>(_gpio), esp_err_to_name(configResult));
         return false;
     }
 
 //    if (_interruptType != GPIO_INTR_DISABLE) {                // ohne GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X, wenn das genutzt wird, dann soll auch der Handler hier nicht initialisiert werden, da das dann über SmartLED erfolgt.
     if (_interruptType != GPIO_INTR_DISABLE) {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        //hook isr handler for specific gpio pin
+        ESP_LOGD(TAG, "GpioPin::init add isr handler for GPIO %d", _gpio);
         _isrContext.eventQueue = eventQueue;
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        _isrContext.gpio = _gpio;
+        const esp_err_t isrResult = gpio_isr_handler_add(_gpio, gpio_isr_handler, &_isrContext);
         if (isrResult != ESP_OK) {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            ESP_LOGE(TAG, "gpio_isr_handler_add failed for GPIO%d: %s",
+                     static_cast<int>(_gpio), esp_err_to_name(isrResult));
             return false;
         }
         _isrRegistered = true;
@@ -211,17 +211,17 @@ bool GpioPin::getValue(std::string* errorText)
         (*errorText) = "GPIO is not in input mode";
     }
 
-                response += "{\"gpio\":";
+    return gpio_get_level(_gpio) == 1;
 }
 
-                response += "{\"gpio\":";
+void GpioPin::setValue(bool value, gpio_set_source setSource, std::string* errorText, bool publishMqtt)
 {
     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 (errorText != NULL) *errorText = "GPIO is not in output mode";
     } else {
-                response += "{\"gpio\":";
+        gpio_set_level(_gpio, value);
 
 #ifdef ENABLE_MQTT
         if (publishMqtt && !_mqttTopic.empty() && setSource != GPIO_SET_SOURCE_MQTT) {
@@ -232,10 +232,10 @@ bool GpioPin::getValue(std::string* errorText)
 }
 
 void GpioPin::publishState() {
-                response += "{\"gpio\":";
+    const int newState = gpio_get_level(_gpio);
     const int previousState = currentState.exchange(newState, std::memory_order_relaxed);
     if (newState != previousState) {
-                response += "{\"gpio\":";
+        ESP_LOGD(TAG, "publish state of GPIO %d new state %d", _gpio, newState);
 #ifdef ENABLE_MQTT
         if (!_mqttTopic.empty()) {
             MQTTPublish(_mqttTopic, newState ? "true" : "false", 1);
@@ -272,8 +272,8 @@ esp_err_t callHandleHttpRequest(httpd_req_t *req)
 {
     ESP_LOGD(TAG,"callHandleHttpRequest");
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    GpioHandler *gpioHandler = (GpioHandler*)req->user_ctx;
+    return gpioHandler->handleHttpRequest(req);
 }
 
 GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer) 
@@ -288,9 +288,9 @@ GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer)
 
 GpioHandler::~GpioHandler()  {
     deinit();
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if (gpioMap != NULL) {
+        delete gpioMap;
+        gpioMap = NULL;
     }
 }
 
@@ -303,9 +303,9 @@ void GpioHandler::init()
 
     {
         std::lock_guard<std::recursive_mutex> lock(_mapMutex);
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        if (gpioMap == NULL) {
+            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;
@@ -316,17 +316,17 @@ void GpioHandler::init()
     ESP_LOGI(TAG, "read GPIO config and init GPIO");
     if (!readConfig()) {
         clear();
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        delete gpioMap;
+        gpioMap = NULL;
         _isEnabled = false;
         ESP_LOGI(TAG, "GPIO init completed, handler is disabled");
         return;
     }
 
-            response += ",\"pins\":[";
-                response += "{\"gpio\":";
+    // An empty board whitelist (or no enabled user pins) needs no queue or worker.
+    if (gpioMap->empty()) {
         _isEnabled = false;
-            response += ",\"pins\":[";
+        ESP_LOGI(TAG, "GPIO handler disabled: no user GPIO pins are configured or available");
         return;
     }
 
@@ -350,11 +350,11 @@ void GpioHandler::init()
     }
 
     bool needsIsr = false;
-                response += "{\"gpio\":";
+    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) {
-                response += "{\"gpio\":";
+        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();
@@ -369,7 +369,7 @@ void GpioHandler::init()
 
     {
         std::lock_guard<std::recursive_mutex> lock(_mapMutex);
-                response += "{\"gpio\":";
+        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)));
@@ -385,7 +385,7 @@ void GpioHandler::init()
     }
 
     _isEnabled = true;
-                response += "{\"gpio\":";
+    const BaseType_t taskResult = xTaskCreate(&GpioHandler::taskEntry, "gpio_int", 3 * 1024,
                                                this, tskIDLE_PRIORITY + 4, &_workerTask);
     if (taskResult != pdPASS) {
         _workerTask = NULL;
@@ -401,7 +401,7 @@ void GpioHandler::init()
 
 #ifdef ENABLE_MQTT
     std::function<void()> f = std::bind(&GpioHandler::handleMQTTconnect, this);
-                response += "{\"gpio\":";
+    MQTTregisterConnectFunction("gpio-handler", f);
 #endif
     ESP_LOGI(TAG, "GPIO init completed, is enabled");
 }
@@ -410,8 +410,8 @@ void GpioHandler::taskHandler() {
     // The map is immutable while the worker is running. deinit() stops and joins
     // this worker before clearing the map. Do not hold _mapMutex while publishing
     // to MQTT: the MQTT client may wait on its event task, which can run callbacks.
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if (gpioMap != NULL) {
+        for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
             if ((it->second->getInterruptType() == GPIO_INTR_DISABLE))
                 it->second->publishState();
         }
@@ -424,8 +424,8 @@ void GpioHandler::handleMQTTconnect()
     // MQTTconnected() invokes this while holding connectFunctionMutex. Keep the
     // GPIO map lock out of synchronous MQTT publishing to avoid lock inversion.
     // deinit() unregisters this callback before clearing the map.
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    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_INPUT) || (it->second->getMode() == GPIO_PIN_MODE_INPUT_PULLDOWN) || (it->second->getMode() == GPIO_PIN_MODE_INPUT_PULLUP))
                 it->second->publishState();
         }
@@ -436,7 +436,7 @@ void GpioHandler::handleMQTTconnect()
 void GpioHandler::deinit() {
     _isEnabled = false;
 #ifdef ENABLE_MQTT
-                response += "{\"gpio\":";
+    MQTTunregisterConnectFunction("gpio-handler");
 #endif
 
     // Wake the worker and wait until it has stopped using the handler.
@@ -490,8 +490,8 @@ void GpioHandler::workerLoop() {
             if (result.stopEvent) {
                 running = false;
             } else {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+                result.value = gpio_get_level(result.gpio);
+                gpioInterrupt(&result);
             }
         }
 
@@ -507,18 +507,18 @@ void GpioHandler::workerLoop() {
     vTaskDelete(NULL);
 }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
+    // The worker is stopped and joined before deinit() mutates or frees gpioMap.
     // Avoid holding _mapMutex across the MQTT publish performed by GpioPin.
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if ((gpioMap != NULL) && (gpioMap->find(gpioResult->gpio) != gpioMap->end())) {
+        (*gpioMap)[gpioResult->gpio]->gpioInterrupt(gpioResult->value);
     }
 }
 
 bool GpioHandler::readConfig() 
 {
     std::lock_guard<std::recursive_mutex> lock(_mapMutex);
-                response += "{\"gpio\":";
+    if (!gpioMap->empty())
         clear();
 
     ConfigFile configFile = ConfigFile(_configFile); 
@@ -527,7 +527,7 @@ bool GpioHandler::readConfig()
     std::string line = "";
     bool disabledLine = false;
     bool eof = false;
-                response += "{\"gpio\":";
+    gpio_num_t gpioExtLED = (gpio_num_t) 0;
     
 //    ESP_LOGD(TAG, "readConfig - Start 1");
         
@@ -543,7 +543,7 @@ bool GpioHandler::readConfig()
     if (!_isEnabled)
         return false;
 
-                response += "{\"gpio\":";
+    if (!gpioBoardProfileIsValid()) {
         LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "GPIO disabled: invalid board GPIO profile");
         return false;
     }
@@ -570,37 +570,37 @@ bool GpioHandler::readConfig()
         // std::smatch pieces_match;
         // if (std::regex_match(splitted[0], pieces_match, pieces_regex) && (pieces_match.size() == 2))
         // {
-                response += "{\"gpio\":";
+        //     std::string gpioStr = pieces_match[1];
         ESP_LOGD(TAG, "conf param %s", toUpper(splitted[0]).c_str());
         if (toUpper(splitted[0]) == "MAINTOPICMQTT") {
 //            ESP_LOGD(TAG, "MAINTOPICMQTT found");
 //            mainTopicMQTT = splitted[1];
         } else if (toUpper(splitted[0]).rfind("IO", 0) == 0)
         {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            gpio_num_t gpioNr = GPIO_NUM_NC;
+            const std::string gpioKey = toUpper(splitted[0]);
+            if (!parseUserGpioKey(gpioKey, &gpioNr)) {
                 ESP_LOGW(TAG, "Ignoring malformed GPIO configuration key '%s'", splitted[0].c_str());
                 continue;
             }
             if (splitted.size() < 6U) {
-                response += "{\"gpio\":";
+                ESP_LOGW(TAG, "Ignoring incomplete GPIO configuration for %s", gpioKey.c_str());
                 continue;
             }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            ESP_LOGI(TAG,"Enable %s in %s mode", gpioKey.c_str(), splitted[1].c_str());
+            gpio_pin_mode_t pinMode = resolvePinMode(toLower(splitted[1]));
             const std::string interruptName = toLower(splitted[2]);
             if (!isSupportedInterruptName(interruptName)) {
                 ESP_LOGW(TAG, "Ignoring %s: unsupported interrupt setting '%s'",
-                response += "{\"gpio\":";
+                         gpioKey.c_str(), interruptName.c_str());
                 continue;
             }
-                response += "{\"gpio\":";
+            gpio_int_type_t intType = resolveIntType(interruptName);
             uint16_t dutyResolution = static_cast<uint8_t>(atoi(splitted[3].c_str()));
 
             if (intType != GPIO_INTR_DISABLE && !isInputPinMode(pinMode)) {
-                response += "{\"gpio\":";
+                ESP_LOGW(TAG, "Ignoring %s: interrupts are only valid for input modes", gpioKey.c_str());
                 continue;
             }
 
@@ -610,49 +610,49 @@ bool GpioHandler::readConfig()
             }
 
             std::string validationReason;
-                response += "{\"gpio\":";
+            if (!isAllowedUserPinConfiguration(gpioNr, pinMode, intType, &validationReason)) {
                 ESP_LOGW(TAG, "Ignoring unsafe GPIO configuration %s: %s", splitted[0].c_str(), validationReason.c_str());
                 continue;
             }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            const auto existingPin = gpioMap->find(gpioNr);
+            if (existingPin != gpioMap->end()) {
                 ESP_LOGW(TAG, "Ignoring duplicate GPIO entry %s", splitted[0].c_str());
                 continue;
             }
-                response += "{\"gpio\":";
+            if (acceptedUserChannels >= gpioGetBoardProfile()->maxUserChannels) {
                 ESP_LOGW(TAG, "Ignoring %s: maximum of %u user GPIO channels reached",
-                response += "{\"gpio\":";
+                         splitted[0].c_str(), static_cast<unsigned int>(gpioGetBoardProfile()->maxUserChannels));
                 continue;
             }
 #ifdef ENABLE_MQTT 
             bool mqttEnabled = (toLower(splitted[4]) == "true");
 #endif // ENABLE_MQTT
             bool httpEnabled = (toLower(splitted[5]) == "true");
-                response += "{\"gpio\":";
+            char gpioName[100];
             if (splitted.size() >= 7) {
-                response += "{\"gpio\":";
+                strlcpy(gpioName, trim(splitted[6]).c_str(), sizeof(gpioName));
             } else {
-                response += "{\"gpio\":";
+                sprintf(gpioName, "GPIO%d", gpioNr);
             }
 #ifdef ENABLE_MQTT            
-                response += "{\"gpio\":";
+            std::string mqttTopic = mqttEnabled ? (mainTopicMQTT + "/" + gpioName) : "";
 #else // ENABLE_MQTT
             std::string mqttTopic = "";
 #endif // ENABLE_MQTT
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            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;
             }
-                response += "{\"gpio\":";
+            gpioMap->emplace(gpioNr, gpioPin);
             ++acceptedUserChannels;
 
             if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
             {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+                ESP_LOGD(TAG, "Set WS2812 to GPIO %d", gpioNr);
+                gpioExtLED = gpioNr;
             }
 
         }
@@ -691,7 +691,7 @@ bool GpioHandler::readConfig()
         }
     }
 
-                response += "{\"gpio\":";
+    if (gpioExtLED > 0)
     {
     //     LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Startsequence 06");      // Nremove
 //        vTaskDelay( xDelay );   
@@ -704,7 +704,7 @@ bool GpioHandler::readConfig()
 //        leds[ 0 ] = Rgb{ 255, 0, 0 };
 //        leds[ 1 ] = Rgb{ 255, 255, 255 };
 //        leds.show();    
-                response += "{\"gpio\":";
+//        SmartLed leds = new SmartLed(LEDType, LEDNumbers, gpioExtLED, 0, DoubleBuffer);
 //        _SmartLED = new SmartLed( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer );
     }
 
@@ -716,14 +716,14 @@ void GpioHandler::clear()
     std::lock_guard<std::recursive_mutex> lock(_mapMutex);
     ESP_LOGD(TAG, "GpioHandler::clear");
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if (gpioMap != NULL) {
+        for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
             delete it->second;
         }
-                response += "{\"gpio\":";
+        gpioMap->clear();
     }
 
-                response += "{\"gpio\":";
+    // gpio_uninstall_isr_service(); can't uninstall, isr service is used by camera
 }
  
 void GpioHandler::registerGpioUri() 
@@ -744,12 +744,12 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
 
     char query[200] = {};
     if (httpd_req_get_url_query_str(req, query, sizeof(query)) == ESP_OK) {
-                response += ",\"capabilities\":";
-                response += ",\"capabilities\":";
-                response += ",\"capabilities\":";
-                response += ",\"capabilities\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        char capabilitiesRequest[8] = {};
+        if (httpd_query_key_value(query, "capabilities", capabilitiesRequest,
+                                  sizeof(capabilitiesRequest)) == ESP_OK &&
+            strcmp(capabilitiesRequest, "1") == 0) {
+            const GpioBoardProfile *profile = gpioGetBoardProfile();
+            if (profile == NULL || !gpioBoardProfileIsValid()) {
                 httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR,
                                     "Invalid GPIO board profile");
                 return ESP_OK;
@@ -763,9 +763,9 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
             for (size_t i = 0; i < profile->userPinCount; ++i) {
                 if (i > 0U) response += ",";
                 response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += ",\"capabilities\":";
+                response += std::to_string(static_cast<int>(profile->userPins[i].gpio));
                 response += ",\"capabilities\":";
+                response += std::to_string(profile->userPins[i].capabilities);
                 response += "}";
             }
             response += "]}";
@@ -775,7 +775,7 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
         }
     }
 
-                response += "{\"gpio\":";
+    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,
@@ -783,7 +783,7 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
         return ESP_OK;
     }
 
-                response += "{\"gpio\":";
+    if (httpd_query_key_value(query, "GPIO", gpioText, sizeof(gpioText)) != ESP_OK) {
         httpd_resp_sendstr(req, "GPIO No is not defined");
         return ESP_OK;
     }
@@ -800,12 +800,12 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
         return ESP_OK;
     }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    const std::string gpio = gpioText;
+    if (gpio.empty()) {
         httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing");
         return ESP_OK;
     }
-                response += "{\"gpio\":";
+    for (char ch : gpio) {
         if (ch < '0' || ch > '9') {
             httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST,
                                 "GPIO number must be numeric");
@@ -813,10 +813,10 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
         }
     }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    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;
@@ -833,12 +833,12 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
     {
         std::lock_guard<std::recursive_mutex> lock(_mapMutex);
 
-                response += "{\"gpio\":";
+        if (gpioMap == NULL) {
             response = "GPIO handler not initialized";
         } else {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+            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;
@@ -851,7 +851,7 @@ esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
                 const bool high = status == "HIGH" || status == "TRUE" || status == "1";
                 pin->second->setValue(high, GPIO_SET_SOURCE_HTTP, &errorText, false);
                 if (errorText.empty()) {
-                response += "{\"gpio\":";
+                    response = "GPIO" + std::to_string(gpioNumber) +
                                " switched to " + status;
 #ifdef ENABLE_MQTT
                     mqttTopic = pin->second->getMqttTopic();
@@ -886,9 +886,9 @@ void GpioHandler::flashLightEnable(bool value)
     std::vector<std::string> mqttTopics;
     {
         std::lock_guard<std::recursive_mutex> lock(_mapMutex);
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+        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
@@ -921,7 +921,7 @@ void GpioHandler::flashLightEnable(bool value)
 #endif
 }
 
-                response += "{\"gpio\":";
+gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input) 
 {
     if( input == "disabled" ) return GPIO_PIN_MODE_DISABLED;
     if( input == "input" ) return GPIO_PIN_MODE_INPUT;
@@ -936,7 +936,7 @@ void GpioHandler::flashLightEnable(bool value)
     return GPIO_PIN_MODE_DISABLED;
 }
 
-                response += "{\"gpio\":";
+gpio_int_type_t GpioHandler::resolveIntType(std::string input) 
 {
     if( input == "disabled" ) return GPIO_INTR_DISABLE;
     if( input == "rising-edge" ) return GPIO_INTR_POSEDGE;
@@ -949,42 +949,42 @@ void GpioHandler::flashLightEnable(bool value)
     return GPIO_INTR_DISABLE;
 }
 
-                response += "{\"gpio\":";
+static GpioHandler *gpioHandler = NULL;
 
-                response += "{\"gpio\":";
+void gpio_handler_create(httpd_handle_t server)
 {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    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");
         }
     }
 }
 
-                response += "{\"gpio\":";
+void gpio_handler_init() 
 {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if (gpioHandler != NULL) {
+        gpioHandler->init();
     }
 }
 
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+void gpio_handler_deinit() {
+    if (gpioHandler != NULL) {
+        gpioHandler->deinit();
    }
 }
 
-                response += "{\"gpio\":";
+void gpio_handler_destroy()
 {
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
-                response += "{\"gpio\":";
+    if (gpioHandler != NULL) {
+        gpio_handler_deinit();
+        delete gpioHandler;
+        gpioHandler = NULL;
     }
 }
 
-                response += "{\"gpio\":";
+GpioHandler* gpio_handler_get()
 {
-                response += "{\"gpio\":";
+    return gpioHandler;
 }