server_GPIO.cpp 32 KB

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