#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" #include "board_gpio_profile.h" #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"; static bool parseUserGpioKey(const std::string &key, gpio_num_t *gpio) { if (gpio == NULL || key.size() < 3U || key.size() > 4U || 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; } *gpio = static_cast(value); 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"; } 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; } static uint8_t requiredCapabilitiesForPinMode(gpio_pin_mode_t mode) { 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; } } 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); 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; if (!gpioBoardPinSupports(gpio, required)) { if (reason != NULL) *reason = "GPIO is not whitelisted for this board or requested mode"; return false; } return true; } 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) { _gpio = gpio; _name = (name != NULL) ? name : ""; _mode = mode; _interruptType = interruptType; _mqttTopic = mqttTopic; _httpEnable = httpEnable; } GpioPin::~GpioPin() { ESP_LOGD(TAG,"reset GPIO pin %d", _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. gpio_isr_handler_remove(_gpio); _isrRegistered = false; } gpio_reset_pin(_gpio); } static void IRAM_ATTR gpio_isr_handler(void *arg) { GpioIsrContext *context = static_cast(arg); if (context == NULL || context->eventQueue == NULL) { return; } GpioResult result = {}; result.gpio = context->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(); } } void GpioPin::gpioInterrupt(int value) { #ifdef ENABLE_MQTT if (!_mqttTopic.empty()) { ESP_LOGD(TAG, "gpioInterrupt %s %d", _mqttTopic.c_str(), value); 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) { ESP_LOGE(TAG, "No event queue available for GPIO%d interrupt", static_cast(_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; io_conf.pin_bit_mask = (1ULL << static_cast(_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; const esp_err_t configResult = gpio_config(&io_conf); if (configResult != ESP_OK) { ESP_LOGE(TAG, "gpio_config failed for GPIO%d: %s", static_cast(_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) { //hook isr handler for specific gpio pin ESP_LOGD(TAG, "GpioPin::init add isr handler for GPIO %d", _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(_gpio), esp_err_to_name(isrResult)); 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"; } return gpio_get_level(_gpio) == 1; } 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 { gpio_set_level(_gpio, value); #ifdef ENABLE_MQTT if (publishMqtt && !_mqttTopic.empty() && setSource != GPIO_SET_SOURCE_MQTT) { MQTTPublish(_mqttTopic, value ? "true" : "false", 1); } #endif // ENABLE_MQTT } } void GpioPin::publishState() { const int newState = gpio_get_level(_gpio); const int previousState = currentState.exchange(newState, std::memory_order_relaxed); if (newState != previousState) { 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); } #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"); GpioHandler *gpioHandler = (GpioHandler*)req->user_ctx; return gpioHandler->handleHttpRequest(req); } 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(); if (gpioMap != NULL) { delete gpioMap; gpioMap = NULL; } } 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); if (gpioMap == NULL) { gpioMap = new (std::nothrow) std::map(); if (gpioMap == NULL) { 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(); delete gpioMap; gpioMap = NULL; _isEnabled = false; ESP_LOGI(TAG, "GPIO init completed, handler is disabled"); return; } // An empty board whitelist (or no enabled user pins) needs no queue or worker. if (gpioMap->empty()) { _isEnabled = false; ESP_LOGI(TAG, "GPIO handler disabled: no user GPIO pins are configured or available"); 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; for (std::map::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; } } { std::lock_guard lock(_mapMutex); for (std::map::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(it->first))); clear(); vSemaphoreDelete(_workerStopped); _workerStopped = NULL; vQueueDelete(_eventQueue); _eventQueue = NULL; _isEnabled = false; return; } } } _isEnabled = true; const BaseType_t taskResult = xTaskCreate(&GpioHandler::taskEntry, "gpio_int", 3 * 1024, 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); MQTTregisterConnectFunction("gpio-handler", f); #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. if (gpioMap != NULL) { for(std::map::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) { 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. if (gpioMap != NULL) { for(std::map::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(); } } } #endif //ENABLE_MQTT void GpioHandler::deinit() { _isEnabled = false; #ifdef ENABLE_MQTT MQTTunregisterConnectFunction("gpio-handler"); #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 { result.value = gpio_get_level(result.gpio); 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) { // The worker is stopped and joined before deinit() mutates or frees gpioMap. // Avoid holding _mapMutex across the MQTT publish performed by GpioPin. if ((gpioMap != NULL) && (gpioMap->find(gpioResult->gpio) != gpioMap->end())) { (*gpioMap)[gpioResult->gpio]->gpioInterrupt(gpioResult->value); } } bool GpioHandler::readConfig() { std::lock_guard lock(_mapMutex); if (!gpioMap->empty()) clear(); ConfigFile configFile = ConfigFile(_configFile); std::vector splitted; std::string line = ""; bool disabledLine = false; bool eof = false; gpio_num_t gpioExtLED = (gpio_num_t) 0; // 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; if (!gpioBoardProfileIsValid()) { 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)) // { // 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) { 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) { ESP_LOGW(TAG, "Ignoring incomplete GPIO configuration for %s", gpioKey.c_str()); continue; } 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'", gpioKey.c_str(), interruptName.c_str()); continue; } gpio_int_type_t intType = resolveIntType(interruptName); uint16_t dutyResolution = static_cast(atoi(splitted[3].c_str())); if (intType != GPIO_INTR_DISABLE && !isInputPinMode(pinMode)) { ESP_LOGW(TAG, "Ignoring %s: interrupts are only valid for input modes", gpioKey.c_str()); 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; if (!isAllowedUserPinConfiguration(gpioNr, pinMode, intType, &validationReason)) { ESP_LOGW(TAG, "Ignoring unsafe GPIO configuration %s: %s", splitted[0].c_str(), validationReason.c_str()); continue; } const auto existingPin = gpioMap->find(gpioNr); if (existingPin != gpioMap->end()) { ESP_LOGW(TAG, "Ignoring duplicate GPIO entry %s", splitted[0].c_str()); continue; } if (acceptedUserChannels >= gpioGetBoardProfile()->maxUserChannels) { ESP_LOGW(TAG, "Ignoring %s: maximum of %u user GPIO channels reached", splitted[0].c_str(), static_cast(gpioGetBoardProfile()->maxUserChannels)); continue; } #ifdef ENABLE_MQTT bool mqttEnabled = (toLower(splitted[4]) == "true"); #endif // ENABLE_MQTT bool httpEnabled = (toLower(splitted[5]) == "true"); char gpioName[100]; if (splitted.size() >= 7) { strlcpy(gpioName, trim(splitted[6]).c_str(), sizeof(gpioName)); } else { sprintf(gpioName, "GPIO%d", gpioNr); } #ifdef ENABLE_MQTT std::string mqttTopic = mqttEnabled ? (mainTopicMQTT + "/" + gpioName) : ""; #else // ENABLE_MQTT std::string mqttTopic = ""; #endif // ENABLE_MQTT 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; } gpioMap->emplace(gpioNr, gpioPin); ++acceptedUserChannels; if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X) { ESP_LOGD(TAG, "Set WS2812 to GPIO %d", gpioNr); gpioExtLED = gpioNr; } } 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; } } } if (gpioExtLED > 0) { // 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(); // SmartLed leds = new SmartLed(LEDType, LEDNumbers, gpioExtLED, 0, DoubleBuffer); // _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"); if (gpioMap != NULL) { for(std::map::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) { delete it->second; } gpioMap->clear(); } // gpio_uninstall_isr_service(); can't uninstall, isr service is used by camera } 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) { 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; } 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 += std::to_string(static_cast(profile->userPins[i].gpio)); response += ",\\"capabilities\\":"; response += std::to_string(profile->userPins[i].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()); } } 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; } if (httpd_query_key_value(query, "GPIO", gpioText, sizeof(gpioText)) != ESP_OK) { 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; } const std::string gpio = gpioText; if (gpio.empty()) { httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing"); return ESP_OK; } 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; } } const int gpioNumber = atoi(gpio.c_str()); const gpio_num_t gpioNum = static_cast(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; } 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); 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; } } } } #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); if (gpioMap != NULL) { for (std::map::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(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 } 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; 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; } gpio_int_type_t GpioHandler::resolveIntType(std::string input) { 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; } static GpioHandler *gpioHandler = NULL; void gpio_handler_create(httpd_handle_t server) { 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"); } } } void gpio_handler_init() { if (gpioHandler != NULL) { gpioHandler->init(); } } void gpio_handler_deinit() { if (gpioHandler != NULL) { gpioHandler->deinit(); } } void gpio_handler_destroy() { if (gpioHandler != NULL) { gpio_handler_deinit(); delete gpioHandler; gpioHandler = NULL; } } GpioHandler* gpio_handler_get() { return gpioHandler; }