#include #include #include "string.h" #include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include #include "esp_system.h" #include "esp_log.h" #include #include #include "../../include/defines.h" #include "server_GPIO.h" response += "{\"gpio\":"; #include "ClassLogFile.h" #include "configFile.h" #include "Helper.h" #ifdef ENABLE_MQTT #include "interface_mqtt.h" #include "server_mqtt.h" #endif //ENABLE_MQTT #include "basic_auth.h" static const char *TAG = "GPIO"; response += "{\"gpio\":"; { response += "{\"gpio\":"; key.compare(0, 2, "IO") != 0) { return false; } int value = 0; for (size_t i = 2U; i < key.size(); ++i) { const char ch = key[i]; if (ch < '0' || ch > '9') { return false; } value = (value * 10) + (ch - '0'); } /* GPIO0..GPIO48 is the supported configuration namespace. */ if (value < 0 || value > 48) { return false; } response += "{\"gpio\":"; return true; } static bool isSupportedInterruptName(const std::string &name) { return name == "disabled" || name == "rising-edge" || name == "falling-edge" || name == "rising-and-falling" || name == "low-level-trigger" || name == "high-level-trigger"; } response += "{\"gpio\":"; { return mode == GPIO_PIN_MODE_INPUT || mode == GPIO_PIN_MODE_INPUT_PULLUP || mode == GPIO_PIN_MODE_INPUT_PULLDOWN; } response += "{\"gpio\":"; { switch (mode) { case GPIO_PIN_MODE_INPUT: return GPIO_PIN_CAP_INPUT; case GPIO_PIN_MODE_INPUT_PULLUP: return GPIO_PIN_CAP_INPUT | GPIO_PIN_CAP_PULL_UP; case GPIO_PIN_MODE_INPUT_PULLDOWN: return GPIO_PIN_CAP_INPUT | GPIO_PIN_CAP_PULL_DOWN; case GPIO_PIN_MODE_OUTPUT: return GPIO_PIN_CAP_OUTPUT; case GPIO_PIN_MODE_OUTPUT_PWM: /* PWM remains unavailable until a tested LEDC backend is implemented. */ return 0U; default: return 0U; } } response += "{\"gpio\":"; response += "{\"gpio\":"; std::string *reason) { uint8_t required = requiredCapabilitiesForPinMode(mode); if (required == 0U) { if (reason != NULL) *reason = "board-owned or unsupported GPIO mode"; return false; } if (interruptType != GPIO_INTR_DISABLE) required |= GPIO_PIN_CAP_INTERRUPT; response += "{\"gpio\":"; if (reason != NULL) *reason = "GPIO is not whitelisted for this board or requested mode"; return false; } return true; } response += "{\"gpio\":"; { response += "{\"gpio\":"; _name = (name != NULL) ? name : ""; _mode = mode; _interruptType = interruptType; _mqttTopic = mqttTopic; _httpEnable = httpEnable; } GpioPin::~GpioPin() { response += "{\"gpio\":"; #ifdef ENABLE_MQTT if (!_mqttTopic.empty()) { MQTTunregisterSubscribeFunction(_mqttTopic); } #endif // ENABLE_MQTT if (_isrRegistered) { // Remove only an ISR that was successfully installed for this pin. response += "{\"gpio\":"; _isrRegistered = false; } response += "{\"gpio\":"; } response += "{\"gpio\":"; { GpioIsrContext *context = static_cast(arg); if (context == NULL || context->eventQueue == NULL) { return; } GpioResult result = {}; response += "{\"gpio\":"; // Read the pin level in task context; keep the IRAM ISR minimal. result.value = 0; result.stopEvent = false; BaseType_t higherPriorityTaskWoken = pdFALSE; if (xQueueSendFromISR(context->eventQueue, &result, &higherPriorityTaskWoken) == pdPASS && higherPriorityTaskWoken == pdTRUE) { portYIELD_FROM_ISR(); } } response += "{\"gpio\":"; #ifdef ENABLE_MQTT if (!_mqttTopic.empty()) { response += "{\"gpio\":"; MQTTPublish(_mqttTopic, value ? "true" : "false", 1); } #endif // ENABLE_MQTT currentState.store(value, std::memory_order_relaxed); } bool GpioPin::init(QueueHandle_t eventQueue) { if (_interruptType != GPIO_INTR_DISABLE && eventQueue == NULL) { response += "{\"gpio\":"; return false; } response += "{\"gpio\":"; io_conf.intr_type = _interruptType; io_conf.mode = (_mode == GPIO_PIN_MODE_OUTPUT) ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT; response += "{\"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\":"; if (configResult != ESP_OK) { response += "{\"gpio\":"; 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\":"; _isrContext.eventQueue = eventQueue; response += "{\"gpio\":"; response += "{\"gpio\":"; if (isrResult != ESP_OK) { response += "{\"gpio\":"; response += "{\"gpio\":"; return false; } _isrRegistered = true; } #ifdef ENABLE_MQTT if ((_mqttTopic.compare("") != 0) && ((_mode == GPIO_PIN_MODE_OUTPUT) || (_mode == GPIO_PIN_MODE_OUTPUT_PWM) || (_mode == GPIO_PIN_MODE_BUILT_IN_FLASH_LED))) { std::function f = std::bind(&GpioPin::handleMQTT, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); MQTTregisterSubscribeFunction(_mqttTopic, f); } #endif //ENABLE_MQTT return true; } bool GpioPin::getValue(std::string* errorText) { if ((_mode != GPIO_PIN_MODE_INPUT) && (_mode != GPIO_PIN_MODE_INPUT_PULLUP) && (_mode != GPIO_PIN_MODE_INPUT_PULLDOWN)) { (*errorText) = "GPIO is not in input mode"; } response += "{\"gpio\":"; } response += "{\"gpio\":"; { 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\":"; #ifdef ENABLE_MQTT if (publishMqtt && !_mqttTopic.empty() && setSource != GPIO_SET_SOURCE_MQTT) { MQTTPublish(_mqttTopic, value ? "true" : "false", 1); } #endif // ENABLE_MQTT } } void GpioPin::publishState() { response += "{\"gpio\":"; const int previousState = currentState.exchange(newState, std::memory_order_relaxed); if (newState != previousState) { response += "{\"gpio\":"; #ifdef ENABLE_MQTT if (!_mqttTopic.empty()) { MQTTPublish(_mqttTopic, newState ? "true" : "false", 1); } #endif // ENABLE_MQTT } } #ifdef ENABLE_MQTT bool GpioPin::handleMQTT(std::string, char* data, int data_len) { ESP_LOGD(TAG, "GpioPin::handleMQTT data %.*s", data_len, data); std::string dataStr(data, data_len); dataStr = toLower(dataStr); std::string errorText = ""; if ((dataStr == "true") || (dataStr == "1")) { setValue(true, GPIO_SET_SOURCE_MQTT, &errorText); } else if ((dataStr == "false") || (dataStr == "0")) { setValue(false, GPIO_SET_SOURCE_MQTT, &errorText); } else { errorText = "wrong value "; errorText.append(data, data_len); } if (errorText != "") { ESP_LOGE(TAG, "%s", errorText.c_str()); } return (errorText == ""); } #endif //ENABLE_MQTT esp_err_t callHandleHttpRequest(httpd_req_t *req) { ESP_LOGD(TAG,"callHandleHttpRequest"); response += "{\"gpio\":"; response += "{\"gpio\":"; } GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer) { ESP_LOGI(TAG,"start GpioHandler"); _configFile = configFile; _httpServer = httpServer; ESP_LOGI(TAG, "register GPIO Uri"); registerGpioUri(); } GpioHandler::~GpioHandler() { deinit(); response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; } } void GpioHandler::init() { ESP_LOGD(TAG, "*************** Start GPIOHandler_Init *****************"); // Stop any previous task, queue and pin callbacks before rebuilding them. deinit(); { std::lock_guard lock(_mapMutex); response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO map"); _isEnabled = false; return; } } } ESP_LOGI(TAG, "read GPIO config and init GPIO"); if (!readConfig()) { clear(); response += "{\"gpio\":"; response += "{\"gpio\":"; _isEnabled = false; ESP_LOGI(TAG, "GPIO init completed, handler is disabled"); return; } response += ",\"pins\":["; response += "{\"gpio\":"; _isEnabled = false; response += ",\"pins\":["; return; } // 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; } bool needsIsr = false; response += "{\"gpio\":"; if (it->second->getInterruptType() != GPIO_INTR_DISABLE) needsIsr = true; } if (needsIsr) { response += "{\"gpio\":"; 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; } } { std::lock_guard lock(_mapMutex); response += "{\"gpio\":"; if (!it->second->init(_eventQueue)) { LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "GPIO initialization failed for GPIO" + std::to_string(static_cast(it->first))); clear(); vSemaphoreDelete(_workerStopped); _workerStopped = NULL; vQueueDelete(_eventQueue); _eventQueue = NULL; _isEnabled = false; return; } } } _isEnabled = true; response += "{\"gpio\":"; this, tskIDLE_PRIORITY + 4, &_workerTask); if (taskResult != pdPASS) { _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; } #ifdef ENABLE_MQTT std::function f = std::bind(&GpioHandler::handleMQTTconnect, this); response += "{\"gpio\":"; #endif ESP_LOGI(TAG, "GPIO init completed, is enabled"); } 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 ((it->second->getInterruptType() == GPIO_INTR_DISABLE)) it->second->publishState(); } } } #ifdef ENABLE_MQTT 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 ((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(); } } } #endif //ENABLE_MQTT void GpioHandler::deinit() { _isEnabled = false; #ifdef ENABLE_MQTT response += "{\"gpio\":"; #endif // 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) { leds_global->wait(); delete leds_global; leds_global = NULL; } #endif { std::lock_guard lock(_mapMutex); clear(); } if (_workerStopped != NULL) { vSemaphoreDelete(_workerStopped); _workerStopped = NULL; } if (_eventQueue != NULL) { vQueueDelete(_eventQueue); _eventQueue = NULL; } } void GpioHandler::taskEntry(void *arg) { static_cast(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 { response += "{\"gpio\":"; response += "{\"gpio\":"; } } 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); } response += "{\"gpio\":"; response += "{\"gpio\":"; // Avoid holding _mapMutex across the MQTT publish performed by GpioPin. response += "{\"gpio\":"; response += "{\"gpio\":"; } } bool GpioHandler::readConfig() { std::lock_guard lock(_mapMutex); response += "{\"gpio\":"; clear(); ConfigFile configFile = ConfigFile(_configFile); std::vector splitted; std::string line = ""; bool disabledLine = false; bool eof = false; response += "{\"gpio\":"; // ESP_LOGD(TAG, "readConfig - Start 1"); while ((!configFile.GetNextParagraph(line, disabledLine, eof) || (line.compare("[GPIO]") != 0)) && !eof) {} if (eof) return false; // ESP_LOGD(TAG, "readConfig - Start 2 line: %s, disabbledLine: %d", line.c_str(), (int) disabledLine); _isEnabled = !disabledLine; if (!_isEnabled) return false; response += "{\"gpio\":"; LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "GPIO disabled: invalid board GPIO profile"); return false; } // ESP_LOGD(TAG, "readConfig - Start 3"); #ifdef ENABLE_MQTT // std::string mainTopicMQTT = ""; std::string mainTopicMQTT = mqttServer_getMainTopic(); if (mainTopicMQTT.length() > 0) { mainTopicMQTT = mainTopicMQTT + "/GPIO"; ESP_LOGD(TAG, "MAINTOPICMQTT found"); } #endif // ENABLE_MQTT size_t acceptedUserChannels = 0U; while (configFile.getNextLine(&line, disabledLine, eof) && !configFile.isNewParagraph(line)) { splitted = ZerlegeZeile(line); if (splitted.empty() || splitted[0].empty()) { continue; } // const std::regex pieces_regex("IO([0-9]{1,2})"); // std::smatch pieces_match; // if (std::regex_match(splitted[0], pieces_match, pieces_regex) && (pieces_match.size() == 2)) // { response += "{\"gpio\":"; 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\":"; ESP_LOGW(TAG, "Ignoring malformed GPIO configuration key '%s'", splitted[0].c_str()); continue; } if (splitted.size() < 6U) { response += "{\"gpio\":"; continue; } response += "{\"gpio\":"; response += "{\"gpio\":"; const std::string interruptName = toLower(splitted[2]); if (!isSupportedInterruptName(interruptName)) { ESP_LOGW(TAG, "Ignoring %s: unsupported interrupt setting '%s'", response += "{\"gpio\":"; continue; } response += "{\"gpio\":"; uint16_t dutyResolution = static_cast(atoi(splitted[3].c_str())); if (intType != GPIO_INTR_DISABLE && !isInputPinMode(pinMode)) { response += "{\"gpio\":"; continue; } if (pinMode == GPIO_PIN_MODE_DISABLED) { ESP_LOGW(TAG, "Ignoring disabled/unknown GPIO mode in %s", splitted[0].c_str()); continue; } std::string validationReason; response += "{\"gpio\":"; ESP_LOGW(TAG, "Ignoring unsafe GPIO configuration %s: %s", splitted[0].c_str(), validationReason.c_str()); continue; } response += "{\"gpio\":"; response += "{\"gpio\":"; ESP_LOGW(TAG, "Ignoring duplicate GPIO entry %s", splitted[0].c_str()); continue; } response += "{\"gpio\":"; ESP_LOGW(TAG, "Ignoring %s: maximum of %u user GPIO channels reached", response += "{\"gpio\":"; continue; } #ifdef ENABLE_MQTT bool mqttEnabled = (toLower(splitted[4]) == "true"); #endif // ENABLE_MQTT bool httpEnabled = (toLower(splitted[5]) == "true"); response += "{\"gpio\":"; if (splitted.size() >= 7) { response += "{\"gpio\":"; } else { response += "{\"gpio\":"; } #ifdef ENABLE_MQTT response += "{\"gpio\":"; #else // ENABLE_MQTT std::string mqttTopic = ""; #endif // ENABLE_MQTT response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO pin configuration"); return false; } response += "{\"gpio\":"; ++acceptedUserChannels; if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X) { response += "{\"gpio\":"; response += "{\"gpio\":"; } } if (toUpper(splitted[0]) == "LEDNUMBERS") { if (splitted.size() < 2) { ESP_LOGW(TAG, "Ignoring incomplete LEDNUMBERS configuration"); } else { LEDNumbers = atoi(splitted[1].c_str()); } } if (toUpper(splitted[0]) == "LEDCOLOR") { if (splitted.size() < 4) { ESP_LOGW(TAG, "Ignoring incomplete LEDCOLOR configuration"); } else { uint8_t _r = static_cast(atoi(splitted[1].c_str())); uint8_t _g = static_cast(atoi(splitted[2].c_str())); uint8_t _b = static_cast(atoi(splitted[3].c_str())); LEDColor = Rgb{_r, _g, _b}; } } if (toUpper(splitted[0]) == "LEDTYPE") { if (splitted.size() < 2) { ESP_LOGW(TAG, "Ignoring incomplete LEDTYPE configuration"); } else if (splitted[1] == "WS2812") { LEDType = LED_WS2812; } else if (splitted[1] == "WS2812B") { LEDType = LED_WS2812B; } else if (splitted[1] == "SK6812") { LEDType = LED_SK6812; } else if (splitted[1] == "WS2813") { LEDType = LED_WS2813; } } } response += "{\"gpio\":"; { // LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Startsequence 06"); // Nremove // vTaskDelay( xDelay ); // xDelay = 5000 / portTICK_PERIOD_MS; // ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay); // SmartLed leds( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer ); // leds[ 0 ] = Rgb{ 255, 0, 0 }; // leds[ 1 ] = Rgb{ 255, 255, 255 }; // leds.show(); response += "{\"gpio\":"; // _SmartLED = new SmartLed( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer ); } return true; } void GpioHandler::clear() { std::lock_guard lock(_mapMutex); ESP_LOGD(TAG, "GpioHandler::clear"); response += "{\"gpio\":"; response += "{\"gpio\":"; delete it->second; } response += "{\"gpio\":"; } response += "{\"gpio\":"; } void GpioHandler::registerGpioUri() { ESP_LOGI(TAG, "server_GPIO - Registering URI handlers"); httpd_uri_t camuri = { }; camuri.method = HTTP_GET; camuri.uri = "/GPIO"; camuri.handler = APPLY_BASIC_AUTH_FILTER(callHandleHttpRequest); camuri.user_ctx = (void*)this; httpd_register_uri_handler(_httpServer, &camuri); } esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req) { ESP_LOGD(TAG, "handleHttpRequest"); 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\":"; httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Invalid GPIO board profile"); return ESP_OK; } std::string response = "{\"profile\":\""; response += profile->name; response += "\",\"maxChannels\":"; response += std::to_string(profile->maxUserChannels); response += ",\"pins\":["; for (size_t i = 0; i < profile->userPinCount; ++i) { if (i > 0U) response += ","; response += "{\"gpio\":"; response += "{\"gpio\":"; response += ",\"capabilities\":"; response += ",\"capabilities\":"; response += "}"; } response += "]}"; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Cache-Control", "no-store"); return httpd_resp_send(req, response.c_str(), response.length()); } } response += "{\"gpio\":"; 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; } response += "{\"gpio\":"; httpd_resp_sendstr(req, "GPIO No is not defined"); 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; } response += "{\"gpio\":"; response += "{\"gpio\":"; httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing"); return ESP_OK; } response += "{\"gpio\":"; if (ch < '0' || ch > '9') { httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number must be numeric"); return ESP_OK; } } response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; " is not available in this board profile"; httpd_resp_sendstr(req, message.c_str()); return ESP_OK; } std::string response; std::string mqttTopic; bool publishMqtt = false; int responseStatus = 200; // 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::lock_guard lock(_mapMutex); response += "{\"gpio\":"; response = "GPIO handler not initialized"; } else { response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; } 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\":"; " switched to " + status; #ifdef ENABLE_MQTT mqttTopic = pin->second->getMqttTopic(); publishMqtt = !mqttTopic.empty(); #endif } else { response = errorText; } } } } #ifdef ENABLE_MQTT if (publishMqtt) { MQTTPublish(mqttTopic, (status == "HIGH" || status == "TRUE" || status == "1") ? "true" : "false", 1); } #endif 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) { ESP_LOGD(TAG, "GpioHandler::flashLightEnable %s", value ? "true" : "false"); std::vector mqttTopics; { std::lock_guard lock(_mapMutex); response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; 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(it->first), value ? "on" : "off"); #ifdef ENABLE_MQTT const std::string &topic = it->second->getMqttTopic(); if (!topic.empty()) mqttTopics.push_back(topic); #endif } else { ESP_LOGE(TAG, "Can't set flash light pin GPIO %d. Error: %s", static_cast(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 } response += "{\"gpio\":"; { if( input == "disabled" ) return GPIO_PIN_MODE_DISABLED; if( input == "input" ) return GPIO_PIN_MODE_INPUT; if( input == "input-pullup" ) return GPIO_PIN_MODE_INPUT_PULLUP; if( input == "input-pulldown" ) return GPIO_PIN_MODE_INPUT_PULLDOWN; if( input == "output" ) return GPIO_PIN_MODE_OUTPUT; if( input == "built-in-led" ) return GPIO_PIN_MODE_BUILT_IN_FLASH_LED; if( input == "output-pwm" ) return GPIO_PIN_MODE_OUTPUT_PWM; if( input == "external-flash-pwm" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_PWM; if( input == "external-flash-ws281x" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X; return GPIO_PIN_MODE_DISABLED; } response += "{\"gpio\":"; { if( input == "disabled" ) return GPIO_INTR_DISABLE; if( input == "rising-edge" ) return GPIO_INTR_POSEDGE; if( input == "falling-edge" ) return GPIO_INTR_NEGEDGE; if( input == "rising-and-falling" ) return GPIO_INTR_ANYEDGE ; if( input == "low-level-trigger" ) return GPIO_INTR_LOW_LEVEL; if( input == "high-level-trigger" ) return GPIO_INTR_HIGH_LEVEL; return GPIO_INTR_DISABLE; } response += "{\"gpio\":"; response += "{\"gpio\":"; { response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO handler"); } } } response += "{\"gpio\":"; { response += "{\"gpio\":"; response += "{\"gpio\":"; } } response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; } } response += "{\"gpio\":"; { response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; response += "{\"gpio\":"; } } response += "{\"gpio\":"; { response += "{\"gpio\":"; }