server_GPIO.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. #include <string>
  2. #include <functional>
  3. #include "string.h"
  4. #include <string.h>
  5. #include "freertos/FreeRTOS.h"
  6. #include "freertos/task.h"
  7. #include "freertos/queue.h"
  8. #include <new>
  9. #include "esp_system.h"
  10. #include "esp_log.h"
  11. #include <sys/stat.h>
  12. #include <vector>
  13. #include "../../include/defines.h"
  14. #include "server_GPIO.h"
  15. #include "board_gpio_profile.h"
  16. #include "ClassLogFile.h"
  17. #include "configFile.h"
  18. #include "Helper.h"
  19. #ifdef ENABLE_MQTT
  20. #include "interface_mqtt.h"
  21. #include "server_mqtt.h"
  22. #endif //ENABLE_MQTT
  23. #include "basic_auth.h"
  24. static const char *TAG = "GPIO";
  25. static bool parseUserGpioKey(const std::string &key, gpio_num_t *gpio)
  26. {
  27. if (gpio == NULL || key.size() < 3U || key.size() > 4U ||
  28. key.compare(0, 2, "IO") != 0) {
  29. return false;
  30. }
  31. int value = 0;
  32. for (size_t i = 2U; i < key.size(); ++i) {
  33. const char ch = key[i];
  34. if (ch < '0' || ch > '9') {
  35. return false;
  36. }
  37. value = (value * 10) + (ch - '0');
  38. }
  39. /* GPIO0..GPIO48 is the supported configuration namespace. */
  40. if (value < 0 || value > 48) {
  41. return false;
  42. }
  43. *gpio = static_cast<gpio_num_t>(value);
  44. return true;
  45. }
  46. static bool isSupportedInterruptName(const std::string &name)
  47. {
  48. return name == "disabled" ||
  49. name == "rising-edge" ||
  50. name == "falling-edge" ||
  51. name == "rising-and-falling" ||
  52. name == "low-level-trigger" ||
  53. name == "high-level-trigger";
  54. }
  55. static bool isInputPinMode(gpio_pin_mode_t mode)
  56. {
  57. return mode == GPIO_PIN_MODE_INPUT ||
  58. mode == GPIO_PIN_MODE_INPUT_PULLUP ||
  59. mode == GPIO_PIN_MODE_INPUT_PULLDOWN;
  60. }
  61. static uint8_t requiredCapabilitiesForPinMode(gpio_pin_mode_t mode)
  62. {
  63. switch (mode) {
  64. case GPIO_PIN_MODE_INPUT: return GPIO_PIN_CAP_INPUT;
  65. case GPIO_PIN_MODE_INPUT_PULLUP: return GPIO_PIN_CAP_INPUT | GPIO_PIN_CAP_PULL_UP;
  66. case GPIO_PIN_MODE_INPUT_PULLDOWN: return GPIO_PIN_CAP_INPUT | GPIO_PIN_CAP_PULL_DOWN;
  67. case GPIO_PIN_MODE_OUTPUT: return GPIO_PIN_CAP_OUTPUT;
  68. case GPIO_PIN_MODE_OUTPUT_PWM:
  69. /* PWM remains unavailable until a tested LEDC backend is implemented. */
  70. return 0U;
  71. default: return 0U;
  72. }
  73. }
  74. static bool isAllowedUserPinConfiguration(gpio_num_t gpio, gpio_pin_mode_t mode,
  75. gpio_int_type_t interruptType,
  76. std::string *reason)
  77. {
  78. uint8_t required = requiredCapabilitiesForPinMode(mode);
  79. if (required == 0U) {
  80. if (reason != NULL) *reason = "board-owned or unsupported GPIO mode";
  81. return false;
  82. }
  83. if (interruptType != GPIO_INTR_DISABLE) required |= GPIO_PIN_CAP_INTERRUPT;
  84. if (!gpioBoardPinSupports(gpio, required)) {
  85. if (reason != NULL) *reason = "GPIO is not whitelisted for this board or requested mode";
  86. return false;
  87. }
  88. return true;
  89. }
  90. 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)
  91. {
  92. _gpio = gpio;
  93. _name = (name != NULL) ? name : "";
  94. _mode = mode;
  95. _interruptType = interruptType;
  96. _mqttTopic = mqttTopic;
  97. _httpEnable = httpEnable;
  98. }
  99. GpioPin::~GpioPin()
  100. {
  101. ESP_LOGD(TAG,"reset GPIO pin %d", _gpio);
  102. #ifdef ENABLE_MQTT
  103. if (!_mqttTopic.empty()) {
  104. MQTTunregisterSubscribeFunction(_mqttTopic);
  105. }
  106. #endif // ENABLE_MQTT
  107. if (_isrRegistered) {
  108. // Remove only an ISR that was successfully installed for this pin.
  109. gpio_isr_handler_remove(_gpio);
  110. _isrRegistered = false;
  111. }
  112. gpio_reset_pin(_gpio);
  113. }
  114. static void IRAM_ATTR gpio_isr_handler(void *arg)
  115. {
  116. GpioIsrContext *context = static_cast<GpioIsrContext *>(arg);
  117. if (context == NULL || context->eventQueue == NULL) {
  118. return;
  119. }
  120. GpioResult result = {};
  121. result.gpio = context->gpio;
  122. // Read the pin level in task context; keep the IRAM ISR minimal.
  123. result.value = 0;
  124. result.stopEvent = false;
  125. BaseType_t higherPriorityTaskWoken = pdFALSE;
  126. if (xQueueSendFromISR(context->eventQueue, &result, &higherPriorityTaskWoken) == pdPASS &&
  127. higherPriorityTaskWoken == pdTRUE) {
  128. portYIELD_FROM_ISR();
  129. }
  130. }
  131. void GpioPin::gpioInterrupt(int value) {
  132. #ifdef ENABLE_MQTT
  133. if (!_mqttTopic.empty()) {
  134. ESP_LOGD(TAG, "gpioInterrupt %s %d", _mqttTopic.c_str(), value);
  135. MQTTPublish(_mqttTopic, value ? "true" : "false", 1);
  136. }
  137. #endif // ENABLE_MQTT
  138. currentState.store(value, std::memory_order_relaxed);
  139. }
  140. bool GpioPin::init(QueueHandle_t eventQueue)
  141. {
  142. if (_interruptType != GPIO_INTR_DISABLE && eventQueue == NULL) {
  143. ESP_LOGE(TAG, "No event queue available for GPIO%d interrupt", static_cast<int>(_gpio));
  144. return false;
  145. }
  146. gpio_config_t io_conf = {};
  147. io_conf.intr_type = _interruptType;
  148. io_conf.mode = (_mode == GPIO_PIN_MODE_OUTPUT) ? GPIO_MODE_OUTPUT : GPIO_MODE_INPUT;
  149. io_conf.pin_bit_mask = (1ULL << static_cast<unsigned int>(_gpio));
  150. io_conf.pull_down_en = (_mode == GPIO_PIN_MODE_INPUT_PULLDOWN) ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE;
  151. io_conf.pull_up_en = (_mode == GPIO_PIN_MODE_INPUT_PULLUP) ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
  152. const esp_err_t configResult = gpio_config(&io_conf);
  153. if (configResult != ESP_OK) {
  154. ESP_LOGE(TAG, "gpio_config failed for GPIO%d: %s", static_cast<int>(_gpio), esp_err_to_name(configResult));
  155. return false;
  156. }
  157. // 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.
  158. if (_interruptType != GPIO_INTR_DISABLE) {
  159. //hook isr handler for specific gpio pin
  160. ESP_LOGD(TAG, "GpioPin::init add isr handler for GPIO %d", _gpio);
  161. _isrContext.eventQueue = eventQueue;
  162. _isrContext.gpio = _gpio;
  163. const esp_err_t isrResult = gpio_isr_handler_add(_gpio, gpio_isr_handler, &_isrContext);
  164. if (isrResult != ESP_OK) {
  165. ESP_LOGE(TAG, "gpio_isr_handler_add failed for GPIO%d: %s",
  166. static_cast<int>(_gpio), esp_err_to_name(isrResult));
  167. return false;
  168. }
  169. _isrRegistered = true;
  170. }
  171. #ifdef ENABLE_MQTT
  172. if ((_mqttTopic.compare("") != 0) && ((_mode == GPIO_PIN_MODE_OUTPUT) || (_mode == GPIO_PIN_MODE_OUTPUT_PWM) || (_mode == GPIO_PIN_MODE_BUILT_IN_FLASH_LED))) {
  173. std::function<bool(std::string, char*, int)> f = std::bind(&GpioPin::handleMQTT, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
  174. MQTTregisterSubscribeFunction(_mqttTopic, f);
  175. }
  176. #endif //ENABLE_MQTT
  177. return true;
  178. }
  179. bool GpioPin::getValue(std::string* errorText)
  180. {
  181. if ((_mode != GPIO_PIN_MODE_INPUT) && (_mode != GPIO_PIN_MODE_INPUT_PULLUP) && (_mode != GPIO_PIN_MODE_INPUT_PULLDOWN)) {
  182. (*errorText) = "GPIO is not in input mode";
  183. }
  184. return gpio_get_level(_gpio) == 1;
  185. }
  186. void GpioPin::setValue(bool value, gpio_set_source setSource, std::string* errorText)
  187. {
  188. ESP_LOGD(TAG, "GpioPin::setValue %d", value);
  189. if ((_mode != GPIO_PIN_MODE_OUTPUT) && (_mode != GPIO_PIN_MODE_OUTPUT_PWM) && (_mode != GPIO_PIN_MODE_BUILT_IN_FLASH_LED)) {
  190. (*errorText) = "GPIO is not in output mode";
  191. } else {
  192. gpio_set_level(_gpio, value);
  193. #ifdef ENABLE_MQTT
  194. if ((_mqttTopic.compare("") != 0) && (setSource != GPIO_SET_SOURCE_MQTT)) {
  195. MQTTPublish(_mqttTopic, value ? "true" : "false", 1);
  196. }
  197. #endif //ENABLE_MQTT
  198. }
  199. }
  200. void GpioPin::publishState() {
  201. const int newState = gpio_get_level(_gpio);
  202. const int previousState = currentState.exchange(newState, std::memory_order_relaxed);
  203. if (newState != previousState) {
  204. ESP_LOGD(TAG, "publish state of GPIO %d new state %d", _gpio, newState);
  205. #ifdef ENABLE_MQTT
  206. if (!_mqttTopic.empty()) {
  207. MQTTPublish(_mqttTopic, newState ? "true" : "false", 1);
  208. }
  209. #endif // ENABLE_MQTT
  210. }
  211. }
  212. #ifdef ENABLE_MQTT
  213. bool GpioPin::handleMQTT(std::string, char* data, int data_len) {
  214. ESP_LOGD(TAG, "GpioPin::handleMQTT data %.*s", data_len, data);
  215. std::string dataStr(data, data_len);
  216. dataStr = toLower(dataStr);
  217. std::string errorText = "";
  218. if ((dataStr == "true") || (dataStr == "1")) {
  219. setValue(true, GPIO_SET_SOURCE_MQTT, &errorText);
  220. } else if ((dataStr == "false") || (dataStr == "0")) {
  221. setValue(false, GPIO_SET_SOURCE_MQTT, &errorText);
  222. } else {
  223. errorText = "wrong value ";
  224. errorText.append(data, data_len);
  225. }
  226. if (errorText != "") {
  227. ESP_LOGE(TAG, "%s", errorText.c_str());
  228. }
  229. return (errorText == "");
  230. }
  231. #endif //ENABLE_MQTT
  232. esp_err_t callHandleHttpRequest(httpd_req_t *req)
  233. {
  234. ESP_LOGD(TAG,"callHandleHttpRequest");
  235. GpioHandler *gpioHandler = (GpioHandler*)req->user_ctx;
  236. return gpioHandler->handleHttpRequest(req);
  237. }
  238. GpioHandler::GpioHandler(std::string configFile, httpd_handle_t httpServer)
  239. {
  240. ESP_LOGI(TAG,"start GpioHandler");
  241. _configFile = configFile;
  242. _httpServer = httpServer;
  243. ESP_LOGI(TAG, "register GPIO Uri");
  244. registerGpioUri();
  245. }
  246. GpioHandler::~GpioHandler() {
  247. deinit();
  248. if (gpioMap != NULL) {
  249. delete gpioMap;
  250. gpioMap = NULL;
  251. }
  252. }
  253. void GpioHandler::init()
  254. {
  255. ESP_LOGD(TAG, "*************** Start GPIOHandler_Init *****************");
  256. // Stop any previous task, queue and pin callbacks before rebuilding them.
  257. deinit();
  258. {
  259. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  260. if (gpioMap == NULL) {
  261. gpioMap = new (std::nothrow) std::map<gpio_num_t, GpioPin*>();
  262. if (gpioMap == NULL) {
  263. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO map");
  264. _isEnabled = false;
  265. return;
  266. }
  267. }
  268. }
  269. ESP_LOGI(TAG, "read GPIO config and init GPIO");
  270. if (!readConfig()) {
  271. clear();
  272. delete gpioMap;
  273. gpioMap = NULL;
  274. _isEnabled = false;
  275. ESP_LOGI(TAG, "GPIO init completed, handler is disabled");
  276. return;
  277. }
  278. // An empty board whitelist (or no enabled user pins) needs no queue or worker.
  279. if (gpioMap->empty()) {
  280. _isEnabled = false;
  281. ESP_LOGI(TAG, "GPIO handler disabled: no user GPIO pins are configured or available");
  282. return;
  283. }
  284. // Each handler owns its queue; ISR callbacks never use a process-global queue.
  285. _eventQueue = xQueueCreate(16, sizeof(GpioResult));
  286. if (_eventQueue == NULL) {
  287. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO event queue");
  288. clear();
  289. _isEnabled = false;
  290. return;
  291. }
  292. _workerStopped = xSemaphoreCreateBinary();
  293. if (_workerStopped == NULL) {
  294. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO worker stop semaphore");
  295. vQueueDelete(_eventQueue);
  296. _eventQueue = NULL;
  297. clear();
  298. _isEnabled = false;
  299. return;
  300. }
  301. bool needsIsr = false;
  302. for (std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  303. if (it->second->getInterruptType() != GPIO_INTR_DISABLE) needsIsr = true;
  304. }
  305. if (needsIsr) {
  306. const esp_err_t isrServiceResult = gpio_install_isr_service(ESP_INTR_FLAG_LOWMED | ESP_INTR_FLAG_IRAM);
  307. if (isrServiceResult != ESP_OK && isrServiceResult != ESP_ERR_INVALID_STATE) {
  308. ESP_LOGE(TAG, "Unable to install GPIO ISR service: %s", esp_err_to_name(isrServiceResult));
  309. clear();
  310. vSemaphoreDelete(_workerStopped);
  311. _workerStopped = NULL;
  312. vQueueDelete(_eventQueue);
  313. _eventQueue = NULL;
  314. _isEnabled = false;
  315. return;
  316. }
  317. }
  318. {
  319. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  320. for (std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  321. if (!it->second->init(_eventQueue)) {
  322. LogFile.WriteToFile(ESP_LOG_ERROR, TAG,
  323. "GPIO initialization failed for GPIO" + std::to_string(static_cast<int>(it->first)));
  324. clear();
  325. vSemaphoreDelete(_workerStopped);
  326. _workerStopped = NULL;
  327. vQueueDelete(_eventQueue);
  328. _eventQueue = NULL;
  329. _isEnabled = false;
  330. return;
  331. }
  332. }
  333. }
  334. _isEnabled = true;
  335. const BaseType_t taskResult = xTaskCreate(&GpioHandler::taskEntry, "gpio_int", 3 * 1024,
  336. this, tskIDLE_PRIORITY + 4, &_workerTask);
  337. if (taskResult != pdPASS) {
  338. _workerTask = NULL;
  339. _isEnabled = false;
  340. clear();
  341. vSemaphoreDelete(_workerStopped);
  342. _workerStopped = NULL;
  343. vQueueDelete(_eventQueue);
  344. _eventQueue = NULL;
  345. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to create GPIO handler task");
  346. return;
  347. }
  348. #ifdef ENABLE_MQTT
  349. std::function<void()> f = std::bind(&GpioHandler::handleMQTTconnect, this);
  350. MQTTregisterConnectFunction("gpio-handler", f);
  351. #endif
  352. ESP_LOGI(TAG, "GPIO init completed, is enabled");
  353. }
  354. void GpioHandler::taskHandler() {
  355. // The map is immutable while the worker is running. deinit() stops and joins
  356. // this worker before clearing the map. Do not hold _mapMutex while publishing
  357. // to MQTT: the MQTT client may wait on its event task, which can run callbacks.
  358. if (gpioMap != NULL) {
  359. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  360. if ((it->second->getInterruptType() == GPIO_INTR_DISABLE))
  361. it->second->publishState();
  362. }
  363. }
  364. }
  365. #ifdef ENABLE_MQTT
  366. void GpioHandler::handleMQTTconnect()
  367. {
  368. // MQTTconnected() invokes this while holding connectFunctionMutex. Keep the
  369. // GPIO map lock out of synchronous MQTT publishing to avoid lock inversion.
  370. // deinit() unregisters this callback before clearing the map.
  371. if (gpioMap != NULL) {
  372. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  373. if ((it->second->getMode() == GPIO_PIN_MODE_INPUT) || (it->second->getMode() == GPIO_PIN_MODE_INPUT_PULLDOWN) || (it->second->getMode() == GPIO_PIN_MODE_INPUT_PULLUP))
  374. it->second->publishState();
  375. }
  376. }
  377. }
  378. #endif //ENABLE_MQTT
  379. void GpioHandler::deinit() {
  380. _isEnabled = false;
  381. #ifdef ENABLE_MQTT
  382. MQTTunregisterConnectFunction("gpio-handler");
  383. #endif
  384. // Wake the worker and wait until it has stopped using the handler.
  385. if (_workerTask != NULL && _eventQueue != NULL) {
  386. GpioResult stop = {};
  387. stop.stopEvent = true;
  388. if (xQueueSend(_eventQueue, &stop, pdMS_TO_TICKS(1000)) != pdPASS) {
  389. ESP_LOGW(TAG, "GPIO worker queue full while stopping; waiting for next queue slot");
  390. xQueueSend(_eventQueue, &stop, portMAX_DELAY);
  391. }
  392. if (_workerStopped != NULL) {
  393. xSemaphoreTake(_workerStopped, portMAX_DELAY);
  394. }
  395. _workerTask = NULL;
  396. }
  397. #ifdef __LEDGLOBAL
  398. if (leds_global != NULL) {
  399. leds_global->wait();
  400. delete leds_global;
  401. leds_global = NULL;
  402. }
  403. #endif
  404. {
  405. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  406. clear();
  407. }
  408. if (_workerStopped != NULL) {
  409. vSemaphoreDelete(_workerStopped);
  410. _workerStopped = NULL;
  411. }
  412. if (_eventQueue != NULL) {
  413. vQueueDelete(_eventQueue);
  414. _eventQueue = NULL;
  415. }
  416. }
  417. void GpioHandler::taskEntry(void *arg) {
  418. static_cast<GpioHandler *>(arg)->workerLoop();
  419. }
  420. void GpioHandler::workerLoop() {
  421. ESP_LOGD(TAG, "GPIO worker started");
  422. bool running = true;
  423. TickType_t lastPoll = xTaskGetTickCount();
  424. while (running) {
  425. GpioResult result = {};
  426. if (xQueueReceive(_eventQueue, &result, pdMS_TO_TICKS(250)) == pdPASS) {
  427. if (result.stopEvent) {
  428. running = false;
  429. } else {
  430. result.value = gpio_get_level(result.gpio);
  431. gpioInterrupt(&result);
  432. }
  433. }
  434. const TickType_t now = xTaskGetTickCount();
  435. if (running && (now - lastPoll) >= pdMS_TO_TICKS(1000)) {
  436. taskHandler();
  437. lastPoll = now;
  438. }
  439. }
  440. ESP_LOGD(TAG, "GPIO worker stopped");
  441. if (_workerStopped != NULL) xSemaphoreGive(_workerStopped);
  442. vTaskDelete(NULL);
  443. }
  444. void GpioHandler::gpioInterrupt(GpioResult* gpioResult) {
  445. // The worker is stopped and joined before deinit() mutates or frees gpioMap.
  446. // Avoid holding _mapMutex across the MQTT publish performed by GpioPin.
  447. if ((gpioMap != NULL) && (gpioMap->find(gpioResult->gpio) != gpioMap->end())) {
  448. (*gpioMap)[gpioResult->gpio]->gpioInterrupt(gpioResult->value);
  449. }
  450. }
  451. bool GpioHandler::readConfig()
  452. {
  453. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  454. if (!gpioMap->empty())
  455. clear();
  456. ConfigFile configFile = ConfigFile(_configFile);
  457. std::vector<std::string> splitted;
  458. std::string line = "";
  459. bool disabledLine = false;
  460. bool eof = false;
  461. gpio_num_t gpioExtLED = (gpio_num_t) 0;
  462. // ESP_LOGD(TAG, "readConfig - Start 1");
  463. while ((!configFile.GetNextParagraph(line, disabledLine, eof) || (line.compare("[GPIO]") != 0)) && !eof) {}
  464. if (eof)
  465. return false;
  466. // ESP_LOGD(TAG, "readConfig - Start 2 line: %s, disabbledLine: %d", line.c_str(), (int) disabledLine);
  467. _isEnabled = !disabledLine;
  468. if (!_isEnabled)
  469. return false;
  470. if (!gpioBoardProfileIsValid()) {
  471. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "GPIO disabled: invalid board GPIO profile");
  472. return false;
  473. }
  474. // ESP_LOGD(TAG, "readConfig - Start 3");
  475. #ifdef ENABLE_MQTT
  476. // std::string mainTopicMQTT = "";
  477. std::string mainTopicMQTT = mqttServer_getMainTopic();
  478. if (mainTopicMQTT.length() > 0)
  479. {
  480. mainTopicMQTT = mainTopicMQTT + "/GPIO";
  481. ESP_LOGD(TAG, "MAINTOPICMQTT found");
  482. }
  483. #endif // ENABLE_MQTT
  484. size_t acceptedUserChannels = 0U;
  485. while (configFile.getNextLine(&line, disabledLine, eof) && !configFile.isNewParagraph(line))
  486. {
  487. splitted = ZerlegeZeile(line);
  488. if (splitted.empty() || splitted[0].empty()) {
  489. continue;
  490. }
  491. // const std::regex pieces_regex("IO([0-9]{1,2})");
  492. // std::smatch pieces_match;
  493. // if (std::regex_match(splitted[0], pieces_match, pieces_regex) && (pieces_match.size() == 2))
  494. // {
  495. // std::string gpioStr = pieces_match[1];
  496. ESP_LOGD(TAG, "conf param %s", toUpper(splitted[0]).c_str());
  497. if (toUpper(splitted[0]) == "MAINTOPICMQTT") {
  498. // ESP_LOGD(TAG, "MAINTOPICMQTT found");
  499. // mainTopicMQTT = splitted[1];
  500. } else if (toUpper(splitted[0]).rfind("IO", 0) == 0)
  501. {
  502. gpio_num_t gpioNr = GPIO_NUM_NC;
  503. const std::string gpioKey = toUpper(splitted[0]);
  504. if (!parseUserGpioKey(gpioKey, &gpioNr)) {
  505. ESP_LOGW(TAG, "Ignoring malformed GPIO configuration key '%s'", splitted[0].c_str());
  506. continue;
  507. }
  508. if (splitted.size() < 6U) {
  509. ESP_LOGW(TAG, "Ignoring incomplete GPIO configuration for %s", gpioKey.c_str());
  510. continue;
  511. }
  512. ESP_LOGI(TAG,"Enable %s in %s mode", gpioKey.c_str(), splitted[1].c_str());
  513. gpio_pin_mode_t pinMode = resolvePinMode(toLower(splitted[1]));
  514. const std::string interruptName = toLower(splitted[2]);
  515. if (!isSupportedInterruptName(interruptName)) {
  516. ESP_LOGW(TAG, "Ignoring %s: unsupported interrupt setting '%s'",
  517. gpioKey.c_str(), interruptName.c_str());
  518. continue;
  519. }
  520. gpio_int_type_t intType = resolveIntType(interruptName);
  521. uint16_t dutyResolution = static_cast<uint8_t>(atoi(splitted[3].c_str()));
  522. if (intType != GPIO_INTR_DISABLE && !isInputPinMode(pinMode)) {
  523. ESP_LOGW(TAG, "Ignoring %s: interrupts are only valid for input modes", gpioKey.c_str());
  524. continue;
  525. }
  526. if (pinMode == GPIO_PIN_MODE_DISABLED) {
  527. ESP_LOGW(TAG, "Ignoring disabled/unknown GPIO mode in %s", splitted[0].c_str());
  528. continue;
  529. }
  530. std::string validationReason;
  531. if (!isAllowedUserPinConfiguration(gpioNr, pinMode, intType, &validationReason)) {
  532. ESP_LOGW(TAG, "Ignoring unsafe GPIO configuration %s: %s", splitted[0].c_str(), validationReason.c_str());
  533. continue;
  534. }
  535. const auto existingPin = gpioMap->find(gpioNr);
  536. if (existingPin != gpioMap->end()) {
  537. ESP_LOGW(TAG, "Ignoring duplicate GPIO entry %s", splitted[0].c_str());
  538. continue;
  539. }
  540. if (acceptedUserChannels >= gpioGetBoardProfile()->maxUserChannels) {
  541. ESP_LOGW(TAG, "Ignoring %s: maximum of %u user GPIO channels reached",
  542. splitted[0].c_str(), static_cast<unsigned int>(gpioGetBoardProfile()->maxUserChannels));
  543. continue;
  544. }
  545. #ifdef ENABLE_MQTT
  546. bool mqttEnabled = (toLower(splitted[4]) == "true");
  547. #endif // ENABLE_MQTT
  548. bool httpEnabled = (toLower(splitted[5]) == "true");
  549. char gpioName[100];
  550. if (splitted.size() >= 7) {
  551. strlcpy(gpioName, trim(splitted[6]).c_str(), sizeof(gpioName));
  552. } else {
  553. sprintf(gpioName, "GPIO%d", gpioNr);
  554. }
  555. #ifdef ENABLE_MQTT
  556. std::string mqttTopic = mqttEnabled ? (mainTopicMQTT + "/" + gpioName) : "";
  557. #else // ENABLE_MQTT
  558. std::string mqttTopic = "";
  559. #endif // ENABLE_MQTT
  560. GpioPin* gpioPin = new (std::nothrow) GpioPin(
  561. gpioNr, gpioName, pinMode, intType, dutyResolution, mqttTopic, httpEnabled);
  562. if (gpioPin == NULL) {
  563. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO pin configuration");
  564. return false;
  565. }
  566. gpioMap->emplace(gpioNr, gpioPin);
  567. ++acceptedUserChannels;
  568. if (pinMode == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
  569. {
  570. ESP_LOGD(TAG, "Set WS2812 to GPIO %d", gpioNr);
  571. gpioExtLED = gpioNr;
  572. }
  573. }
  574. if (toUpper(splitted[0]) == "LEDNUMBERS")
  575. {
  576. if (splitted.size() < 2) {
  577. ESP_LOGW(TAG, "Ignoring incomplete LEDNUMBERS configuration");
  578. } else {
  579. LEDNumbers = atoi(splitted[1].c_str());
  580. }
  581. }
  582. if (toUpper(splitted[0]) == "LEDCOLOR")
  583. {
  584. if (splitted.size() < 4) {
  585. ESP_LOGW(TAG, "Ignoring incomplete LEDCOLOR configuration");
  586. } else {
  587. uint8_t _r = static_cast<uint8_t>(atoi(splitted[1].c_str()));
  588. uint8_t _g = static_cast<uint8_t>(atoi(splitted[2].c_str()));
  589. uint8_t _b = static_cast<uint8_t>(atoi(splitted[3].c_str()));
  590. LEDColor = Rgb{_r, _g, _b};
  591. }
  592. }
  593. if (toUpper(splitted[0]) == "LEDTYPE")
  594. {
  595. if (splitted.size() < 2) {
  596. ESP_LOGW(TAG, "Ignoring incomplete LEDTYPE configuration");
  597. } else if (splitted[1] == "WS2812") {
  598. LEDType = LED_WS2812;
  599. } else if (splitted[1] == "WS2812B") {
  600. LEDType = LED_WS2812B;
  601. } else if (splitted[1] == "SK6812") {
  602. LEDType = LED_SK6812;
  603. } else if (splitted[1] == "WS2813") {
  604. LEDType = LED_WS2813;
  605. }
  606. }
  607. }
  608. if (gpioExtLED > 0)
  609. {
  610. // LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Startsequence 06"); // Nremove
  611. // vTaskDelay( xDelay );
  612. // xDelay = 5000 / portTICK_PERIOD_MS;
  613. // ESP_LOGD(TAG, "main: sleep for: %ldms", (long) xDelay);
  614. // SmartLed leds( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer );
  615. // leds[ 0 ] = Rgb{ 255, 0, 0 };
  616. // leds[ 1 ] = Rgb{ 255, 255, 255 };
  617. // leds.show();
  618. // SmartLed leds = new SmartLed(LEDType, LEDNumbers, gpioExtLED, 0, DoubleBuffer);
  619. // _SmartLED = new SmartLed( LED_WS2812, 2, GPIO_NUM_12, 0, DoubleBuffer );
  620. }
  621. return true;
  622. }
  623. void GpioHandler::clear()
  624. {
  625. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  626. ESP_LOGD(TAG, "GpioHandler::clear");
  627. if (gpioMap != NULL) {
  628. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it) {
  629. delete it->second;
  630. }
  631. gpioMap->clear();
  632. }
  633. // gpio_uninstall_isr_service(); can't uninstall, isr service is used by camera
  634. }
  635. void GpioHandler::registerGpioUri()
  636. {
  637. ESP_LOGI(TAG, "server_GPIO - Registering URI handlers");
  638. httpd_uri_t camuri = { };
  639. camuri.method = HTTP_GET;
  640. camuri.uri = "/GPIO";
  641. camuri.handler = APPLY_BASIC_AUTH_FILTER(callHandleHttpRequest);
  642. camuri.user_ctx = (void*)this;
  643. httpd_register_uri_handler(_httpServer, &camuri);
  644. }
  645. esp_err_t GpioHandler::handleHttpRequest(httpd_req_t *req)
  646. {
  647. ESP_LOGD(TAG, "handleHttpRequest");
  648. char _query[200];
  649. if (httpd_req_get_url_query_str(req, _query, sizeof(_query)) == ESP_OK) {
  650. char capabilitiesRequest[8] = {};
  651. if (httpd_query_key_value(_query, "capabilities", capabilitiesRequest,
  652. sizeof(capabilitiesRequest)) == ESP_OK &&
  653. strcmp(capabilitiesRequest, "1") == 0) {
  654. const GpioBoardProfile *profile = gpioGetBoardProfile();
  655. if (profile == NULL || !gpioBoardProfileIsValid()) {
  656. httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR,
  657. "Invalid GPIO board profile");
  658. return ESP_OK;
  659. }
  660. std::string response = "{\"profile\":\"";
  661. response += profile->name;
  662. response += "\",\"maxChannels\":";
  663. response += std::to_string(profile->maxUserChannels);
  664. response += ",\"pins\":[";
  665. for (size_t i = 0; i < profile->userPinCount; ++i) {
  666. if (i > 0U) response += ",";
  667. response += "{\"gpio\":";
  668. response += std::to_string(static_cast<int>(profile->userPins[i].gpio));
  669. response += ",\"capabilities\":";
  670. response += std::to_string(profile->userPins[i].capabilities);
  671. response += "}";
  672. }
  673. response += "]}";
  674. httpd_resp_set_type(req, "application/json");
  675. httpd_resp_set_hdr(req, "Cache-Control", "no-store");
  676. httpd_resp_send(req, response.c_str(), response.length());
  677. return ESP_OK;
  678. }
  679. }
  680. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  681. if (gpioMap == NULL) {
  682. httpd_resp_sendstr(req, "GPIO handler not initialized");
  683. return ESP_OK;
  684. }
  685. #ifdef DEBUG_DETAIL_ON
  686. LogFile.WriteHeapInfo("handler_switch_GPIO - Start");
  687. #endif
  688. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_switch_GPIO");
  689. char _valueGPIO[30];
  690. char _valueStatus[30];
  691. std::string gpio, status;
  692. if (httpd_req_get_url_query_str(req, _query, 200) == ESP_OK) {
  693. ESP_LOGD(TAG, "Query: %s", _query);
  694. if (httpd_query_key_value(_query, "GPIO", _valueGPIO, 30) == ESP_OK)
  695. {
  696. ESP_LOGD(TAG, "GPIO is found %s", _valueGPIO);
  697. gpio = std::string(_valueGPIO);
  698. } else {
  699. std::string resp_str = "GPIO No is not defined";
  700. httpd_resp_send(req, resp_str.c_str(), resp_str.length());
  701. return ESP_OK;
  702. }
  703. if (httpd_query_key_value(_query, "Status", _valueStatus, 30) == ESP_OK)
  704. {
  705. ESP_LOGD(TAG, "Status is found %s", _valueStatus);
  706. status = std::string(_valueStatus);
  707. }
  708. } else {
  709. const char* resp_str = "Error in call. Use /GPIO?GPIO=12&Status=high";
  710. httpd_resp_send(req, resp_str, strlen(resp_str));
  711. return ESP_OK;
  712. }
  713. status = toUpper(status);
  714. if ((status != "HIGH") && (status != "LOW") && (status != "TRUE") && (status != "FALSE") && (status != "0") && (status != "1") && (status != ""))
  715. {
  716. std::string zw = "Status not valid: " + status;
  717. httpd_resp_sendstr_chunk(req, zw.c_str());
  718. httpd_resp_sendstr_chunk(req, NULL);
  719. return ESP_OK;
  720. }
  721. if (gpio.empty()) {
  722. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number is missing");
  723. return ESP_OK;
  724. }
  725. for (size_t i = 0; i < gpio.length(); ++i) {
  726. if (gpio[i] < '0' || gpio[i] > '9') {
  727. httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "GPIO number must be numeric");
  728. return ESP_OK;
  729. }
  730. }
  731. const int gpionum = atoi(gpio.c_str());
  732. gpio_num_t gpio_num = static_cast<gpio_num_t>(gpionum);
  733. if (gpioBoardFindUserPin(gpio_num) == NULL)
  734. {
  735. std::string zw = "GPIO" + std::to_string(gpionum) + " is not available in this board profile";
  736. httpd_resp_sendstr_chunk(req, zw.c_str());
  737. httpd_resp_sendstr_chunk(req, NULL);
  738. return ESP_OK;
  739. }
  740. if (gpioMap->count(gpio_num) == 0) {
  741. char resp_str [30];
  742. sprintf(resp_str, "GPIO%d is not registred", gpio_num);
  743. httpd_resp_send(req, resp_str, strlen(resp_str));
  744. return ESP_OK;
  745. }
  746. if (!(*gpioMap)[gpio_num]->isHttpEnabled()) {
  747. httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "HTTP access is disabled for this GPIO");
  748. return ESP_OK;
  749. }
  750. if (status == "")
  751. {
  752. std::string resp_str = "";
  753. status = (*gpioMap)[gpio_num]->getValue(&resp_str) ? "HIGH" : "LOW";
  754. if (resp_str == "") {
  755. resp_str = status;
  756. }
  757. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  758. httpd_resp_sendstr_chunk(req, NULL);
  759. }
  760. else
  761. {
  762. std::string resp_str = "";
  763. (*gpioMap)[gpio_num]->setValue((status == "HIGH") || (status == "TRUE") || (status == "1"), GPIO_SET_SOURCE_HTTP, &resp_str);
  764. if (resp_str == "") {
  765. resp_str = "GPIO" + std::to_string(gpionum) + " switched to " + status;
  766. }
  767. httpd_resp_sendstr_chunk(req, resp_str.c_str());
  768. httpd_resp_sendstr_chunk(req, NULL);
  769. }
  770. return ESP_OK;
  771. };
  772. void GpioHandler::flashLightEnable(bool value)
  773. {
  774. std::lock_guard<std::recursive_mutex> lock(_mapMutex);
  775. ESP_LOGD(TAG, "GpioHandler::flashLightEnable %s", value ? "true" : "false");
  776. if (gpioMap != NULL) {
  777. for(std::map<gpio_num_t, GpioPin*>::iterator it = gpioMap->begin(); it != gpioMap->end(); ++it)
  778. {
  779. 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))
  780. {
  781. std::string resp_str = "";
  782. it->second->setValue(value, GPIO_SET_SOURCE_INTERNAL, &resp_str);
  783. if (resp_str == "") {
  784. ESP_LOGD(TAG, "Flash light pin GPIO %d switched to %s", (int)it->first, (value ? "on" : "off"));
  785. } else {
  786. ESP_LOGE(TAG, "Can't set flash light pin GPIO %d. Error: %s", (int)it->first, resp_str.c_str());
  787. }
  788. } else
  789. {
  790. if (it->second->getMode() == GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X)
  791. {
  792. #ifdef __LEDGLOBAL
  793. if (leds_global == NULL) {
  794. ESP_LOGI(TAG, "init SmartLed: LEDNumber=%d, GPIO=%d", LEDNumbers, (int)it->second->getGPIO());
  795. leds_global = new SmartLed( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
  796. } else {
  797. // wait until we can update: https://github.com/RoboticsBrno/SmartLeds/issues/10#issuecomment-386921623
  798. leds_global->wait();
  799. }
  800. #else
  801. SmartLed leds( LEDType, LEDNumbers, it->second->getGPIO(), 0, DoubleBuffer );
  802. #endif
  803. if (value)
  804. {
  805. for (int i = 0; i < LEDNumbers; ++i)
  806. #ifdef __LEDGLOBAL
  807. (*leds_global)[i] = LEDColor;
  808. #else
  809. leds[i] = LEDColor;
  810. #endif
  811. }
  812. else
  813. {
  814. for (int i = 0; i < LEDNumbers; ++i)
  815. #ifdef __LEDGLOBAL
  816. (*leds_global)[i] = Rgb{0, 0, 0};
  817. #else
  818. leds[i] = Rgb{0, 0, 0};
  819. #endif
  820. }
  821. #ifdef __LEDGLOBAL
  822. leds_global->show();
  823. #else
  824. leds.show();
  825. #endif
  826. }
  827. }
  828. }
  829. }
  830. }
  831. gpio_pin_mode_t GpioHandler::resolvePinMode(std::string input)
  832. {
  833. if( input == "disabled" ) return GPIO_PIN_MODE_DISABLED;
  834. if( input == "input" ) return GPIO_PIN_MODE_INPUT;
  835. if( input == "input-pullup" ) return GPIO_PIN_MODE_INPUT_PULLUP;
  836. if( input == "input-pulldown" ) return GPIO_PIN_MODE_INPUT_PULLDOWN;
  837. if( input == "output" ) return GPIO_PIN_MODE_OUTPUT;
  838. if( input == "built-in-led" ) return GPIO_PIN_MODE_BUILT_IN_FLASH_LED;
  839. if( input == "output-pwm" ) return GPIO_PIN_MODE_OUTPUT_PWM;
  840. if( input == "external-flash-pwm" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_PWM;
  841. if( input == "external-flash-ws281x" ) return GPIO_PIN_MODE_EXTERNAL_FLASH_WS281X;
  842. return GPIO_PIN_MODE_DISABLED;
  843. }
  844. gpio_int_type_t GpioHandler::resolveIntType(std::string input)
  845. {
  846. if( input == "disabled" ) return GPIO_INTR_DISABLE;
  847. if( input == "rising-edge" ) return GPIO_INTR_POSEDGE;
  848. if( input == "falling-edge" ) return GPIO_INTR_NEGEDGE;
  849. if( input == "rising-and-falling" ) return GPIO_INTR_ANYEDGE ;
  850. if( input == "low-level-trigger" ) return GPIO_INTR_LOW_LEVEL;
  851. if( input == "high-level-trigger" ) return GPIO_INTR_HIGH_LEVEL;
  852. return GPIO_INTR_DISABLE;
  853. }
  854. static GpioHandler *gpioHandler = NULL;
  855. void gpio_handler_create(httpd_handle_t server)
  856. {
  857. if (gpioHandler == NULL) {
  858. gpioHandler = new (std::nothrow) GpioHandler(CONFIG_FILE, server);
  859. if (gpioHandler == NULL) {
  860. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Unable to allocate GPIO handler");
  861. }
  862. }
  863. }
  864. void gpio_handler_init()
  865. {
  866. if (gpioHandler != NULL) {
  867. gpioHandler->init();
  868. }
  869. }
  870. void gpio_handler_deinit() {
  871. if (gpioHandler != NULL) {
  872. gpioHandler->deinit();
  873. }
  874. }
  875. void gpio_handler_destroy()
  876. {
  877. if (gpioHandler != NULL) {
  878. gpio_handler_deinit();
  879. delete gpioHandler;
  880. gpioHandler = NULL;
  881. }
  882. }
  883. GpioHandler* gpio_handler_get()
  884. {
  885. return gpioHandler;
  886. }