server_GPIO.cpp 27 KB

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