server_GPIO.cpp 24 KB

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