server_GPIO.cpp 26 KB

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