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