server_GPIO.cpp 29 KB

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